xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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(ArrayRef<concepts::Requirement *> Reqs,
553       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
554   concepts::TypeRequirement *
555   TransformTypeRequirement(concepts::TypeRequirement *Req);
556   concepts::ExprRequirement *
557   TransformExprRequirement(concepts::ExprRequirement *Req);
558   concepts::NestedRequirement *
559   TransformNestedRequirement(concepts::NestedRequirement *Req);
560 
561   /// Transform the given template name.
562   ///
563   /// \param SS The nested-name-specifier that qualifies the template
564   /// name. This nested-name-specifier must already have been transformed.
565   ///
566   /// \param Name The template name to transform.
567   ///
568   /// \param NameLoc The source location of the template name.
569   ///
570   /// \param ObjectType If we're translating a template name within a member
571   /// access expression, this is the type of the object whose member template
572   /// is being referenced.
573   ///
574   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
575   /// also refers to a name within the current (lexical) scope, this is the
576   /// declaration it refers to.
577   ///
578   /// By default, transforms the template name by transforming the declarations
579   /// and nested-name-specifiers that occur within the template name.
580   /// Subclasses may override this function to provide alternate behavior.
581   TemplateName
582   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
583                         SourceLocation NameLoc,
584                         QualType ObjectType = QualType(),
585                         NamedDecl *FirstQualifierInScope = nullptr,
586                         bool AllowInjectedClassName = false);
587 
588   /// Transform the given template argument.
589   ///
590   /// By default, this operation transforms the type, expression, or
591   /// declaration stored within the template argument and constructs a
592   /// new template argument from the transformed result. Subclasses may
593   /// override this function to provide alternate behavior.
594   ///
595   /// Returns true if there was an error.
596   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
597                                  TemplateArgumentLoc &Output,
598                                  bool Uneval = false);
599 
600   /// Transform the given set of template arguments.
601   ///
602   /// By default, this operation transforms all of the template arguments
603   /// in the input set using \c TransformTemplateArgument(), and appends
604   /// the transformed arguments to the output list.
605   ///
606   /// Note that this overload of \c TransformTemplateArguments() is merely
607   /// a convenience function. Subclasses that wish to override this behavior
608   /// should override the iterator-based member template version.
609   ///
610   /// \param Inputs The set of template arguments to be transformed.
611   ///
612   /// \param NumInputs The number of template arguments in \p Inputs.
613   ///
614   /// \param Outputs The set of transformed template arguments output by this
615   /// routine.
616   ///
617   /// Returns true if an error occurred.
618   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
619                                   unsigned NumInputs,
620                                   TemplateArgumentListInfo &Outputs,
621                                   bool Uneval = false) {
622     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
623                                       Uneval);
624   }
625 
626   /// Transform the given set of template arguments.
627   ///
628   /// By default, this operation transforms all of the template arguments
629   /// in the input set using \c TransformTemplateArgument(), and appends
630   /// the transformed arguments to the output list.
631   ///
632   /// \param First An iterator to the first template argument.
633   ///
634   /// \param Last An iterator one step past the last template argument.
635   ///
636   /// \param Outputs The set of transformed template arguments output by this
637   /// routine.
638   ///
639   /// Returns true if an error occurred.
640   template<typename InputIterator>
641   bool TransformTemplateArguments(InputIterator First,
642                                   InputIterator Last,
643                                   TemplateArgumentListInfo &Outputs,
644                                   bool Uneval = false);
645 
646   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
647   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
648                                  TemplateArgumentLoc &ArgLoc);
649 
650   /// Fakes up a TypeSourceInfo for a type.
651   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
652     return SemaRef.Context.getTrivialTypeSourceInfo(T,
653                        getDerived().getBaseLocation());
654   }
655 
656 #define ABSTRACT_TYPELOC(CLASS, PARENT)
657 #define TYPELOC(CLASS, PARENT)                                   \
658   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
659 #include "clang/AST/TypeLocNodes.def"
660 
661   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
662                                          TemplateTypeParmTypeLoc TL,
663                                          bool SuppressObjCLifetime);
664   QualType
665   TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
666                                          SubstTemplateTypeParmPackTypeLoc TL,
667                                          bool SuppressObjCLifetime);
668 
669   template<typename Fn>
670   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
671                                       FunctionProtoTypeLoc TL,
672                                       CXXRecordDecl *ThisContext,
673                                       Qualifiers ThisTypeQuals,
674                                       Fn TransformExceptionSpec);
675 
676   bool TransformExceptionSpec(SourceLocation Loc,
677                               FunctionProtoType::ExceptionSpecInfo &ESI,
678                               SmallVectorImpl<QualType> &Exceptions,
679                               bool &Changed);
680 
681   StmtResult TransformSEHHandler(Stmt *Handler);
682 
683   QualType
684   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
685                                       TemplateSpecializationTypeLoc TL,
686                                       TemplateName Template);
687 
688   QualType
689   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
690                                       DependentTemplateSpecializationTypeLoc TL,
691                                                TemplateName Template,
692                                                CXXScopeSpec &SS);
693 
694   QualType TransformDependentTemplateSpecializationType(
695       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
696       NestedNameSpecifierLoc QualifierLoc);
697 
698   /// Transforms the parameters of a function type into the
699   /// given vectors.
700   ///
701   /// The result vectors should be kept in sync; null entries in the
702   /// variables vector are acceptable.
703   ///
704   /// LastParamTransformed, if non-null, will be set to the index of the last
705   /// parameter on which transfromation was started. In the event of an error,
706   /// this will contain the parameter which failed to instantiate.
707   ///
708   /// Return true on error.
709   bool TransformFunctionTypeParams(
710       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
711       const QualType *ParamTypes,
712       const FunctionProtoType::ExtParameterInfo *ParamInfos,
713       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
714       Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
715 
716   bool TransformFunctionTypeParams(
717       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
718       const QualType *ParamTypes,
719       const FunctionProtoType::ExtParameterInfo *ParamInfos,
720       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
721       Sema::ExtParameterInfoBuilder &PInfos) {
722     return getDerived().TransformFunctionTypeParams(
723         Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos, nullptr);
724   }
725 
726   /// Transforms the parameters of a requires expresison into the given vectors.
727   ///
728   /// The result vectors should be kept in sync; null entries in the
729   /// variables vector are acceptable.
730   ///
731   /// Returns an unset ExprResult on success.  Returns an ExprResult the 'not
732   /// satisfied' RequiresExpr if subsitution failed, OR an ExprError, both of
733   /// which are cases where transformation shouldn't continue.
734   ExprResult TransformRequiresTypeParams(
735       SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
736       RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
737       SmallVectorImpl<QualType> &PTypes,
738       SmallVectorImpl<ParmVarDecl *> &TransParams,
739       Sema::ExtParameterInfoBuilder &PInfos) {
740     if (getDerived().TransformFunctionTypeParams(
741             KWLoc, Params, /*ParamTypes=*/nullptr,
742             /*ParamInfos=*/nullptr, PTypes, &TransParams, PInfos))
743       return ExprError();
744 
745     return ExprResult{};
746   }
747 
748   /// Transforms a single function-type parameter.  Return null
749   /// on error.
750   ///
751   /// \param indexAdjustment - A number to add to the parameter's
752   ///   scope index;  can be negative
753   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
754                                           int indexAdjustment,
755                                           std::optional<unsigned> NumExpansions,
756                                           bool ExpectParameterPack);
757 
758   /// Transform the body of a lambda-expression.
759   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
760   /// Alternative implementation of TransformLambdaBody that skips transforming
761   /// the body.
762   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
763 
764   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
765 
766   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
767   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
768 
769   TemplateParameterList *TransformTemplateParameterList(
770         TemplateParameterList *TPL) {
771     return TPL;
772   }
773 
774   ExprResult TransformAddressOfOperand(Expr *E);
775 
776   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
777                                                 bool IsAddressOfOperand,
778                                                 TypeSourceInfo **RecoveryTSI);
779 
780   ExprResult TransformParenDependentScopeDeclRefExpr(
781       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
782       TypeSourceInfo **RecoveryTSI);
783 
784   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
785 
786 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
787 // amount of stack usage with clang.
788 #define STMT(Node, Parent)                        \
789   LLVM_ATTRIBUTE_NOINLINE \
790   StmtResult Transform##Node(Node *S);
791 #define VALUESTMT(Node, Parent)                   \
792   LLVM_ATTRIBUTE_NOINLINE \
793   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
794 #define EXPR(Node, Parent)                        \
795   LLVM_ATTRIBUTE_NOINLINE \
796   ExprResult Transform##Node(Node *E);
797 #define ABSTRACT_STMT(Stmt)
798 #include "clang/AST/StmtNodes.inc"
799 
800 #define GEN_CLANG_CLAUSE_CLASS
801 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
802   LLVM_ATTRIBUTE_NOINLINE                                                      \
803   OMPClause *Transform##Class(Class *S);
804 #include "llvm/Frontend/OpenMP/OMP.inc"
805 
806   /// Build a new qualified type given its unqualified type and type location.
807   ///
808   /// By default, this routine adds type qualifiers only to types that can
809   /// have qualifiers, and silently suppresses those qualifiers that are not
810   /// permitted. Subclasses may override this routine to provide different
811   /// behavior.
812   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
813 
814   /// Build a new pointer type given its pointee type.
815   ///
816   /// By default, performs semantic analysis when building the pointer type.
817   /// Subclasses may override this routine to provide different behavior.
818   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
819 
820   /// Build a new block pointer type given its pointee type.
821   ///
822   /// By default, performs semantic analysis when building the block pointer
823   /// type. Subclasses may override this routine to provide different behavior.
824   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
825 
826   /// Build a new reference type given the type it references.
827   ///
828   /// By default, performs semantic analysis when building the
829   /// reference type. Subclasses may override this routine to provide
830   /// different behavior.
831   ///
832   /// \param LValue whether the type was written with an lvalue sigil
833   /// or an rvalue sigil.
834   QualType RebuildReferenceType(QualType ReferentType,
835                                 bool LValue,
836                                 SourceLocation Sigil);
837 
838   /// Build a new member pointer type given the pointee type and the
839   /// class type it refers into.
840   ///
841   /// By default, performs semantic analysis when building the member pointer
842   /// type. Subclasses may override this routine to provide different behavior.
843   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
844                                     SourceLocation Sigil);
845 
846   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
847                                     SourceLocation ProtocolLAngleLoc,
848                                     ArrayRef<ObjCProtocolDecl *> Protocols,
849                                     ArrayRef<SourceLocation> ProtocolLocs,
850                                     SourceLocation ProtocolRAngleLoc);
851 
852   /// Build an Objective-C object type.
853   ///
854   /// By default, performs semantic analysis when building the object type.
855   /// Subclasses may override this routine to provide different behavior.
856   QualType RebuildObjCObjectType(QualType BaseType,
857                                  SourceLocation Loc,
858                                  SourceLocation TypeArgsLAngleLoc,
859                                  ArrayRef<TypeSourceInfo *> TypeArgs,
860                                  SourceLocation TypeArgsRAngleLoc,
861                                  SourceLocation ProtocolLAngleLoc,
862                                  ArrayRef<ObjCProtocolDecl *> Protocols,
863                                  ArrayRef<SourceLocation> ProtocolLocs,
864                                  SourceLocation ProtocolRAngleLoc);
865 
866   /// Build a new Objective-C object pointer type given the pointee type.
867   ///
868   /// By default, directly builds the pointer type, with no additional semantic
869   /// analysis.
870   QualType RebuildObjCObjectPointerType(QualType PointeeType,
871                                         SourceLocation Star);
872 
873   /// Build a new array type given the element type, size
874   /// modifier, size of the array (if known), size expression, and index type
875   /// qualifiers.
876   ///
877   /// By default, performs semantic analysis when building the array type.
878   /// Subclasses may override this routine to provide different behavior.
879   /// Also by default, all of the other Rebuild*Array
880   QualType RebuildArrayType(QualType ElementType,
881                             ArrayType::ArraySizeModifier SizeMod,
882                             const llvm::APInt *Size,
883                             Expr *SizeExpr,
884                             unsigned IndexTypeQuals,
885                             SourceRange BracketsRange);
886 
887   /// Build a new constant array type given the element type, size
888   /// modifier, (known) size of the array, and index type qualifiers.
889   ///
890   /// By default, performs semantic analysis when building the array type.
891   /// Subclasses may override this routine to provide different behavior.
892   QualType RebuildConstantArrayType(QualType ElementType,
893                                     ArrayType::ArraySizeModifier SizeMod,
894                                     const llvm::APInt &Size,
895                                     Expr *SizeExpr,
896                                     unsigned IndexTypeQuals,
897                                     SourceRange BracketsRange);
898 
899   /// Build a new incomplete array type given the element type, size
900   /// modifier, and index type qualifiers.
901   ///
902   /// By default, performs semantic analysis when building the array type.
903   /// Subclasses may override this routine to provide different behavior.
904   QualType RebuildIncompleteArrayType(QualType ElementType,
905                                       ArrayType::ArraySizeModifier SizeMod,
906                                       unsigned IndexTypeQuals,
907                                       SourceRange BracketsRange);
908 
909   /// Build a new variable-length array type given the element type,
910   /// size modifier, size expression, and index type qualifiers.
911   ///
912   /// By default, performs semantic analysis when building the array type.
913   /// Subclasses may override this routine to provide different behavior.
914   QualType RebuildVariableArrayType(QualType ElementType,
915                                     ArrayType::ArraySizeModifier SizeMod,
916                                     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                                           ArrayType::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                              VectorType::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,
946                                            VectorType::VectorKind);
947 
948   /// Build a new extended vector type given the element type and
949   /// number of elements.
950   ///
951   /// By default, performs semantic analysis when building the vector type.
952   /// Subclasses may override this routine to provide different behavior.
953   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
954                                 SourceLocation AttributeLoc);
955 
956   /// Build a new potentially dependently-sized extended vector type
957   /// given the element type and number of elements.
958   ///
959   /// By default, performs semantic analysis when building the vector type.
960   /// Subclasses may override this routine to provide different behavior.
961   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
962                                               Expr *SizeExpr,
963                                               SourceLocation AttributeLoc);
964 
965   /// Build a new matrix type given the element type and dimensions.
966   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
967                                      unsigned NumColumns);
968 
969   /// Build a new matrix type given the type and dependently-defined
970   /// dimensions.
971   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
972                                            Expr *ColumnExpr,
973                                            SourceLocation AttributeLoc);
974 
975   /// Build a new DependentAddressSpaceType or return the pointee
976   /// type variable with the correct address space (retrieved from
977   /// AddrSpaceExpr) applied to it. The former will be returned in cases
978   /// where the address space remains dependent.
979   ///
980   /// By default, performs semantic analysis when building the type with address
981   /// space applied. Subclasses may override this routine to provide different
982   /// behavior.
983   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
984                                             Expr *AddrSpaceExpr,
985                                             SourceLocation AttributeLoc);
986 
987   /// Build a new function type.
988   ///
989   /// By default, performs semantic analysis when building the function type.
990   /// Subclasses may override this routine to provide different behavior.
991   QualType RebuildFunctionProtoType(QualType T,
992                                     MutableArrayRef<QualType> ParamTypes,
993                                     const FunctionProtoType::ExtProtoInfo &EPI);
994 
995   /// Build a new unprototyped function type.
996   QualType RebuildFunctionNoProtoType(QualType ResultType);
997 
998   /// Rebuild an unresolved typename type, given the decl that
999   /// the UnresolvedUsingTypenameDecl was transformed to.
1000   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
1001 
1002   /// Build a new type found via an alias.
1003   QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
1004     return SemaRef.Context.getUsingType(Found, Underlying);
1005   }
1006 
1007   /// Build a new typedef type.
1008   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
1009     return SemaRef.Context.getTypeDeclType(Typedef);
1010   }
1011 
1012   /// Build a new MacroDefined type.
1013   QualType RebuildMacroQualifiedType(QualType T,
1014                                      const IdentifierInfo *MacroII) {
1015     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
1016   }
1017 
1018   /// Build a new class/struct/union type.
1019   QualType RebuildRecordType(RecordDecl *Record) {
1020     return SemaRef.Context.getTypeDeclType(Record);
1021   }
1022 
1023   /// Build a new Enum type.
1024   QualType RebuildEnumType(EnumDecl *Enum) {
1025     return SemaRef.Context.getTypeDeclType(Enum);
1026   }
1027 
1028   /// Build a new typeof(expr) type.
1029   ///
1030   /// By default, performs semantic analysis when building the typeof type.
1031   /// Subclasses may override this routine to provide different behavior.
1032   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc,
1033                                  TypeOfKind Kind);
1034 
1035   /// Build a new typeof(type) type.
1036   ///
1037   /// By default, builds a new TypeOfType with the given underlying type.
1038   QualType RebuildTypeOfType(QualType Underlying, TypeOfKind Kind);
1039 
1040   /// Build a new unary transform type.
1041   QualType RebuildUnaryTransformType(QualType BaseType,
1042                                      UnaryTransformType::UTTKind UKind,
1043                                      SourceLocation Loc);
1044 
1045   /// Build a new C++11 decltype type.
1046   ///
1047   /// By default, performs semantic analysis when building the decltype type.
1048   /// Subclasses may override this routine to provide different behavior.
1049   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
1050 
1051   /// Build a new C++11 auto type.
1052   ///
1053   /// By default, builds a new AutoType with the given deduced type.
1054   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
1055                            ConceptDecl *TypeConstraintConcept,
1056                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
1057     // Note, IsDependent is always false here: we implicitly convert an 'auto'
1058     // which has been deduced to a dependent type into an undeduced 'auto', so
1059     // that we'll retry deduction after the transformation.
1060     return SemaRef.Context.getAutoType(Deduced, Keyword,
1061                                        /*IsDependent*/ false, /*IsPack=*/false,
1062                                        TypeConstraintConcept,
1063                                        TypeConstraintArgs);
1064   }
1065 
1066   /// By default, builds a new DeducedTemplateSpecializationType with the given
1067   /// deduced type.
1068   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1069       QualType Deduced) {
1070     return SemaRef.Context.getDeducedTemplateSpecializationType(
1071         Template, Deduced, /*IsDependent*/ false);
1072   }
1073 
1074   /// Build a new template specialization type.
1075   ///
1076   /// By default, performs semantic analysis when building the template
1077   /// specialization type. Subclasses may override this routine to provide
1078   /// different behavior.
1079   QualType RebuildTemplateSpecializationType(TemplateName Template,
1080                                              SourceLocation TemplateLoc,
1081                                              TemplateArgumentListInfo &Args);
1082 
1083   /// Build a new parenthesized type.
1084   ///
1085   /// By default, builds a new ParenType type from the inner type.
1086   /// Subclasses may override this routine to provide different behavior.
1087   QualType RebuildParenType(QualType InnerType) {
1088     return SemaRef.BuildParenType(InnerType);
1089   }
1090 
1091   /// Build a new qualified name type.
1092   ///
1093   /// By default, builds a new ElaboratedType type from the keyword,
1094   /// the nested-name-specifier and the named type.
1095   /// Subclasses may override this routine to provide different behavior.
1096   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1097                                  ElaboratedTypeKeyword Keyword,
1098                                  NestedNameSpecifierLoc QualifierLoc,
1099                                  QualType Named) {
1100     return SemaRef.Context.getElaboratedType(Keyword,
1101                                          QualifierLoc.getNestedNameSpecifier(),
1102                                              Named);
1103   }
1104 
1105   /// Build a new typename type that refers to a template-id.
1106   ///
1107   /// By default, builds a new DependentNameType type from the
1108   /// nested-name-specifier and the given type. Subclasses may override
1109   /// this routine to provide different behavior.
1110   QualType RebuildDependentTemplateSpecializationType(
1111                                           ElaboratedTypeKeyword Keyword,
1112                                           NestedNameSpecifierLoc QualifierLoc,
1113                                           SourceLocation TemplateKWLoc,
1114                                           const IdentifierInfo *Name,
1115                                           SourceLocation NameLoc,
1116                                           TemplateArgumentListInfo &Args,
1117                                           bool AllowInjectedClassName) {
1118     // Rebuild the template name.
1119     // TODO: avoid TemplateName abstraction
1120     CXXScopeSpec SS;
1121     SS.Adopt(QualifierLoc);
1122     TemplateName InstName = getDerived().RebuildTemplateName(
1123         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1124         AllowInjectedClassName);
1125 
1126     if (InstName.isNull())
1127       return QualType();
1128 
1129     // If it's still dependent, make a dependent specialization.
1130     if (InstName.getAsDependentTemplateName())
1131       return SemaRef.Context.getDependentTemplateSpecializationType(
1132           Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
1133           Args.arguments());
1134 
1135     // Otherwise, make an elaborated type wrapping a non-dependent
1136     // specialization.
1137     QualType T =
1138         getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1139     if (T.isNull())
1140       return QualType();
1141     return SemaRef.Context.getElaboratedType(
1142         Keyword, QualifierLoc.getNestedNameSpecifier(), T);
1143   }
1144 
1145   /// Build a new typename type that refers to an identifier.
1146   ///
1147   /// By default, performs semantic analysis when building the typename type
1148   /// (or elaborated type). Subclasses may override this routine to provide
1149   /// different behavior.
1150   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1151                                     SourceLocation KeywordLoc,
1152                                     NestedNameSpecifierLoc QualifierLoc,
1153                                     const IdentifierInfo *Id,
1154                                     SourceLocation IdLoc,
1155                                     bool DeducedTSTContext) {
1156     CXXScopeSpec SS;
1157     SS.Adopt(QualifierLoc);
1158 
1159     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1160       // If the name is still dependent, just build a new dependent name type.
1161       if (!SemaRef.computeDeclContext(SS))
1162         return SemaRef.Context.getDependentNameType(Keyword,
1163                                           QualifierLoc.getNestedNameSpecifier(),
1164                                                     Id);
1165     }
1166 
1167     if (Keyword == ETK_None || Keyword == ETK_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) << SomeDecl
1217                                                                << NTK << 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               << Kind << Id << DC << QualifierLoc.getSourceRange();
1224           break;
1225       }
1226       return QualType();
1227     }
1228 
1229     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1230                                               IdLoc, Id)) {
1231       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1232       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1233       return QualType();
1234     }
1235 
1236     // Build the elaborated-type-specifier type.
1237     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1238     return SemaRef.Context.getElaboratedType(Keyword,
1239                                          QualifierLoc.getNestedNameSpecifier(),
1240                                              T);
1241   }
1242 
1243   /// Build a new pack expansion type.
1244   ///
1245   /// By default, builds a new PackExpansionType type from the given pattern.
1246   /// Subclasses may override this routine to provide different behavior.
1247   QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange,
1248                                     SourceLocation EllipsisLoc,
1249                                     std::optional<unsigned> NumExpansions) {
1250     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1251                                         NumExpansions);
1252   }
1253 
1254   /// Build a new atomic type given its value type.
1255   ///
1256   /// By default, performs semantic analysis when building the atomic type.
1257   /// Subclasses may override this routine to provide different behavior.
1258   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1259 
1260   /// Build a new pipe type given its value type.
1261   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1262                            bool isReadPipe);
1263 
1264   /// Build a bit-precise int given its value type.
1265   QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1266                              SourceLocation Loc);
1267 
1268   /// Build a dependent bit-precise int given its value type.
1269   QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1270                                       SourceLocation Loc);
1271 
1272   /// Build a new template name given a nested name specifier, a flag
1273   /// indicating whether the "template" keyword was provided, and the template
1274   /// that the template name refers to.
1275   ///
1276   /// By default, builds the new template name directly. Subclasses may override
1277   /// this routine to provide different behavior.
1278   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1279                                    bool TemplateKW,
1280                                    TemplateDecl *Template);
1281 
1282   /// Build a new template name given a nested name specifier and the
1283   /// name that is referred to as a template.
1284   ///
1285   /// By default, performs semantic analysis to determine whether the name can
1286   /// be resolved to a specific template, then builds the appropriate kind of
1287   /// template name. Subclasses may override this routine to provide different
1288   /// behavior.
1289   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1290                                    SourceLocation TemplateKWLoc,
1291                                    const IdentifierInfo &Name,
1292                                    SourceLocation NameLoc, QualType ObjectType,
1293                                    NamedDecl *FirstQualifierInScope,
1294                                    bool AllowInjectedClassName);
1295 
1296   /// Build a new template name given a nested name specifier and the
1297   /// overloaded operator name that is referred to as a template.
1298   ///
1299   /// By default, performs semantic analysis to determine whether the name can
1300   /// be resolved to a specific template, then builds the appropriate kind of
1301   /// template name. Subclasses may override this routine to provide different
1302   /// behavior.
1303   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1304                                    SourceLocation TemplateKWLoc,
1305                                    OverloadedOperatorKind Operator,
1306                                    SourceLocation NameLoc, QualType ObjectType,
1307                                    bool AllowInjectedClassName);
1308 
1309   /// Build a new template name given a template template parameter pack
1310   /// and the
1311   ///
1312   /// By default, performs semantic analysis to determine whether the name can
1313   /// be resolved to a specific template, then builds the appropriate kind of
1314   /// template name. Subclasses may override this routine to provide different
1315   /// behavior.
1316   TemplateName RebuildTemplateName(const TemplateArgument &ArgPack,
1317                                    Decl *AssociatedDecl, unsigned Index,
1318                                    bool Final) {
1319     return getSema().Context.getSubstTemplateTemplateParmPack(
1320         ArgPack, AssociatedDecl, Index, Final);
1321   }
1322 
1323   /// Build a new compound statement.
1324   ///
1325   /// By default, performs semantic analysis to build the new statement.
1326   /// Subclasses may override this routine to provide different behavior.
1327   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1328                                        MultiStmtArg Statements,
1329                                        SourceLocation RBraceLoc,
1330                                        bool IsStmtExpr) {
1331     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1332                                        IsStmtExpr);
1333   }
1334 
1335   /// Build a new case statement.
1336   ///
1337   /// By default, performs semantic analysis to build the new statement.
1338   /// Subclasses may override this routine to provide different behavior.
1339   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1340                                    Expr *LHS,
1341                                    SourceLocation EllipsisLoc,
1342                                    Expr *RHS,
1343                                    SourceLocation ColonLoc) {
1344     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1345                                    ColonLoc);
1346   }
1347 
1348   /// Attach the body to a new case statement.
1349   ///
1350   /// By default, performs semantic analysis to build the new statement.
1351   /// Subclasses may override this routine to provide different behavior.
1352   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1353     getSema().ActOnCaseStmtBody(S, Body);
1354     return S;
1355   }
1356 
1357   /// Build a new default statement.
1358   ///
1359   /// By default, performs semantic analysis to build the new statement.
1360   /// Subclasses may override this routine to provide different behavior.
1361   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1362                                       SourceLocation ColonLoc,
1363                                       Stmt *SubStmt) {
1364     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1365                                       /*CurScope=*/nullptr);
1366   }
1367 
1368   /// Build a new label statement.
1369   ///
1370   /// By default, performs semantic analysis to build the new statement.
1371   /// Subclasses may override this routine to provide different behavior.
1372   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1373                               SourceLocation ColonLoc, Stmt *SubStmt) {
1374     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1375   }
1376 
1377   /// Build a new attributed statement.
1378   ///
1379   /// By default, performs semantic analysis to build the new statement.
1380   /// Subclasses may override this routine to provide different behavior.
1381   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1382                                    ArrayRef<const Attr *> Attrs,
1383                                    Stmt *SubStmt) {
1384     return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1385   }
1386 
1387   /// Build a new "if" statement.
1388   ///
1389   /// By default, performs semantic analysis to build the new statement.
1390   /// Subclasses may override this routine to provide different behavior.
1391   StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1392                            SourceLocation LParenLoc, Sema::ConditionResult Cond,
1393                            SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1394                            SourceLocation ElseLoc, Stmt *Else) {
1395     return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1396                                  Then, ElseLoc, Else);
1397   }
1398 
1399   /// Start building a new switch statement.
1400   ///
1401   /// By default, performs semantic analysis to build the new statement.
1402   /// Subclasses may override this routine to provide different behavior.
1403   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1404                                     SourceLocation LParenLoc, Stmt *Init,
1405                                     Sema::ConditionResult Cond,
1406                                     SourceLocation RParenLoc) {
1407     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1408                                             RParenLoc);
1409   }
1410 
1411   /// Attach the body to the switch statement.
1412   ///
1413   /// By default, performs semantic analysis to build the new statement.
1414   /// Subclasses may override this routine to provide different behavior.
1415   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1416                                    Stmt *Switch, Stmt *Body) {
1417     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1418   }
1419 
1420   /// Build a new while statement.
1421   ///
1422   /// By default, performs semantic analysis to build the new statement.
1423   /// Subclasses may override this routine to provide different behavior.
1424   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1425                               Sema::ConditionResult Cond,
1426                               SourceLocation RParenLoc, Stmt *Body) {
1427     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1428   }
1429 
1430   /// Build a new do-while statement.
1431   ///
1432   /// By default, performs semantic analysis to build the new statement.
1433   /// Subclasses may override this routine to provide different behavior.
1434   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1435                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1436                            Expr *Cond, SourceLocation RParenLoc) {
1437     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1438                                  Cond, RParenLoc);
1439   }
1440 
1441   /// Build a new for statement.
1442   ///
1443   /// By default, performs semantic analysis to build the new statement.
1444   /// Subclasses may override this routine to provide different behavior.
1445   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1446                             Stmt *Init, Sema::ConditionResult Cond,
1447                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1448                             Stmt *Body) {
1449     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1450                                   Inc, RParenLoc, Body);
1451   }
1452 
1453   /// Build a new goto statement.
1454   ///
1455   /// By default, performs semantic analysis to build the new statement.
1456   /// Subclasses may override this routine to provide different behavior.
1457   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1458                              LabelDecl *Label) {
1459     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1460   }
1461 
1462   /// Build a new indirect goto statement.
1463   ///
1464   /// By default, performs semantic analysis to build the new statement.
1465   /// Subclasses may override this routine to provide different behavior.
1466   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1467                                      SourceLocation StarLoc,
1468                                      Expr *Target) {
1469     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1470   }
1471 
1472   /// Build a new return statement.
1473   ///
1474   /// By default, performs semantic analysis to build the new statement.
1475   /// Subclasses may override this routine to provide different behavior.
1476   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1477     return getSema().BuildReturnStmt(ReturnLoc, Result);
1478   }
1479 
1480   /// Build a new declaration statement.
1481   ///
1482   /// By default, performs semantic analysis to build the new statement.
1483   /// Subclasses may override this routine to provide different behavior.
1484   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1485                              SourceLocation StartLoc, SourceLocation EndLoc) {
1486     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1487     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1488   }
1489 
1490   /// Build a new inline asm statement.
1491   ///
1492   /// By default, performs semantic analysis to build the new statement.
1493   /// Subclasses may override this routine to provide different behavior.
1494   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1495                                bool IsVolatile, unsigned NumOutputs,
1496                                unsigned NumInputs, IdentifierInfo **Names,
1497                                MultiExprArg Constraints, MultiExprArg Exprs,
1498                                Expr *AsmString, MultiExprArg Clobbers,
1499                                unsigned NumLabels,
1500                                SourceLocation RParenLoc) {
1501     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1502                                      NumInputs, Names, Constraints, Exprs,
1503                                      AsmString, Clobbers, NumLabels, RParenLoc);
1504   }
1505 
1506   /// Build a new MS style inline asm statement.
1507   ///
1508   /// By default, performs semantic analysis to build the new statement.
1509   /// Subclasses may override this routine to provide different behavior.
1510   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1511                               ArrayRef<Token> AsmToks,
1512                               StringRef AsmString,
1513                               unsigned NumOutputs, unsigned NumInputs,
1514                               ArrayRef<StringRef> Constraints,
1515                               ArrayRef<StringRef> Clobbers,
1516                               ArrayRef<Expr*> Exprs,
1517                               SourceLocation EndLoc) {
1518     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1519                                     NumOutputs, NumInputs,
1520                                     Constraints, Clobbers, Exprs, EndLoc);
1521   }
1522 
1523   /// Build a new co_return statement.
1524   ///
1525   /// By default, performs semantic analysis to build the new statement.
1526   /// Subclasses may override this routine to provide different behavior.
1527   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1528                                  bool IsImplicit) {
1529     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1530   }
1531 
1532   /// Build a new co_await expression.
1533   ///
1534   /// By default, performs semantic analysis to build the new expression.
1535   /// Subclasses may override this routine to provide different behavior.
1536   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1537                                 UnresolvedLookupExpr *OpCoawaitLookup,
1538                                 bool IsImplicit) {
1539     // This function rebuilds a coawait-expr given its operator.
1540     // For an explicit coawait-expr, the rebuild involves the full set
1541     // of transformations performed by BuildUnresolvedCoawaitExpr(),
1542     // including calling await_transform().
1543     // For an implicit coawait-expr, we need to rebuild the "operator
1544     // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1545     // This mirrors how the implicit CoawaitExpr is originally created
1546     // in Sema::ActOnCoroutineBodyStart().
1547     if (IsImplicit) {
1548       ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1549           CoawaitLoc, Operand, OpCoawaitLookup);
1550       if (Suspend.isInvalid())
1551         return ExprError();
1552       return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1553                                                 Suspend.get(), true);
1554     }
1555 
1556     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1557                                                 OpCoawaitLookup);
1558   }
1559 
1560   /// Build a new co_await expression.
1561   ///
1562   /// By default, performs semantic analysis to build the new expression.
1563   /// Subclasses may override this routine to provide different behavior.
1564   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1565                                          Expr *Result,
1566                                          UnresolvedLookupExpr *Lookup) {
1567     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1568   }
1569 
1570   /// Build a new co_yield expression.
1571   ///
1572   /// By default, performs semantic analysis to build the new expression.
1573   /// Subclasses may override this routine to provide different behavior.
1574   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1575     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1576   }
1577 
1578   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1579     return getSema().BuildCoroutineBodyStmt(Args);
1580   }
1581 
1582   /// Build a new Objective-C \@try statement.
1583   ///
1584   /// By default, performs semantic analysis to build the new statement.
1585   /// Subclasses may override this routine to provide different behavior.
1586   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1587                                         Stmt *TryBody,
1588                                         MultiStmtArg CatchStmts,
1589                                         Stmt *Finally) {
1590     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1591                                         Finally);
1592   }
1593 
1594   /// Rebuild an Objective-C exception declaration.
1595   ///
1596   /// By default, performs semantic analysis to build the new declaration.
1597   /// Subclasses may override this routine to provide different behavior.
1598   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1599                                     TypeSourceInfo *TInfo, QualType T) {
1600     return getSema().BuildObjCExceptionDecl(TInfo, T,
1601                                             ExceptionDecl->getInnerLocStart(),
1602                                             ExceptionDecl->getLocation(),
1603                                             ExceptionDecl->getIdentifier());
1604   }
1605 
1606   /// Build a new Objective-C \@catch statement.
1607   ///
1608   /// By default, performs semantic analysis to build the new statement.
1609   /// Subclasses may override this routine to provide different behavior.
1610   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1611                                           SourceLocation RParenLoc,
1612                                           VarDecl *Var,
1613                                           Stmt *Body) {
1614     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1615                                           Var, Body);
1616   }
1617 
1618   /// Build a new Objective-C \@finally statement.
1619   ///
1620   /// By default, performs semantic analysis to build the new statement.
1621   /// Subclasses may override this routine to provide different behavior.
1622   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1623                                             Stmt *Body) {
1624     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1625   }
1626 
1627   /// Build a new Objective-C \@throw statement.
1628   ///
1629   /// By default, performs semantic analysis to build the new statement.
1630   /// Subclasses may override this routine to provide different behavior.
1631   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1632                                           Expr *Operand) {
1633     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1634   }
1635 
1636   /// Build a new OpenMP Canonical loop.
1637   ///
1638   /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1639   /// OMPCanonicalLoop.
1640   StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1641     return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1642   }
1643 
1644   /// Build a new OpenMP executable directive.
1645   ///
1646   /// By default, performs semantic analysis to build the new statement.
1647   /// Subclasses may override this routine to provide different behavior.
1648   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1649                                            DeclarationNameInfo DirName,
1650                                            OpenMPDirectiveKind CancelRegion,
1651                                            ArrayRef<OMPClause *> Clauses,
1652                                            Stmt *AStmt, SourceLocation StartLoc,
1653                                            SourceLocation EndLoc) {
1654     return getSema().ActOnOpenMPExecutableDirective(
1655         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1656   }
1657 
1658   /// Build a new OpenMP 'if' clause.
1659   ///
1660   /// By default, performs semantic analysis to build the new OpenMP clause.
1661   /// Subclasses may override this routine to provide different behavior.
1662   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1663                                 Expr *Condition, SourceLocation StartLoc,
1664                                 SourceLocation LParenLoc,
1665                                 SourceLocation NameModifierLoc,
1666                                 SourceLocation ColonLoc,
1667                                 SourceLocation EndLoc) {
1668     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1669                                          LParenLoc, NameModifierLoc, ColonLoc,
1670                                          EndLoc);
1671   }
1672 
1673   /// Build a new OpenMP 'final' clause.
1674   ///
1675   /// By default, performs semantic analysis to build the new OpenMP clause.
1676   /// Subclasses may override this routine to provide different behavior.
1677   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1678                                    SourceLocation LParenLoc,
1679                                    SourceLocation EndLoc) {
1680     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1681                                             EndLoc);
1682   }
1683 
1684   /// Build a new OpenMP 'num_threads' clause.
1685   ///
1686   /// By default, performs semantic analysis to build the new OpenMP clause.
1687   /// Subclasses may override this routine to provide different behavior.
1688   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1689                                         SourceLocation StartLoc,
1690                                         SourceLocation LParenLoc,
1691                                         SourceLocation EndLoc) {
1692     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1693                                                  LParenLoc, EndLoc);
1694   }
1695 
1696   /// Build a new OpenMP 'safelen' clause.
1697   ///
1698   /// By default, performs semantic analysis to build the new OpenMP clause.
1699   /// Subclasses may override this routine to provide different behavior.
1700   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1701                                      SourceLocation LParenLoc,
1702                                      SourceLocation EndLoc) {
1703     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1704   }
1705 
1706   /// Build a new OpenMP 'simdlen' clause.
1707   ///
1708   /// By default, performs semantic analysis to build the new OpenMP clause.
1709   /// Subclasses may override this routine to provide different behavior.
1710   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1711                                      SourceLocation LParenLoc,
1712                                      SourceLocation EndLoc) {
1713     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1714   }
1715 
1716   OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1717                                    SourceLocation StartLoc,
1718                                    SourceLocation LParenLoc,
1719                                    SourceLocation EndLoc) {
1720     return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1721   }
1722 
1723   /// Build a new OpenMP 'full' clause.
1724   OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1725                                   SourceLocation EndLoc) {
1726     return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1727   }
1728 
1729   /// Build a new OpenMP 'partial' clause.
1730   OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1731                                      SourceLocation LParenLoc,
1732                                      SourceLocation EndLoc) {
1733     return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1734                                               EndLoc);
1735   }
1736 
1737   /// Build a new OpenMP 'allocator' clause.
1738   ///
1739   /// By default, performs semantic analysis to build the new OpenMP clause.
1740   /// Subclasses may override this routine to provide different behavior.
1741   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1742                                        SourceLocation LParenLoc,
1743                                        SourceLocation EndLoc) {
1744     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1745   }
1746 
1747   /// Build a new OpenMP 'collapse' clause.
1748   ///
1749   /// By default, performs semantic analysis to build the new OpenMP clause.
1750   /// Subclasses may override this routine to provide different behavior.
1751   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1752                                       SourceLocation LParenLoc,
1753                                       SourceLocation EndLoc) {
1754     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1755                                                EndLoc);
1756   }
1757 
1758   /// Build a new OpenMP 'default' clause.
1759   ///
1760   /// By default, performs semantic analysis to build the new OpenMP clause.
1761   /// Subclasses may override this routine to provide different behavior.
1762   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1763                                      SourceLocation StartLoc,
1764                                      SourceLocation LParenLoc,
1765                                      SourceLocation EndLoc) {
1766     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1767                                               StartLoc, LParenLoc, EndLoc);
1768   }
1769 
1770   /// Build a new OpenMP 'proc_bind' clause.
1771   ///
1772   /// By default, performs semantic analysis to build the new OpenMP clause.
1773   /// Subclasses may override this routine to provide different behavior.
1774   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1775                                       SourceLocation KindKwLoc,
1776                                       SourceLocation StartLoc,
1777                                       SourceLocation LParenLoc,
1778                                       SourceLocation EndLoc) {
1779     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1780                                                StartLoc, LParenLoc, EndLoc);
1781   }
1782 
1783   /// Build a new OpenMP 'schedule' clause.
1784   ///
1785   /// By default, performs semantic analysis to build the new OpenMP clause.
1786   /// Subclasses may override this routine to provide different behavior.
1787   OMPClause *RebuildOMPScheduleClause(
1788       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1789       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1790       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1791       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1792     return getSema().ActOnOpenMPScheduleClause(
1793         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1794         CommaLoc, EndLoc);
1795   }
1796 
1797   /// Build a new OpenMP 'ordered' clause.
1798   ///
1799   /// By default, performs semantic analysis to build the new OpenMP clause.
1800   /// Subclasses may override this routine to provide different behavior.
1801   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1802                                      SourceLocation EndLoc,
1803                                      SourceLocation LParenLoc, Expr *Num) {
1804     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1805   }
1806 
1807   /// Build a new OpenMP 'private' clause.
1808   ///
1809   /// By default, performs semantic analysis to build the new OpenMP clause.
1810   /// Subclasses may override this routine to provide different behavior.
1811   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1812                                      SourceLocation StartLoc,
1813                                      SourceLocation LParenLoc,
1814                                      SourceLocation EndLoc) {
1815     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1816                                               EndLoc);
1817   }
1818 
1819   /// Build a new OpenMP 'firstprivate' clause.
1820   ///
1821   /// By default, performs semantic analysis to build the new OpenMP clause.
1822   /// Subclasses may override this routine to provide different behavior.
1823   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1824                                           SourceLocation StartLoc,
1825                                           SourceLocation LParenLoc,
1826                                           SourceLocation EndLoc) {
1827     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1828                                                    EndLoc);
1829   }
1830 
1831   /// Build a new OpenMP 'lastprivate' clause.
1832   ///
1833   /// By default, performs semantic analysis to build the new OpenMP clause.
1834   /// Subclasses may override this routine to provide different behavior.
1835   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1836                                          OpenMPLastprivateModifier LPKind,
1837                                          SourceLocation LPKindLoc,
1838                                          SourceLocation ColonLoc,
1839                                          SourceLocation StartLoc,
1840                                          SourceLocation LParenLoc,
1841                                          SourceLocation EndLoc) {
1842     return getSema().ActOnOpenMPLastprivateClause(
1843         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1844   }
1845 
1846   /// Build a new OpenMP 'shared' clause.
1847   ///
1848   /// By default, performs semantic analysis to build the new OpenMP clause.
1849   /// Subclasses may override this routine to provide different behavior.
1850   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1851                                     SourceLocation StartLoc,
1852                                     SourceLocation LParenLoc,
1853                                     SourceLocation EndLoc) {
1854     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1855                                              EndLoc);
1856   }
1857 
1858   /// Build a new OpenMP 'reduction' clause.
1859   ///
1860   /// By default, performs semantic analysis to build the new statement.
1861   /// Subclasses may override this routine to provide different behavior.
1862   OMPClause *RebuildOMPReductionClause(
1863       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1864       SourceLocation StartLoc, SourceLocation LParenLoc,
1865       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1866       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1867       const DeclarationNameInfo &ReductionId,
1868       ArrayRef<Expr *> UnresolvedReductions) {
1869     return getSema().ActOnOpenMPReductionClause(
1870         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1871         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1872   }
1873 
1874   /// Build a new OpenMP 'task_reduction' clause.
1875   ///
1876   /// By default, performs semantic analysis to build the new statement.
1877   /// Subclasses may override this routine to provide different behavior.
1878   OMPClause *RebuildOMPTaskReductionClause(
1879       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1880       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1881       CXXScopeSpec &ReductionIdScopeSpec,
1882       const DeclarationNameInfo &ReductionId,
1883       ArrayRef<Expr *> UnresolvedReductions) {
1884     return getSema().ActOnOpenMPTaskReductionClause(
1885         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1886         ReductionId, UnresolvedReductions);
1887   }
1888 
1889   /// Build a new OpenMP 'in_reduction' clause.
1890   ///
1891   /// By default, performs semantic analysis to build the new statement.
1892   /// Subclasses may override this routine to provide different behavior.
1893   OMPClause *
1894   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1895                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1896                               SourceLocation EndLoc,
1897                               CXXScopeSpec &ReductionIdScopeSpec,
1898                               const DeclarationNameInfo &ReductionId,
1899                               ArrayRef<Expr *> UnresolvedReductions) {
1900     return getSema().ActOnOpenMPInReductionClause(
1901         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1902         ReductionId, UnresolvedReductions);
1903   }
1904 
1905   /// Build a new OpenMP 'linear' clause.
1906   ///
1907   /// By default, performs semantic analysis to build the new OpenMP clause.
1908   /// Subclasses may override this routine to provide different behavior.
1909   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1910                                     SourceLocation StartLoc,
1911                                     SourceLocation LParenLoc,
1912                                     OpenMPLinearClauseKind Modifier,
1913                                     SourceLocation ModifierLoc,
1914                                     SourceLocation ColonLoc,
1915                                     SourceLocation EndLoc) {
1916     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1917                                              Modifier, ModifierLoc, ColonLoc,
1918                                              EndLoc);
1919   }
1920 
1921   /// Build a new OpenMP 'aligned' clause.
1922   ///
1923   /// By default, performs semantic analysis to build the new OpenMP clause.
1924   /// Subclasses may override this routine to provide different behavior.
1925   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1926                                      SourceLocation StartLoc,
1927                                      SourceLocation LParenLoc,
1928                                      SourceLocation ColonLoc,
1929                                      SourceLocation EndLoc) {
1930     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1931                                               LParenLoc, ColonLoc, EndLoc);
1932   }
1933 
1934   /// Build a new OpenMP 'copyin' clause.
1935   ///
1936   /// By default, performs semantic analysis to build the new OpenMP clause.
1937   /// Subclasses may override this routine to provide different behavior.
1938   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1939                                     SourceLocation StartLoc,
1940                                     SourceLocation LParenLoc,
1941                                     SourceLocation EndLoc) {
1942     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1943                                              EndLoc);
1944   }
1945 
1946   /// Build a new OpenMP 'copyprivate' clause.
1947   ///
1948   /// By default, performs semantic analysis to build the new OpenMP clause.
1949   /// Subclasses may override this routine to provide different behavior.
1950   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1951                                          SourceLocation StartLoc,
1952                                          SourceLocation LParenLoc,
1953                                          SourceLocation EndLoc) {
1954     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1955                                                   EndLoc);
1956   }
1957 
1958   /// Build a new OpenMP 'flush' pseudo clause.
1959   ///
1960   /// By default, performs semantic analysis to build the new OpenMP clause.
1961   /// Subclasses may override this routine to provide different behavior.
1962   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1963                                    SourceLocation StartLoc,
1964                                    SourceLocation LParenLoc,
1965                                    SourceLocation EndLoc) {
1966     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1967                                             EndLoc);
1968   }
1969 
1970   /// Build a new OpenMP 'depobj' pseudo clause.
1971   ///
1972   /// By default, performs semantic analysis to build the new OpenMP clause.
1973   /// Subclasses may override this routine to provide different behavior.
1974   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1975                                     SourceLocation LParenLoc,
1976                                     SourceLocation EndLoc) {
1977     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1978                                              EndLoc);
1979   }
1980 
1981   /// Build a new OpenMP 'depend' pseudo clause.
1982   ///
1983   /// By default, performs semantic analysis to build the new OpenMP clause.
1984   /// Subclasses may override this routine to provide different behavior.
1985   OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1986                                     Expr *DepModifier, ArrayRef<Expr *> VarList,
1987                                     SourceLocation StartLoc,
1988                                     SourceLocation LParenLoc,
1989                                     SourceLocation EndLoc) {
1990     return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1991                                              StartLoc, LParenLoc, EndLoc);
1992   }
1993 
1994   /// Build a new OpenMP 'device' clause.
1995   ///
1996   /// By default, performs semantic analysis to build the new statement.
1997   /// Subclasses may override this routine to provide different behavior.
1998   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1999                                     Expr *Device, SourceLocation StartLoc,
2000                                     SourceLocation LParenLoc,
2001                                     SourceLocation ModifierLoc,
2002                                     SourceLocation EndLoc) {
2003     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
2004                                              LParenLoc, ModifierLoc, EndLoc);
2005   }
2006 
2007   /// Build a new OpenMP 'map' clause.
2008   ///
2009   /// By default, performs semantic analysis to build the new OpenMP clause.
2010   /// Subclasses may override this routine to provide different behavior.
2011   OMPClause *RebuildOMPMapClause(
2012       Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
2013       ArrayRef<SourceLocation> MapTypeModifiersLoc,
2014       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
2015       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
2016       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
2017       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
2018     return getSema().ActOnOpenMPMapClause(
2019         IteratorModifier, MapTypeModifiers, MapTypeModifiersLoc,
2020         MapperIdScopeSpec, MapperId, MapType, IsMapTypeImplicit, MapLoc,
2021         ColonLoc, VarList, Locs,
2022         /*NoDiagnose=*/false, UnresolvedMappers);
2023   }
2024 
2025   /// Build a new OpenMP 'allocate' clause.
2026   ///
2027   /// By default, performs semantic analysis to build the new OpenMP clause.
2028   /// Subclasses may override this routine to provide different behavior.
2029   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
2030                                       SourceLocation StartLoc,
2031                                       SourceLocation LParenLoc,
2032                                       SourceLocation ColonLoc,
2033                                       SourceLocation EndLoc) {
2034     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
2035                                                LParenLoc, ColonLoc, EndLoc);
2036   }
2037 
2038   /// Build a new OpenMP 'num_teams' clause.
2039   ///
2040   /// By default, performs semantic analysis to build the new statement.
2041   /// Subclasses may override this routine to provide different behavior.
2042   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
2043                                       SourceLocation LParenLoc,
2044                                       SourceLocation EndLoc) {
2045     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
2046                                                EndLoc);
2047   }
2048 
2049   /// Build a new OpenMP 'thread_limit' clause.
2050   ///
2051   /// By default, performs semantic analysis to build the new statement.
2052   /// Subclasses may override this routine to provide different behavior.
2053   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
2054                                          SourceLocation StartLoc,
2055                                          SourceLocation LParenLoc,
2056                                          SourceLocation EndLoc) {
2057     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
2058                                                   LParenLoc, EndLoc);
2059   }
2060 
2061   /// Build a new OpenMP 'priority' clause.
2062   ///
2063   /// By default, performs semantic analysis to build the new statement.
2064   /// Subclasses may override this routine to provide different behavior.
2065   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2066                                       SourceLocation LParenLoc,
2067                                       SourceLocation EndLoc) {
2068     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2069                                                EndLoc);
2070   }
2071 
2072   /// Build a new OpenMP 'grainsize' clause.
2073   ///
2074   /// By default, performs semantic analysis to build the new statement.
2075   /// Subclasses may override this routine to provide different behavior.
2076   OMPClause *RebuildOMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
2077                                        Expr *Device, SourceLocation StartLoc,
2078                                        SourceLocation LParenLoc,
2079                                        SourceLocation ModifierLoc,
2080                                        SourceLocation EndLoc) {
2081     return getSema().ActOnOpenMPGrainsizeClause(Modifier, Device, StartLoc,
2082                                                 LParenLoc, ModifierLoc, EndLoc);
2083   }
2084 
2085   /// Build a new OpenMP 'num_tasks' clause.
2086   ///
2087   /// By default, performs semantic analysis to build the new statement.
2088   /// Subclasses may override this routine to provide different behavior.
2089   OMPClause *RebuildOMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
2090                                       Expr *NumTasks, SourceLocation StartLoc,
2091                                       SourceLocation LParenLoc,
2092                                       SourceLocation ModifierLoc,
2093                                       SourceLocation EndLoc) {
2094     return getSema().ActOnOpenMPNumTasksClause(Modifier, NumTasks, StartLoc,
2095                                                LParenLoc, ModifierLoc, EndLoc);
2096   }
2097 
2098   /// Build a new OpenMP 'hint' clause.
2099   ///
2100   /// By default, performs semantic analysis to build the new statement.
2101   /// Subclasses may override this routine to provide different behavior.
2102   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2103                                   SourceLocation LParenLoc,
2104                                   SourceLocation EndLoc) {
2105     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2106   }
2107 
2108   /// Build a new OpenMP 'detach' clause.
2109   ///
2110   /// By default, performs semantic analysis to build the new statement.
2111   /// Subclasses may override this routine to provide different behavior.
2112   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2113                                     SourceLocation LParenLoc,
2114                                     SourceLocation EndLoc) {
2115     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2116   }
2117 
2118   /// Build a new OpenMP 'dist_schedule' clause.
2119   ///
2120   /// By default, performs semantic analysis to build the new OpenMP clause.
2121   /// Subclasses may override this routine to provide different behavior.
2122   OMPClause *
2123   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2124                                Expr *ChunkSize, SourceLocation StartLoc,
2125                                SourceLocation LParenLoc, SourceLocation KindLoc,
2126                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2127     return getSema().ActOnOpenMPDistScheduleClause(
2128         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2129   }
2130 
2131   /// Build a new OpenMP 'to' clause.
2132   ///
2133   /// By default, performs semantic analysis to build the new statement.
2134   /// Subclasses may override this routine to provide different behavior.
2135   OMPClause *
2136   RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2137                      ArrayRef<SourceLocation> MotionModifiersLoc,
2138                      CXXScopeSpec &MapperIdScopeSpec,
2139                      DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2140                      ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2141                      ArrayRef<Expr *> UnresolvedMappers) {
2142     return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2143                                          MapperIdScopeSpec, MapperId, ColonLoc,
2144                                          VarList, Locs, UnresolvedMappers);
2145   }
2146 
2147   /// Build a new OpenMP 'from' clause.
2148   ///
2149   /// By default, performs semantic analysis to build the new statement.
2150   /// Subclasses may override this routine to provide different behavior.
2151   OMPClause *
2152   RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2153                        ArrayRef<SourceLocation> MotionModifiersLoc,
2154                        CXXScopeSpec &MapperIdScopeSpec,
2155                        DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2156                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2157                        ArrayRef<Expr *> UnresolvedMappers) {
2158     return getSema().ActOnOpenMPFromClause(
2159         MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2160         ColonLoc, VarList, Locs, UnresolvedMappers);
2161   }
2162 
2163   /// Build a new OpenMP 'use_device_ptr' clause.
2164   ///
2165   /// By default, performs semantic analysis to build the new OpenMP clause.
2166   /// Subclasses may override this routine to provide different behavior.
2167   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2168                                           const OMPVarListLocTy &Locs) {
2169     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2170   }
2171 
2172   /// Build a new OpenMP 'use_device_addr' clause.
2173   ///
2174   /// By default, performs semantic analysis to build the new OpenMP clause.
2175   /// Subclasses may override this routine to provide different behavior.
2176   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2177                                            const OMPVarListLocTy &Locs) {
2178     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2179   }
2180 
2181   /// Build a new OpenMP 'is_device_ptr' clause.
2182   ///
2183   /// By default, performs semantic analysis to build the new OpenMP clause.
2184   /// Subclasses may override this routine to provide different behavior.
2185   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2186                                          const OMPVarListLocTy &Locs) {
2187     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2188   }
2189 
2190   /// Build a new OpenMP 'has_device_addr' clause.
2191   ///
2192   /// By default, performs semantic analysis to build the new OpenMP clause.
2193   /// Subclasses may override this routine to provide different behavior.
2194   OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2195                                            const OMPVarListLocTy &Locs) {
2196     return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2197   }
2198 
2199   /// Build a new OpenMP 'defaultmap' clause.
2200   ///
2201   /// By default, performs semantic analysis to build the new OpenMP clause.
2202   /// Subclasses may override this routine to provide different behavior.
2203   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2204                                         OpenMPDefaultmapClauseKind Kind,
2205                                         SourceLocation StartLoc,
2206                                         SourceLocation LParenLoc,
2207                                         SourceLocation MLoc,
2208                                         SourceLocation KindLoc,
2209                                         SourceLocation EndLoc) {
2210     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2211                                                  MLoc, KindLoc, EndLoc);
2212   }
2213 
2214   /// Build a new OpenMP 'nontemporal' clause.
2215   ///
2216   /// By default, performs semantic analysis to build the new OpenMP clause.
2217   /// Subclasses may override this routine to provide different behavior.
2218   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2219                                          SourceLocation StartLoc,
2220                                          SourceLocation LParenLoc,
2221                                          SourceLocation EndLoc) {
2222     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2223                                                   EndLoc);
2224   }
2225 
2226   /// Build a new OpenMP 'inclusive' clause.
2227   ///
2228   /// By default, performs semantic analysis to build the new OpenMP clause.
2229   /// Subclasses may override this routine to provide different behavior.
2230   OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2231                                        SourceLocation StartLoc,
2232                                        SourceLocation LParenLoc,
2233                                        SourceLocation EndLoc) {
2234     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2235                                                 EndLoc);
2236   }
2237 
2238   /// Build a new OpenMP 'exclusive' clause.
2239   ///
2240   /// By default, performs semantic analysis to build the new OpenMP clause.
2241   /// Subclasses may override this routine to provide different behavior.
2242   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2243                                        SourceLocation StartLoc,
2244                                        SourceLocation LParenLoc,
2245                                        SourceLocation EndLoc) {
2246     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2247                                                 EndLoc);
2248   }
2249 
2250   /// Build a new OpenMP 'uses_allocators' clause.
2251   ///
2252   /// By default, performs semantic analysis to build the new OpenMP clause.
2253   /// Subclasses may override this routine to provide different behavior.
2254   OMPClause *RebuildOMPUsesAllocatorsClause(
2255       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2256       SourceLocation LParenLoc, SourceLocation EndLoc) {
2257     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2258                                                     Data);
2259   }
2260 
2261   /// Build a new OpenMP 'affinity' clause.
2262   ///
2263   /// By default, performs semantic analysis to build the new OpenMP clause.
2264   /// Subclasses may override this routine to provide different behavior.
2265   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2266                                       SourceLocation LParenLoc,
2267                                       SourceLocation ColonLoc,
2268                                       SourceLocation EndLoc, Expr *Modifier,
2269                                       ArrayRef<Expr *> Locators) {
2270     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2271                                                EndLoc, Modifier, Locators);
2272   }
2273 
2274   /// Build a new OpenMP 'order' clause.
2275   ///
2276   /// By default, performs semantic analysis to build the new OpenMP clause.
2277   /// Subclasses may override this routine to provide different behavior.
2278   OMPClause *RebuildOMPOrderClause(
2279       OpenMPOrderClauseKind Kind, SourceLocation KindKwLoc,
2280       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
2281       OpenMPOrderClauseModifier Modifier, SourceLocation ModifierKwLoc) {
2282     return getSema().ActOnOpenMPOrderClause(Modifier, Kind, StartLoc, LParenLoc,
2283                                             ModifierKwLoc, KindKwLoc, EndLoc);
2284   }
2285 
2286   /// Build a new OpenMP 'init' clause.
2287   ///
2288   /// By default, performs semantic analysis to build the new OpenMP clause.
2289   /// Subclasses may override this routine to provide different behavior.
2290   OMPClause *RebuildOMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
2291                                   SourceLocation StartLoc,
2292                                   SourceLocation LParenLoc,
2293                                   SourceLocation VarLoc,
2294                                   SourceLocation EndLoc) {
2295     return getSema().ActOnOpenMPInitClause(InteropVar, InteropInfo, StartLoc,
2296                                            LParenLoc, VarLoc, EndLoc);
2297   }
2298 
2299   /// Build a new OpenMP 'use' clause.
2300   ///
2301   /// By default, performs semantic analysis to build the new OpenMP clause.
2302   /// Subclasses may override this routine to provide different behavior.
2303   OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2304                                  SourceLocation LParenLoc,
2305                                  SourceLocation VarLoc, SourceLocation EndLoc) {
2306     return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2307                                           VarLoc, EndLoc);
2308   }
2309 
2310   /// Build a new OpenMP 'destroy' clause.
2311   ///
2312   /// By default, performs semantic analysis to build the new OpenMP clause.
2313   /// Subclasses may override this routine to provide different behavior.
2314   OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2315                                      SourceLocation LParenLoc,
2316                                      SourceLocation VarLoc,
2317                                      SourceLocation EndLoc) {
2318     return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2319                                               VarLoc, EndLoc);
2320   }
2321 
2322   /// Build a new OpenMP 'novariants' clause.
2323   ///
2324   /// By default, performs semantic analysis to build the new OpenMP clause.
2325   /// Subclasses may override this routine to provide different behavior.
2326   OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2327                                         SourceLocation StartLoc,
2328                                         SourceLocation LParenLoc,
2329                                         SourceLocation EndLoc) {
2330     return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2331                                                  EndLoc);
2332   }
2333 
2334   /// Build a new OpenMP 'nocontext' clause.
2335   ///
2336   /// By default, performs semantic analysis to build the new OpenMP clause.
2337   /// Subclasses may override this routine to provide different behavior.
2338   OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2339                                        SourceLocation LParenLoc,
2340                                        SourceLocation EndLoc) {
2341     return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2342                                                 EndLoc);
2343   }
2344 
2345   /// Build a new OpenMP 'filter' clause.
2346   ///
2347   /// By default, performs semantic analysis to build the new OpenMP clause.
2348   /// Subclasses may override this routine to provide different behavior.
2349   OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2350                                     SourceLocation LParenLoc,
2351                                     SourceLocation EndLoc) {
2352     return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2353                                              EndLoc);
2354   }
2355 
2356   /// Build a new OpenMP 'bind' clause.
2357   ///
2358   /// By default, performs semantic analysis to build the new OpenMP clause.
2359   /// Subclasses may override this routine to provide different behavior.
2360   OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2361                                   SourceLocation KindLoc,
2362                                   SourceLocation StartLoc,
2363                                   SourceLocation LParenLoc,
2364                                   SourceLocation EndLoc) {
2365     return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2366                                            EndLoc);
2367   }
2368 
2369   /// Build a new OpenMP 'ompx_dyn_cgroup_mem' clause.
2370   ///
2371   /// By default, performs semantic analysis to build the new OpenMP clause.
2372   /// Subclasses may override this routine to provide different behavior.
2373   OMPClause *RebuildOMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
2374                                            SourceLocation LParenLoc,
2375                                            SourceLocation EndLoc) {
2376     return getSema().ActOnOpenMPXDynCGroupMemClause(Size, StartLoc, LParenLoc,
2377                                                     EndLoc);
2378   }
2379 
2380   /// Build a new OpenMP 'align' clause.
2381   ///
2382   /// By default, performs semantic analysis to build the new OpenMP clause.
2383   /// Subclasses may override this routine to provide different behavior.
2384   OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2385                                    SourceLocation LParenLoc,
2386                                    SourceLocation EndLoc) {
2387     return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2388   }
2389 
2390   /// Build a new OpenMP 'at' clause.
2391   ///
2392   /// By default, performs semantic analysis to build the new OpenMP clause.
2393   /// Subclasses may override this routine to provide different behavior.
2394   OMPClause *RebuildOMPAtClause(OpenMPAtClauseKind Kind, SourceLocation KwLoc,
2395                                 SourceLocation StartLoc,
2396                                 SourceLocation LParenLoc,
2397                                 SourceLocation EndLoc) {
2398     return getSema().ActOnOpenMPAtClause(Kind, KwLoc, StartLoc, LParenLoc,
2399                                          EndLoc);
2400   }
2401 
2402   /// Build a new OpenMP 'severity' clause.
2403   ///
2404   /// By default, performs semantic analysis to build the new OpenMP clause.
2405   /// Subclasses may override this routine to provide different behavior.
2406   OMPClause *RebuildOMPSeverityClause(OpenMPSeverityClauseKind Kind,
2407                                       SourceLocation KwLoc,
2408                                       SourceLocation StartLoc,
2409                                       SourceLocation LParenLoc,
2410                                       SourceLocation EndLoc) {
2411     return getSema().ActOnOpenMPSeverityClause(Kind, KwLoc, StartLoc, LParenLoc,
2412                                                EndLoc);
2413   }
2414 
2415   /// Build a new OpenMP 'message' clause.
2416   ///
2417   /// By default, performs semantic analysis to build the new OpenMP clause.
2418   /// Subclasses may override this routine to provide different behavior.
2419   OMPClause *RebuildOMPMessageClause(Expr *MS, SourceLocation StartLoc,
2420                                      SourceLocation LParenLoc,
2421                                      SourceLocation EndLoc) {
2422     return getSema().ActOnOpenMPMessageClause(MS, StartLoc, LParenLoc, EndLoc);
2423   }
2424 
2425   /// Build a new OpenMP 'doacross' 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 *
2430   RebuildOMPDoacrossClause(OpenMPDoacrossClauseModifier DepType,
2431                            SourceLocation DepLoc, SourceLocation ColonLoc,
2432                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
2433                            SourceLocation LParenLoc, SourceLocation EndLoc) {
2434     return getSema().ActOnOpenMPDoacrossClause(
2435         DepType, DepLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
2436   }
2437 
2438   /// Rebuild the operand to an Objective-C \@synchronized statement.
2439   ///
2440   /// By default, performs semantic analysis to build the new statement.
2441   /// Subclasses may override this routine to provide different behavior.
2442   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2443                                               Expr *object) {
2444     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2445   }
2446 
2447   /// Build a new Objective-C \@synchronized statement.
2448   ///
2449   /// By default, performs semantic analysis to build the new statement.
2450   /// Subclasses may override this routine to provide different behavior.
2451   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2452                                            Expr *Object, Stmt *Body) {
2453     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2454   }
2455 
2456   /// Build a new Objective-C \@autoreleasepool statement.
2457   ///
2458   /// By default, performs semantic analysis to build the new statement.
2459   /// Subclasses may override this routine to provide different behavior.
2460   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2461                                             Stmt *Body) {
2462     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2463   }
2464 
2465   /// Build a new Objective-C fast enumeration statement.
2466   ///
2467   /// By default, performs semantic analysis to build the new statement.
2468   /// Subclasses may override this routine to provide different behavior.
2469   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2470                                           Stmt *Element,
2471                                           Expr *Collection,
2472                                           SourceLocation RParenLoc,
2473                                           Stmt *Body) {
2474     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2475                                                 Element,
2476                                                 Collection,
2477                                                 RParenLoc);
2478     if (ForEachStmt.isInvalid())
2479       return StmtError();
2480 
2481     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2482   }
2483 
2484   /// Build a new C++ exception declaration.
2485   ///
2486   /// By default, performs semantic analysis to build the new decaration.
2487   /// Subclasses may override this routine to provide different behavior.
2488   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2489                                 TypeSourceInfo *Declarator,
2490                                 SourceLocation StartLoc,
2491                                 SourceLocation IdLoc,
2492                                 IdentifierInfo *Id) {
2493     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2494                                                        StartLoc, IdLoc, Id);
2495     if (Var)
2496       getSema().CurContext->addDecl(Var);
2497     return Var;
2498   }
2499 
2500   /// Build a new C++ catch statement.
2501   ///
2502   /// By default, performs semantic analysis to build the new statement.
2503   /// Subclasses may override this routine to provide different behavior.
2504   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2505                                  VarDecl *ExceptionDecl,
2506                                  Stmt *Handler) {
2507     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2508                                                       Handler));
2509   }
2510 
2511   /// Build a new C++ try statement.
2512   ///
2513   /// By default, performs semantic analysis to build the new statement.
2514   /// Subclasses may override this routine to provide different behavior.
2515   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2516                                ArrayRef<Stmt *> Handlers) {
2517     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2518   }
2519 
2520   /// Build a new C++0x range-based for statement.
2521   ///
2522   /// By default, performs semantic analysis to build the new statement.
2523   /// Subclasses may override this routine to provide different behavior.
2524   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2525                                     SourceLocation CoawaitLoc, Stmt *Init,
2526                                     SourceLocation ColonLoc, Stmt *Range,
2527                                     Stmt *Begin, Stmt *End, Expr *Cond,
2528                                     Expr *Inc, Stmt *LoopVar,
2529                                     SourceLocation RParenLoc) {
2530     // If we've just learned that the range is actually an Objective-C
2531     // collection, treat this as an Objective-C fast enumeration loop.
2532     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2533       if (RangeStmt->isSingleDecl()) {
2534         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2535           if (RangeVar->isInvalidDecl())
2536             return StmtError();
2537 
2538           Expr *RangeExpr = RangeVar->getInit();
2539           if (!RangeExpr->isTypeDependent() &&
2540               RangeExpr->getType()->isObjCObjectPointerType()) {
2541             // FIXME: Support init-statements in Objective-C++20 ranged for
2542             // statement.
2543             if (Init) {
2544               return SemaRef.Diag(Init->getBeginLoc(),
2545                                   diag::err_objc_for_range_init_stmt)
2546                          << Init->getSourceRange();
2547             }
2548             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2549                                                         RangeExpr, RParenLoc);
2550           }
2551         }
2552       }
2553     }
2554 
2555     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2556                                           Range, Begin, End, Cond, Inc, LoopVar,
2557                                           RParenLoc, Sema::BFRK_Rebuild);
2558   }
2559 
2560   /// Build a new C++0x range-based for statement.
2561   ///
2562   /// By default, performs semantic analysis to build the new statement.
2563   /// Subclasses may override this routine to provide different behavior.
2564   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2565                                           bool IsIfExists,
2566                                           NestedNameSpecifierLoc QualifierLoc,
2567                                           DeclarationNameInfo NameInfo,
2568                                           Stmt *Nested) {
2569     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2570                                                 QualifierLoc, NameInfo, Nested);
2571   }
2572 
2573   /// Attach body to a C++0x range-based for statement.
2574   ///
2575   /// By default, performs semantic analysis to finish the new statement.
2576   /// Subclasses may override this routine to provide different behavior.
2577   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2578     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2579   }
2580 
2581   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2582                                Stmt *TryBlock, Stmt *Handler) {
2583     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2584   }
2585 
2586   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2587                                   Stmt *Block) {
2588     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2589   }
2590 
2591   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2592     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2593   }
2594 
2595   ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2596                                              SourceLocation LParen,
2597                                              SourceLocation RParen,
2598                                              TypeSourceInfo *TSI) {
2599     return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2600   }
2601 
2602   /// Build a new predefined expression.
2603   ///
2604   /// By default, performs semantic analysis to build the new expression.
2605   /// Subclasses may override this routine to provide different behavior.
2606   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2607                                    PredefinedExpr::IdentKind IK) {
2608     return getSema().BuildPredefinedExpr(Loc, IK);
2609   }
2610 
2611   /// Build a new expression that references a declaration.
2612   ///
2613   /// By default, performs semantic analysis to build the new expression.
2614   /// Subclasses may override this routine to provide different behavior.
2615   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2616                                         LookupResult &R,
2617                                         bool RequiresADL) {
2618     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2619   }
2620 
2621 
2622   /// Build a new expression that references a declaration.
2623   ///
2624   /// By default, performs semantic analysis to build the new expression.
2625   /// Subclasses may override this routine to provide different behavior.
2626   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2627                                 ValueDecl *VD,
2628                                 const DeclarationNameInfo &NameInfo,
2629                                 NamedDecl *Found,
2630                                 TemplateArgumentListInfo *TemplateArgs) {
2631     CXXScopeSpec SS;
2632     SS.Adopt(QualifierLoc);
2633     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2634                                               TemplateArgs);
2635   }
2636 
2637   /// Build a new expression in parentheses.
2638   ///
2639   /// By default, performs semantic analysis to build the new expression.
2640   /// Subclasses may override this routine to provide different behavior.
2641   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2642                                     SourceLocation RParen) {
2643     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2644   }
2645 
2646   /// Build a new pseudo-destructor expression.
2647   ///
2648   /// By default, performs semantic analysis to build the new expression.
2649   /// Subclasses may override this routine to provide different behavior.
2650   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2651                                             SourceLocation OperatorLoc,
2652                                             bool isArrow,
2653                                             CXXScopeSpec &SS,
2654                                             TypeSourceInfo *ScopeType,
2655                                             SourceLocation CCLoc,
2656                                             SourceLocation TildeLoc,
2657                                         PseudoDestructorTypeStorage Destroyed);
2658 
2659   /// Build a new unary operator expression.
2660   ///
2661   /// By default, performs semantic analysis to build the new expression.
2662   /// Subclasses may override this routine to provide different behavior.
2663   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2664                                         UnaryOperatorKind Opc,
2665                                         Expr *SubExpr) {
2666     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2667   }
2668 
2669   /// Build a new builtin offsetof expression.
2670   ///
2671   /// By default, performs semantic analysis to build the new expression.
2672   /// Subclasses may override this routine to provide different behavior.
2673   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2674                                  TypeSourceInfo *Type,
2675                                  ArrayRef<Sema::OffsetOfComponent> Components,
2676                                  SourceLocation RParenLoc) {
2677     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2678                                           RParenLoc);
2679   }
2680 
2681   /// Build a new sizeof, alignof or vec_step expression with a
2682   /// type argument.
2683   ///
2684   /// By default, performs semantic analysis to build the new expression.
2685   /// Subclasses may override this routine to provide different behavior.
2686   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2687                                          SourceLocation OpLoc,
2688                                          UnaryExprOrTypeTrait ExprKind,
2689                                          SourceRange R) {
2690     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2691   }
2692 
2693   /// Build a new sizeof, alignof or vec step expression with an
2694   /// expression argument.
2695   ///
2696   /// By default, performs semantic analysis to build the new expression.
2697   /// Subclasses may override this routine to provide different behavior.
2698   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2699                                          UnaryExprOrTypeTrait ExprKind,
2700                                          SourceRange R) {
2701     ExprResult Result
2702       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2703     if (Result.isInvalid())
2704       return ExprError();
2705 
2706     return Result;
2707   }
2708 
2709   /// Build a new array subscript expression.
2710   ///
2711   /// By default, performs semantic analysis to build the new expression.
2712   /// Subclasses may override this routine to provide different behavior.
2713   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2714                                              SourceLocation LBracketLoc,
2715                                              Expr *RHS,
2716                                              SourceLocation RBracketLoc) {
2717     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2718                                              LBracketLoc, RHS,
2719                                              RBracketLoc);
2720   }
2721 
2722   /// Build a new matrix subscript expression.
2723   ///
2724   /// By default, performs semantic analysis to build the new expression.
2725   /// Subclasses may override this routine to provide different behavior.
2726   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2727                                         Expr *ColumnIdx,
2728                                         SourceLocation RBracketLoc) {
2729     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2730                                                       RBracketLoc);
2731   }
2732 
2733   /// Build a new array section expression.
2734   ///
2735   /// By default, performs semantic analysis to build the new expression.
2736   /// Subclasses may override this routine to provide different behavior.
2737   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2738                                         Expr *LowerBound,
2739                                         SourceLocation ColonLocFirst,
2740                                         SourceLocation ColonLocSecond,
2741                                         Expr *Length, Expr *Stride,
2742                                         SourceLocation RBracketLoc) {
2743     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2744                                               ColonLocFirst, ColonLocSecond,
2745                                               Length, Stride, RBracketLoc);
2746   }
2747 
2748   /// Build a new array shaping expression.
2749   ///
2750   /// By default, performs semantic analysis to build the new expression.
2751   /// Subclasses may override this routine to provide different behavior.
2752   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2753                                         SourceLocation RParenLoc,
2754                                         ArrayRef<Expr *> Dims,
2755                                         ArrayRef<SourceRange> BracketsRanges) {
2756     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2757                                               BracketsRanges);
2758   }
2759 
2760   /// Build a new iterator expression.
2761   ///
2762   /// By default, performs semantic analysis to build the new expression.
2763   /// Subclasses may override this routine to provide different behavior.
2764   ExprResult RebuildOMPIteratorExpr(
2765       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2766       ArrayRef<Sema::OMPIteratorData> Data) {
2767     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2768                                           LLoc, RLoc, Data);
2769   }
2770 
2771   /// Build a new call expression.
2772   ///
2773   /// By default, performs semantic analysis to build the new expression.
2774   /// Subclasses may override this routine to provide different behavior.
2775   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2776                                    MultiExprArg Args,
2777                                    SourceLocation RParenLoc,
2778                                    Expr *ExecConfig = nullptr) {
2779     return getSema().ActOnCallExpr(
2780         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2781   }
2782 
2783   ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2784                                      MultiExprArg Args,
2785                                      SourceLocation RParenLoc) {
2786     return getSema().ActOnArraySubscriptExpr(
2787         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2788   }
2789 
2790   /// Build a new member access expression.
2791   ///
2792   /// By default, performs semantic analysis to build the new expression.
2793   /// Subclasses may override this routine to provide different behavior.
2794   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2795                                bool isArrow,
2796                                NestedNameSpecifierLoc QualifierLoc,
2797                                SourceLocation TemplateKWLoc,
2798                                const DeclarationNameInfo &MemberNameInfo,
2799                                ValueDecl *Member,
2800                                NamedDecl *FoundDecl,
2801                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2802                                NamedDecl *FirstQualifierInScope) {
2803     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2804                                                                       isArrow);
2805     if (!Member->getDeclName()) {
2806       // We have a reference to an unnamed field.  This is always the
2807       // base of an anonymous struct/union member access, i.e. the
2808       // field is always of record type.
2809       assert(Member->getType()->isRecordType() &&
2810              "unnamed member not of record type?");
2811 
2812       BaseResult =
2813         getSema().PerformObjectMemberConversion(BaseResult.get(),
2814                                                 QualifierLoc.getNestedNameSpecifier(),
2815                                                 FoundDecl, Member);
2816       if (BaseResult.isInvalid())
2817         return ExprError();
2818       Base = BaseResult.get();
2819 
2820       CXXScopeSpec EmptySS;
2821       return getSema().BuildFieldReferenceExpr(
2822           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2823           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2824     }
2825 
2826     CXXScopeSpec SS;
2827     SS.Adopt(QualifierLoc);
2828 
2829     Base = BaseResult.get();
2830     QualType BaseType = Base->getType();
2831 
2832     if (isArrow && !BaseType->isPointerType())
2833       return ExprError();
2834 
2835     // FIXME: this involves duplicating earlier analysis in a lot of
2836     // cases; we should avoid this when possible.
2837     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2838     R.addDecl(FoundDecl);
2839     R.resolveKind();
2840 
2841     if (getSema().isUnevaluatedContext() && Base->isImplicitCXXThis() &&
2842         isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(Member)) {
2843       if (auto *ThisClass = cast<CXXThisExpr>(Base)
2844                                 ->getType()
2845                                 ->getPointeeType()
2846                                 ->getAsCXXRecordDecl()) {
2847         auto *Class = cast<CXXRecordDecl>(Member->getDeclContext());
2848         // In unevaluated contexts, an expression supposed to be a member access
2849         // might reference a member in an unrelated class.
2850         if (!ThisClass->Equals(Class) && !ThisClass->isDerivedFrom(Class))
2851           return getSema().BuildDeclRefExpr(Member, Member->getType(),
2852                                             VK_LValue, Member->getLocation());
2853       }
2854     }
2855 
2856     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2857                                               SS, TemplateKWLoc,
2858                                               FirstQualifierInScope,
2859                                               R, ExplicitTemplateArgs,
2860                                               /*S*/nullptr);
2861   }
2862 
2863   /// Build a new binary operator expression.
2864   ///
2865   /// By default, performs semantic analysis to build the new expression.
2866   /// Subclasses may override this routine to provide different behavior.
2867   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2868                                          BinaryOperatorKind Opc,
2869                                          Expr *LHS, Expr *RHS) {
2870     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2871   }
2872 
2873   /// Build a new rewritten operator expression.
2874   ///
2875   /// By default, performs semantic analysis to build the new expression.
2876   /// Subclasses may override this routine to provide different behavior.
2877   ExprResult RebuildCXXRewrittenBinaryOperator(
2878       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2879       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2880     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2881                                            RHS, /*RequiresADL*/false);
2882   }
2883 
2884   /// Build a new conditional operator expression.
2885   ///
2886   /// By default, performs semantic analysis to build the new expression.
2887   /// Subclasses may override this routine to provide different behavior.
2888   ExprResult RebuildConditionalOperator(Expr *Cond,
2889                                         SourceLocation QuestionLoc,
2890                                         Expr *LHS,
2891                                         SourceLocation ColonLoc,
2892                                         Expr *RHS) {
2893     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2894                                         LHS, RHS);
2895   }
2896 
2897   /// Build a new C-style cast expression.
2898   ///
2899   /// By default, performs semantic analysis to build the new expression.
2900   /// Subclasses may override this routine to provide different behavior.
2901   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2902                                          TypeSourceInfo *TInfo,
2903                                          SourceLocation RParenLoc,
2904                                          Expr *SubExpr) {
2905     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2906                                          SubExpr);
2907   }
2908 
2909   /// Build a new compound literal expression.
2910   ///
2911   /// By default, performs semantic analysis to build the new expression.
2912   /// Subclasses may override this routine to provide different behavior.
2913   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2914                                               TypeSourceInfo *TInfo,
2915                                               SourceLocation RParenLoc,
2916                                               Expr *Init) {
2917     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2918                                               Init);
2919   }
2920 
2921   /// Build a new extended vector element access expression.
2922   ///
2923   /// By default, performs semantic analysis to build the new expression.
2924   /// Subclasses may override this routine to provide different behavior.
2925   ExprResult RebuildExtVectorElementExpr(Expr *Base, SourceLocation OpLoc,
2926                                          bool IsArrow,
2927                                          SourceLocation AccessorLoc,
2928                                          IdentifierInfo &Accessor) {
2929 
2930     CXXScopeSpec SS;
2931     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2932     return getSema().BuildMemberReferenceExpr(
2933         Base, Base->getType(), OpLoc, IsArrow, SS, SourceLocation(),
2934         /*FirstQualifierInScope*/ nullptr, NameInfo,
2935         /* TemplateArgs */ nullptr,
2936         /*S*/ nullptr);
2937   }
2938 
2939   /// Build a new initializer list expression.
2940   ///
2941   /// By default, performs semantic analysis to build the new expression.
2942   /// Subclasses may override this routine to provide different behavior.
2943   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2944                              MultiExprArg Inits,
2945                              SourceLocation RBraceLoc) {
2946     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2947   }
2948 
2949   /// Build a new designated initializer expression.
2950   ///
2951   /// By default, performs semantic analysis to build the new expression.
2952   /// Subclasses may override this routine to provide different behavior.
2953   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2954                                              MultiExprArg ArrayExprs,
2955                                              SourceLocation EqualOrColonLoc,
2956                                              bool GNUSyntax,
2957                                              Expr *Init) {
2958     ExprResult Result
2959       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2960                                            Init);
2961     if (Result.isInvalid())
2962       return ExprError();
2963 
2964     return Result;
2965   }
2966 
2967   /// Build a new value-initialized expression.
2968   ///
2969   /// By default, builds the implicit value initialization without performing
2970   /// any semantic analysis. Subclasses may override this routine to provide
2971   /// different behavior.
2972   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2973     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2974   }
2975 
2976   /// Build a new \c va_arg expression.
2977   ///
2978   /// By default, performs semantic analysis to build the new expression.
2979   /// Subclasses may override this routine to provide different behavior.
2980   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2981                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2982                                     SourceLocation RParenLoc) {
2983     return getSema().BuildVAArgExpr(BuiltinLoc,
2984                                     SubExpr, TInfo,
2985                                     RParenLoc);
2986   }
2987 
2988   /// Build a new expression list in parentheses.
2989   ///
2990   /// By default, performs semantic analysis to build the new expression.
2991   /// Subclasses may override this routine to provide different behavior.
2992   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2993                                   MultiExprArg SubExprs,
2994                                   SourceLocation RParenLoc) {
2995     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2996   }
2997 
2998   /// Build a new address-of-label expression.
2999   ///
3000   /// By default, performs semantic analysis, using the name of the label
3001   /// rather than attempting to map the label statement itself.
3002   /// Subclasses may override this routine to provide different behavior.
3003   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
3004                                   SourceLocation LabelLoc, LabelDecl *Label) {
3005     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
3006   }
3007 
3008   /// Build a new GNU statement expression.
3009   ///
3010   /// By default, performs semantic analysis to build the new expression.
3011   /// Subclasses may override this routine to provide different behavior.
3012   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
3013                              SourceLocation RParenLoc, unsigned TemplateDepth) {
3014     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
3015                                    TemplateDepth);
3016   }
3017 
3018   /// Build a new __builtin_choose_expr expression.
3019   ///
3020   /// By default, performs semantic analysis to build the new expression.
3021   /// Subclasses may override this routine to provide different behavior.
3022   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
3023                                      Expr *Cond, Expr *LHS, Expr *RHS,
3024                                      SourceLocation RParenLoc) {
3025     return SemaRef.ActOnChooseExpr(BuiltinLoc,
3026                                    Cond, LHS, RHS,
3027                                    RParenLoc);
3028   }
3029 
3030   /// Build a new generic selection expression with an expression predicate.
3031   ///
3032   /// By default, performs semantic analysis to build the new expression.
3033   /// Subclasses may override this routine to provide different behavior.
3034   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3035                                          SourceLocation DefaultLoc,
3036                                          SourceLocation RParenLoc,
3037                                          Expr *ControllingExpr,
3038                                          ArrayRef<TypeSourceInfo *> Types,
3039                                          ArrayRef<Expr *> Exprs) {
3040     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3041                                                 /*PredicateIsExpr=*/true,
3042                                                 ControllingExpr, Types, Exprs);
3043   }
3044 
3045   /// Build a new generic selection expression with a type predicate.
3046   ///
3047   /// By default, performs semantic analysis to build the new expression.
3048   /// Subclasses may override this routine to provide different behavior.
3049   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3050                                          SourceLocation DefaultLoc,
3051                                          SourceLocation RParenLoc,
3052                                          TypeSourceInfo *ControllingType,
3053                                          ArrayRef<TypeSourceInfo *> Types,
3054                                          ArrayRef<Expr *> Exprs) {
3055     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3056                                                 /*PredicateIsExpr=*/false,
3057                                                 ControllingType, Types, Exprs);
3058   }
3059 
3060   /// Build a new overloaded operator call expression.
3061   ///
3062   /// By default, performs semantic analysis to build the new expression.
3063   /// The semantic analysis provides the behavior of template instantiation,
3064   /// copying with transformations that turn what looks like an overloaded
3065   /// operator call into a use of a builtin operator, performing
3066   /// argument-dependent lookup, etc. Subclasses may override this routine to
3067   /// provide different behavior.
3068   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
3069                                         SourceLocation OpLoc,
3070                                         SourceLocation CalleeLoc,
3071                                         bool RequiresADL,
3072                                         const UnresolvedSetImpl &Functions,
3073                                         Expr *First, Expr *Second);
3074 
3075   /// Build a new C++ "named" cast expression, such as static_cast or
3076   /// reinterpret_cast.
3077   ///
3078   /// By default, this routine dispatches to one of the more-specific routines
3079   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
3080   /// Subclasses may override this routine to provide different behavior.
3081   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
3082                                            Stmt::StmtClass Class,
3083                                            SourceLocation LAngleLoc,
3084                                            TypeSourceInfo *TInfo,
3085                                            SourceLocation RAngleLoc,
3086                                            SourceLocation LParenLoc,
3087                                            Expr *SubExpr,
3088                                            SourceLocation RParenLoc) {
3089     switch (Class) {
3090     case Stmt::CXXStaticCastExprClass:
3091       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
3092                                                    RAngleLoc, LParenLoc,
3093                                                    SubExpr, RParenLoc);
3094 
3095     case Stmt::CXXDynamicCastExprClass:
3096       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
3097                                                     RAngleLoc, LParenLoc,
3098                                                     SubExpr, RParenLoc);
3099 
3100     case Stmt::CXXReinterpretCastExprClass:
3101       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
3102                                                         RAngleLoc, LParenLoc,
3103                                                         SubExpr,
3104                                                         RParenLoc);
3105 
3106     case Stmt::CXXConstCastExprClass:
3107       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
3108                                                    RAngleLoc, LParenLoc,
3109                                                    SubExpr, RParenLoc);
3110 
3111     case Stmt::CXXAddrspaceCastExprClass:
3112       return getDerived().RebuildCXXAddrspaceCastExpr(
3113           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
3114 
3115     default:
3116       llvm_unreachable("Invalid C++ named cast");
3117     }
3118   }
3119 
3120   /// Build a new C++ static_cast expression.
3121   ///
3122   /// By default, performs semantic analysis to build the new expression.
3123   /// Subclasses may override this routine to provide different behavior.
3124   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
3125                                             SourceLocation LAngleLoc,
3126                                             TypeSourceInfo *TInfo,
3127                                             SourceLocation RAngleLoc,
3128                                             SourceLocation LParenLoc,
3129                                             Expr *SubExpr,
3130                                             SourceLocation RParenLoc) {
3131     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
3132                                        TInfo, SubExpr,
3133                                        SourceRange(LAngleLoc, RAngleLoc),
3134                                        SourceRange(LParenLoc, RParenLoc));
3135   }
3136 
3137   /// Build a new C++ dynamic_cast expression.
3138   ///
3139   /// By default, performs semantic analysis to build the new expression.
3140   /// Subclasses may override this routine to provide different behavior.
3141   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
3142                                              SourceLocation LAngleLoc,
3143                                              TypeSourceInfo *TInfo,
3144                                              SourceLocation RAngleLoc,
3145                                              SourceLocation LParenLoc,
3146                                              Expr *SubExpr,
3147                                              SourceLocation RParenLoc) {
3148     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
3149                                        TInfo, SubExpr,
3150                                        SourceRange(LAngleLoc, RAngleLoc),
3151                                        SourceRange(LParenLoc, RParenLoc));
3152   }
3153 
3154   /// Build a new C++ reinterpret_cast expression.
3155   ///
3156   /// By default, performs semantic analysis to build the new expression.
3157   /// Subclasses may override this routine to provide different behavior.
3158   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3159                                                  SourceLocation LAngleLoc,
3160                                                  TypeSourceInfo *TInfo,
3161                                                  SourceLocation RAngleLoc,
3162                                                  SourceLocation LParenLoc,
3163                                                  Expr *SubExpr,
3164                                                  SourceLocation RParenLoc) {
3165     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3166                                        TInfo, SubExpr,
3167                                        SourceRange(LAngleLoc, RAngleLoc),
3168                                        SourceRange(LParenLoc, RParenLoc));
3169   }
3170 
3171   /// Build a new C++ const_cast expression.
3172   ///
3173   /// By default, performs semantic analysis to build the new expression.
3174   /// Subclasses may override this routine to provide different behavior.
3175   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3176                                            SourceLocation LAngleLoc,
3177                                            TypeSourceInfo *TInfo,
3178                                            SourceLocation RAngleLoc,
3179                                            SourceLocation LParenLoc,
3180                                            Expr *SubExpr,
3181                                            SourceLocation RParenLoc) {
3182     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3183                                        TInfo, SubExpr,
3184                                        SourceRange(LAngleLoc, RAngleLoc),
3185                                        SourceRange(LParenLoc, RParenLoc));
3186   }
3187 
3188   ExprResult
3189   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3190                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3191                               SourceLocation LParenLoc, Expr *SubExpr,
3192                               SourceLocation RParenLoc) {
3193     return getSema().BuildCXXNamedCast(
3194         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3195         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3196   }
3197 
3198   /// Build a new C++ functional-style cast expression.
3199   ///
3200   /// By default, performs semantic analysis to build the new expression.
3201   /// Subclasses may override this routine to provide different behavior.
3202   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3203                                           SourceLocation LParenLoc,
3204                                           Expr *Sub,
3205                                           SourceLocation RParenLoc,
3206                                           bool ListInitialization) {
3207     // If Sub is a ParenListExpr, then Sub is the syntatic form of a
3208     // CXXParenListInitExpr. Pass its expanded arguments so that the
3209     // CXXParenListInitExpr can be rebuilt.
3210     if (auto *PLE = dyn_cast<ParenListExpr>(Sub))
3211       return getSema().BuildCXXTypeConstructExpr(
3212           TInfo, LParenLoc, MultiExprArg(PLE->getExprs(), PLE->getNumExprs()),
3213           RParenLoc, ListInitialization);
3214     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3215                                                MultiExprArg(&Sub, 1), RParenLoc,
3216                                                ListInitialization);
3217   }
3218 
3219   /// Build a new C++ __builtin_bit_cast expression.
3220   ///
3221   /// By default, performs semantic analysis to build the new expression.
3222   /// Subclasses may override this routine to provide different behavior.
3223   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3224                                        TypeSourceInfo *TSI, Expr *Sub,
3225                                        SourceLocation RParenLoc) {
3226     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3227   }
3228 
3229   /// Build a new C++ typeid(type) expression.
3230   ///
3231   /// By default, performs semantic analysis to build the new expression.
3232   /// Subclasses may override this routine to provide different behavior.
3233   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3234                                         SourceLocation TypeidLoc,
3235                                         TypeSourceInfo *Operand,
3236                                         SourceLocation RParenLoc) {
3237     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3238                                     RParenLoc);
3239   }
3240 
3241 
3242   /// Build a new C++ typeid(expr) expression.
3243   ///
3244   /// By default, performs semantic analysis to build the new expression.
3245   /// Subclasses may override this routine to provide different behavior.
3246   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3247                                         SourceLocation TypeidLoc,
3248                                         Expr *Operand,
3249                                         SourceLocation RParenLoc) {
3250     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3251                                     RParenLoc);
3252   }
3253 
3254   /// Build a new C++ __uuidof(type) expression.
3255   ///
3256   /// By default, performs semantic analysis to build the new expression.
3257   /// Subclasses may override this routine to provide different behavior.
3258   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3259                                   TypeSourceInfo *Operand,
3260                                   SourceLocation RParenLoc) {
3261     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3262   }
3263 
3264   /// Build a new C++ __uuidof(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 RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3269                                   Expr *Operand, SourceLocation RParenLoc) {
3270     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3271   }
3272 
3273   /// Build a new C++ "this" expression.
3274   ///
3275   /// By default, builds a new "this" expression without performing any
3276   /// semantic analysis. Subclasses may override this routine to provide
3277   /// different behavior.
3278   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3279                                 QualType ThisType,
3280                                 bool isImplicit) {
3281     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3282   }
3283 
3284   /// Build a new C++ throw expression.
3285   ///
3286   /// By default, performs semantic analysis to build the new expression.
3287   /// Subclasses may override this routine to provide different behavior.
3288   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3289                                  bool IsThrownVariableInScope) {
3290     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3291   }
3292 
3293   /// Build a new C++ default-argument expression.
3294   ///
3295   /// By default, builds a new default-argument expression, which does not
3296   /// require any semantic analysis. Subclasses may override this routine to
3297   /// provide different behavior.
3298   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param,
3299                                       Expr *RewrittenExpr) {
3300     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3301                                      RewrittenExpr, getSema().CurContext);
3302   }
3303 
3304   /// Build a new C++11 default-initialization expression.
3305   ///
3306   /// By default, builds a new default field initialization expression, which
3307   /// does not require any semantic analysis. Subclasses may override this
3308   /// routine to provide different behavior.
3309   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3310                                        FieldDecl *Field) {
3311     return getSema().BuildCXXDefaultInitExpr(Loc, Field);
3312   }
3313 
3314   /// Build a new C++ zero-initialization expression.
3315   ///
3316   /// By default, performs semantic analysis to build the new expression.
3317   /// Subclasses may override this routine to provide different behavior.
3318   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3319                                            SourceLocation LParenLoc,
3320                                            SourceLocation RParenLoc) {
3321     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, std::nullopt,
3322                                                RParenLoc,
3323                                                /*ListInitialization=*/false);
3324   }
3325 
3326   /// Build a new C++ "new" expression.
3327   ///
3328   /// By default, performs semantic analysis to build the new expression.
3329   /// Subclasses may override this routine to provide different behavior.
3330   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal,
3331                                SourceLocation PlacementLParen,
3332                                MultiExprArg PlacementArgs,
3333                                SourceLocation PlacementRParen,
3334                                SourceRange TypeIdParens, QualType AllocatedType,
3335                                TypeSourceInfo *AllocatedTypeInfo,
3336                                std::optional<Expr *> ArraySize,
3337                                SourceRange DirectInitRange, Expr *Initializer) {
3338     return getSema().BuildCXXNew(StartLoc, UseGlobal,
3339                                  PlacementLParen,
3340                                  PlacementArgs,
3341                                  PlacementRParen,
3342                                  TypeIdParens,
3343                                  AllocatedType,
3344                                  AllocatedTypeInfo,
3345                                  ArraySize,
3346                                  DirectInitRange,
3347                                  Initializer);
3348   }
3349 
3350   /// Build a new C++ "delete" expression.
3351   ///
3352   /// By default, performs semantic analysis to build the new expression.
3353   /// Subclasses may override this routine to provide different behavior.
3354   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3355                                         bool IsGlobalDelete,
3356                                         bool IsArrayForm,
3357                                         Expr *Operand) {
3358     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3359                                     Operand);
3360   }
3361 
3362   /// Build a new type trait expression.
3363   ///
3364   /// By default, performs semantic analysis to build the new expression.
3365   /// Subclasses may override this routine to provide different behavior.
3366   ExprResult RebuildTypeTrait(TypeTrait Trait,
3367                               SourceLocation StartLoc,
3368                               ArrayRef<TypeSourceInfo *> Args,
3369                               SourceLocation RParenLoc) {
3370     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3371   }
3372 
3373   /// Build a new array type trait expression.
3374   ///
3375   /// By default, performs semantic analysis to build the new expression.
3376   /// Subclasses may override this routine to provide different behavior.
3377   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3378                                    SourceLocation StartLoc,
3379                                    TypeSourceInfo *TSInfo,
3380                                    Expr *DimExpr,
3381                                    SourceLocation RParenLoc) {
3382     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3383   }
3384 
3385   /// Build a new expression trait expression.
3386   ///
3387   /// By default, performs semantic analysis to build the new expression.
3388   /// Subclasses may override this routine to provide different behavior.
3389   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3390                                    SourceLocation StartLoc,
3391                                    Expr *Queried,
3392                                    SourceLocation RParenLoc) {
3393     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3394   }
3395 
3396   /// Build a new (previously unresolved) declaration reference
3397   /// expression.
3398   ///
3399   /// By default, performs semantic analysis to build the new expression.
3400   /// Subclasses may override this routine to provide different behavior.
3401   ExprResult RebuildDependentScopeDeclRefExpr(
3402                                           NestedNameSpecifierLoc QualifierLoc,
3403                                           SourceLocation TemplateKWLoc,
3404                                        const DeclarationNameInfo &NameInfo,
3405                               const TemplateArgumentListInfo *TemplateArgs,
3406                                           bool IsAddressOfOperand,
3407                                           TypeSourceInfo **RecoveryTSI) {
3408     CXXScopeSpec SS;
3409     SS.Adopt(QualifierLoc);
3410 
3411     if (TemplateArgs || TemplateKWLoc.isValid())
3412       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3413                                                     TemplateArgs);
3414 
3415     return getSema().BuildQualifiedDeclarationNameExpr(
3416         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3417   }
3418 
3419   /// Build a new template-id 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 RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3424                                    SourceLocation TemplateKWLoc,
3425                                    LookupResult &R,
3426                                    bool RequiresADL,
3427                               const TemplateArgumentListInfo *TemplateArgs) {
3428     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3429                                          TemplateArgs);
3430   }
3431 
3432   /// Build a new object-construction expression.
3433   ///
3434   /// By default, performs semantic analysis to build the new expression.
3435   /// Subclasses may override this routine to provide different behavior.
3436   ExprResult RebuildCXXConstructExpr(QualType T,
3437                                      SourceLocation Loc,
3438                                      CXXConstructorDecl *Constructor,
3439                                      bool IsElidable,
3440                                      MultiExprArg Args,
3441                                      bool HadMultipleCandidates,
3442                                      bool ListInitialization,
3443                                      bool StdInitListInitialization,
3444                                      bool RequiresZeroInit,
3445                              CXXConstructExpr::ConstructionKind ConstructKind,
3446                                      SourceRange ParenRange) {
3447     // Reconstruct the constructor we originally found, which might be
3448     // different if this is a call to an inherited constructor.
3449     CXXConstructorDecl *FoundCtor = Constructor;
3450     if (Constructor->isInheritingConstructor())
3451       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3452 
3453     SmallVector<Expr *, 8> ConvertedArgs;
3454     if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3455                                           ConvertedArgs))
3456       return ExprError();
3457 
3458     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3459                                            IsElidable,
3460                                            ConvertedArgs,
3461                                            HadMultipleCandidates,
3462                                            ListInitialization,
3463                                            StdInitListInitialization,
3464                                            RequiresZeroInit, ConstructKind,
3465                                            ParenRange);
3466   }
3467 
3468   /// Build a new implicit construction via inherited constructor
3469   /// expression.
3470   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3471                                              CXXConstructorDecl *Constructor,
3472                                              bool ConstructsVBase,
3473                                              bool InheritedFromVBase) {
3474     return new (getSema().Context) CXXInheritedCtorInitExpr(
3475         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3476   }
3477 
3478   /// Build a new object-construction expression.
3479   ///
3480   /// By default, performs semantic analysis to build the new expression.
3481   /// Subclasses may override this routine to provide different behavior.
3482   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3483                                            SourceLocation LParenOrBraceLoc,
3484                                            MultiExprArg Args,
3485                                            SourceLocation RParenOrBraceLoc,
3486                                            bool ListInitialization) {
3487     return getSema().BuildCXXTypeConstructExpr(
3488         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3489   }
3490 
3491   /// Build a new object-construction expression.
3492   ///
3493   /// By default, performs semantic analysis to build the new expression.
3494   /// Subclasses may override this routine to provide different behavior.
3495   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3496                                                SourceLocation LParenLoc,
3497                                                MultiExprArg Args,
3498                                                SourceLocation RParenLoc,
3499                                                bool ListInitialization) {
3500     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3501                                                RParenLoc, ListInitialization);
3502   }
3503 
3504   /// Build a new member reference expression.
3505   ///
3506   /// By default, performs semantic analysis to build the new expression.
3507   /// Subclasses may override this routine to provide different behavior.
3508   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3509                                                 QualType BaseType,
3510                                                 bool IsArrow,
3511                                                 SourceLocation OperatorLoc,
3512                                           NestedNameSpecifierLoc QualifierLoc,
3513                                                 SourceLocation TemplateKWLoc,
3514                                             NamedDecl *FirstQualifierInScope,
3515                                    const DeclarationNameInfo &MemberNameInfo,
3516                               const TemplateArgumentListInfo *TemplateArgs) {
3517     CXXScopeSpec SS;
3518     SS.Adopt(QualifierLoc);
3519 
3520     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3521                                             OperatorLoc, IsArrow,
3522                                             SS, TemplateKWLoc,
3523                                             FirstQualifierInScope,
3524                                             MemberNameInfo,
3525                                             TemplateArgs, /*S*/nullptr);
3526   }
3527 
3528   /// Build a new member reference expression.
3529   ///
3530   /// By default, performs semantic analysis to build the new expression.
3531   /// Subclasses may override this routine to provide different behavior.
3532   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3533                                          SourceLocation OperatorLoc,
3534                                          bool IsArrow,
3535                                          NestedNameSpecifierLoc QualifierLoc,
3536                                          SourceLocation TemplateKWLoc,
3537                                          NamedDecl *FirstQualifierInScope,
3538                                          LookupResult &R,
3539                                 const TemplateArgumentListInfo *TemplateArgs) {
3540     CXXScopeSpec SS;
3541     SS.Adopt(QualifierLoc);
3542 
3543     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3544                                             OperatorLoc, IsArrow,
3545                                             SS, TemplateKWLoc,
3546                                             FirstQualifierInScope,
3547                                             R, TemplateArgs, /*S*/nullptr);
3548   }
3549 
3550   /// Build a new noexcept expression.
3551   ///
3552   /// By default, performs semantic analysis to build the new expression.
3553   /// Subclasses may override this routine to provide different behavior.
3554   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3555     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3556   }
3557 
3558   /// Build a new expression to compute the length of a parameter pack.
3559   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
3560                                    SourceLocation PackLoc,
3561                                    SourceLocation RParenLoc,
3562                                    std::optional<unsigned> Length,
3563                                    ArrayRef<TemplateArgument> PartialArgs) {
3564     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3565                                   RParenLoc, Length, PartialArgs);
3566   }
3567 
3568   /// Build a new expression representing a call to a source location
3569   ///  builtin.
3570   ///
3571   /// By default, performs semantic analysis to build the new expression.
3572   /// Subclasses may override this routine to provide different behavior.
3573   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3574                                   QualType ResultTy, SourceLocation BuiltinLoc,
3575                                   SourceLocation RPLoc,
3576                                   DeclContext *ParentContext) {
3577     return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3578                                         ParentContext);
3579   }
3580 
3581   /// Build a new Objective-C boxed expression.
3582   ///
3583   /// By default, performs semantic analysis to build the new expression.
3584   /// Subclasses may override this routine to provide different behavior.
3585   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3586       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3587       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3588       TemplateArgumentListInfo *TALI) {
3589     CXXScopeSpec SS;
3590     SS.Adopt(NNS);
3591     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3592                                                          ConceptNameInfo,
3593                                                          FoundDecl,
3594                                                          NamedConcept, TALI);
3595     if (Result.isInvalid())
3596       return ExprError();
3597     return Result;
3598   }
3599 
3600   /// \brief Build a new requires expression.
3601   ///
3602   /// By default, performs semantic analysis to build the new expression.
3603   /// Subclasses may override this routine to provide different behavior.
3604   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3605                                  RequiresExprBodyDecl *Body,
3606                                  ArrayRef<ParmVarDecl *> LocalParameters,
3607                                  ArrayRef<concepts::Requirement *> Requirements,
3608                                  SourceLocation ClosingBraceLoc) {
3609     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3610                                 LocalParameters, Requirements, ClosingBraceLoc);
3611   }
3612 
3613   concepts::TypeRequirement *
3614   RebuildTypeRequirement(
3615       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3616     return SemaRef.BuildTypeRequirement(SubstDiag);
3617   }
3618 
3619   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3620     return SemaRef.BuildTypeRequirement(T);
3621   }
3622 
3623   concepts::ExprRequirement *
3624   RebuildExprRequirement(
3625       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3626       SourceLocation NoexceptLoc,
3627       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3628     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3629                                         std::move(Ret));
3630   }
3631 
3632   concepts::ExprRequirement *
3633   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3634                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3635     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3636                                         std::move(Ret));
3637   }
3638 
3639   concepts::NestedRequirement *
3640   RebuildNestedRequirement(StringRef InvalidConstraintEntity,
3641                            const ASTConstraintSatisfaction &Satisfaction) {
3642     return SemaRef.BuildNestedRequirement(InvalidConstraintEntity,
3643                                           Satisfaction);
3644   }
3645 
3646   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3647     return SemaRef.BuildNestedRequirement(Constraint);
3648   }
3649 
3650   /// \brief Build a new Objective-C boxed expression.
3651   ///
3652   /// By default, performs semantic analysis to build the new expression.
3653   /// Subclasses may override this routine to provide different behavior.
3654   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3655     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3656   }
3657 
3658   /// Build a new Objective-C array literal.
3659   ///
3660   /// By default, performs semantic analysis to build the new expression.
3661   /// Subclasses may override this routine to provide different behavior.
3662   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3663                                      Expr **Elements, unsigned NumElements) {
3664     return getSema().BuildObjCArrayLiteral(Range,
3665                                            MultiExprArg(Elements, NumElements));
3666   }
3667 
3668   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3669                                          Expr *Base, Expr *Key,
3670                                          ObjCMethodDecl *getterMethod,
3671                                          ObjCMethodDecl *setterMethod) {
3672     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3673                                                    getterMethod, setterMethod);
3674   }
3675 
3676   /// Build a new Objective-C dictionary literal.
3677   ///
3678   /// By default, performs semantic analysis to build the new expression.
3679   /// Subclasses may override this routine to provide different behavior.
3680   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3681                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3682     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3683   }
3684 
3685   /// Build a new Objective-C \@encode expression.
3686   ///
3687   /// By default, performs semantic analysis to build the new expression.
3688   /// Subclasses may override this routine to provide different behavior.
3689   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3690                                          TypeSourceInfo *EncodeTypeInfo,
3691                                          SourceLocation RParenLoc) {
3692     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3693   }
3694 
3695   /// Build a new Objective-C class message.
3696   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3697                                           Selector Sel,
3698                                           ArrayRef<SourceLocation> SelectorLocs,
3699                                           ObjCMethodDecl *Method,
3700                                           SourceLocation LBracLoc,
3701                                           MultiExprArg Args,
3702                                           SourceLocation RBracLoc) {
3703     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3704                                      ReceiverTypeInfo->getType(),
3705                                      /*SuperLoc=*/SourceLocation(),
3706                                      Sel, Method, LBracLoc, SelectorLocs,
3707                                      RBracLoc, Args);
3708   }
3709 
3710   /// Build a new Objective-C instance message.
3711   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3712                                           Selector Sel,
3713                                           ArrayRef<SourceLocation> SelectorLocs,
3714                                           ObjCMethodDecl *Method,
3715                                           SourceLocation LBracLoc,
3716                                           MultiExprArg Args,
3717                                           SourceLocation RBracLoc) {
3718     return SemaRef.BuildInstanceMessage(Receiver,
3719                                         Receiver->getType(),
3720                                         /*SuperLoc=*/SourceLocation(),
3721                                         Sel, Method, LBracLoc, SelectorLocs,
3722                                         RBracLoc, Args);
3723   }
3724 
3725   /// Build a new Objective-C instance/class message to 'super'.
3726   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3727                                     Selector Sel,
3728                                     ArrayRef<SourceLocation> SelectorLocs,
3729                                     QualType SuperType,
3730                                     ObjCMethodDecl *Method,
3731                                     SourceLocation LBracLoc,
3732                                     MultiExprArg Args,
3733                                     SourceLocation RBracLoc) {
3734     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3735                                           SuperType,
3736                                           SuperLoc,
3737                                           Sel, Method, LBracLoc, SelectorLocs,
3738                                           RBracLoc, Args)
3739                                       : SemaRef.BuildClassMessage(nullptr,
3740                                           SuperType,
3741                                           SuperLoc,
3742                                           Sel, Method, LBracLoc, SelectorLocs,
3743                                           RBracLoc, Args);
3744 
3745 
3746   }
3747 
3748   /// Build a new Objective-C ivar reference expression.
3749   ///
3750   /// By default, performs semantic analysis to build the new expression.
3751   /// Subclasses may override this routine to provide different behavior.
3752   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3753                                           SourceLocation IvarLoc,
3754                                           bool IsArrow, bool IsFreeIvar) {
3755     CXXScopeSpec SS;
3756     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3757     ExprResult Result = getSema().BuildMemberReferenceExpr(
3758         BaseArg, BaseArg->getType(),
3759         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3760         /*FirstQualifierInScope=*/nullptr, NameInfo,
3761         /*TemplateArgs=*/nullptr,
3762         /*S=*/nullptr);
3763     if (IsFreeIvar && Result.isUsable())
3764       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3765     return Result;
3766   }
3767 
3768   /// Build a new Objective-C property 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 RebuildObjCPropertyRefExpr(Expr *BaseArg,
3773                                         ObjCPropertyDecl *Property,
3774                                         SourceLocation PropertyLoc) {
3775     CXXScopeSpec SS;
3776     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3777     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3778                                               /*FIXME:*/PropertyLoc,
3779                                               /*IsArrow=*/false,
3780                                               SS, SourceLocation(),
3781                                               /*FirstQualifierInScope=*/nullptr,
3782                                               NameInfo,
3783                                               /*TemplateArgs=*/nullptr,
3784                                               /*S=*/nullptr);
3785   }
3786 
3787   /// Build a new Objective-C property reference expression.
3788   ///
3789   /// By default, performs semantic analysis to build the new expression.
3790   /// Subclasses may override this routine to provide different behavior.
3791   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3792                                         ObjCMethodDecl *Getter,
3793                                         ObjCMethodDecl *Setter,
3794                                         SourceLocation PropertyLoc) {
3795     // Since these expressions can only be value-dependent, we do not
3796     // need to perform semantic analysis again.
3797     return Owned(
3798       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3799                                                   VK_LValue, OK_ObjCProperty,
3800                                                   PropertyLoc, Base));
3801   }
3802 
3803   /// Build a new Objective-C "isa" expression.
3804   ///
3805   /// By default, performs semantic analysis to build the new expression.
3806   /// Subclasses may override this routine to provide different behavior.
3807   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3808                                 SourceLocation OpLoc, bool IsArrow) {
3809     CXXScopeSpec SS;
3810     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3811     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3812                                               OpLoc, IsArrow,
3813                                               SS, SourceLocation(),
3814                                               /*FirstQualifierInScope=*/nullptr,
3815                                               NameInfo,
3816                                               /*TemplateArgs=*/nullptr,
3817                                               /*S=*/nullptr);
3818   }
3819 
3820   /// Build a new shuffle vector expression.
3821   ///
3822   /// By default, performs semantic analysis to build the new expression.
3823   /// Subclasses may override this routine to provide different behavior.
3824   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3825                                       MultiExprArg SubExprs,
3826                                       SourceLocation RParenLoc) {
3827     // Find the declaration for __builtin_shufflevector
3828     const IdentifierInfo &Name
3829       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3830     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3831     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3832     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3833 
3834     // Build a reference to the __builtin_shufflevector builtin
3835     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3836     Expr *Callee = new (SemaRef.Context)
3837         DeclRefExpr(SemaRef.Context, Builtin, false,
3838                     SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3839     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3840     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3841                                        CK_BuiltinFnToFnPtr).get();
3842 
3843     // Build the CallExpr
3844     ExprResult TheCall = CallExpr::Create(
3845         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3846         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3847         FPOptionsOverride());
3848 
3849     // Type-check the __builtin_shufflevector expression.
3850     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3851   }
3852 
3853   /// Build a new convert vector expression.
3854   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3855                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3856                                       SourceLocation RParenLoc) {
3857     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3858                                          BuiltinLoc, RParenLoc);
3859   }
3860 
3861   /// Build a new template argument pack expansion.
3862   ///
3863   /// By default, performs semantic analysis to build a new pack expansion
3864   /// for a template argument. Subclasses may override this routine to provide
3865   /// different behavior.
3866   TemplateArgumentLoc
3867   RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc,
3868                        std::optional<unsigned> NumExpansions) {
3869     switch (Pattern.getArgument().getKind()) {
3870     case TemplateArgument::Expression: {
3871       ExprResult Result
3872         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3873                                        EllipsisLoc, NumExpansions);
3874       if (Result.isInvalid())
3875         return TemplateArgumentLoc();
3876 
3877       return TemplateArgumentLoc(Result.get(), Result.get());
3878     }
3879 
3880     case TemplateArgument::Template:
3881       return TemplateArgumentLoc(
3882           SemaRef.Context,
3883           TemplateArgument(Pattern.getArgument().getAsTemplate(),
3884                            NumExpansions),
3885           Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3886           EllipsisLoc);
3887 
3888     case TemplateArgument::Null:
3889     case TemplateArgument::Integral:
3890     case TemplateArgument::Declaration:
3891     case TemplateArgument::Pack:
3892     case TemplateArgument::TemplateExpansion:
3893     case TemplateArgument::NullPtr:
3894       llvm_unreachable("Pack expansion pattern has no parameter packs");
3895 
3896     case TemplateArgument::Type:
3897       if (TypeSourceInfo *Expansion
3898             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3899                                            EllipsisLoc,
3900                                            NumExpansions))
3901         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3902                                    Expansion);
3903       break;
3904     }
3905 
3906     return TemplateArgumentLoc();
3907   }
3908 
3909   /// Build a new expression pack expansion.
3910   ///
3911   /// By default, performs semantic analysis to build a new pack expansion
3912   /// for an expression. Subclasses may override this routine to provide
3913   /// different behavior.
3914   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3915                                   std::optional<unsigned> NumExpansions) {
3916     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3917   }
3918 
3919   /// Build a new C++1z fold-expression.
3920   ///
3921   /// By default, performs semantic analysis in order to build a new fold
3922   /// expression.
3923   ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3924                                 SourceLocation LParenLoc, Expr *LHS,
3925                                 BinaryOperatorKind Operator,
3926                                 SourceLocation EllipsisLoc, Expr *RHS,
3927                                 SourceLocation RParenLoc,
3928                                 std::optional<unsigned> NumExpansions) {
3929     return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3930                                       EllipsisLoc, RHS, RParenLoc,
3931                                       NumExpansions);
3932   }
3933 
3934   /// Build an empty C++1z fold-expression with the given operator.
3935   ///
3936   /// By default, produces the fallback value for the fold-expression, or
3937   /// produce an error if there is no fallback value.
3938   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3939                                      BinaryOperatorKind Operator) {
3940     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3941   }
3942 
3943   /// Build a new atomic operation expression.
3944   ///
3945   /// By default, performs semantic analysis to build the new expression.
3946   /// Subclasses may override this routine to provide different behavior.
3947   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3948                                AtomicExpr::AtomicOp Op,
3949                                SourceLocation RParenLoc) {
3950     // Use this for all of the locations, since we don't know the difference
3951     // between the call and the expr at this point.
3952     SourceRange Range{BuiltinLoc, RParenLoc};
3953     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3954                                      Sema::AtomicArgumentOrder::AST);
3955   }
3956 
3957   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3958                                  ArrayRef<Expr *> SubExprs, QualType Type) {
3959     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3960   }
3961 
3962 private:
3963   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3964                                      QualType ObjectType,
3965                                      NamedDecl *FirstQualifierInScope,
3966                                      CXXScopeSpec &SS);
3967 
3968   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3969                                              QualType ObjectType,
3970                                              NamedDecl *FirstQualifierInScope,
3971                                              CXXScopeSpec &SS);
3972 
3973   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3974                                             NamedDecl *FirstQualifierInScope,
3975                                             CXXScopeSpec &SS);
3976 
3977   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3978                                       DependentNameTypeLoc TL,
3979                                       bool DeducibleTSTContext);
3980 };
3981 
3982 template <typename Derived>
3983 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3984   if (!S)
3985     return S;
3986 
3987   switch (S->getStmtClass()) {
3988   case Stmt::NoStmtClass: break;
3989 
3990   // Transform individual statement nodes
3991   // Pass SDK into statements that can produce a value
3992 #define STMT(Node, Parent)                                              \
3993   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3994 #define VALUESTMT(Node, Parent)                                         \
3995   case Stmt::Node##Class:                                               \
3996     return getDerived().Transform##Node(cast<Node>(S), SDK);
3997 #define ABSTRACT_STMT(Node)
3998 #define EXPR(Node, Parent)
3999 #include "clang/AST/StmtNodes.inc"
4000 
4001   // Transform expressions by calling TransformExpr.
4002 #define STMT(Node, Parent)
4003 #define ABSTRACT_STMT(Stmt)
4004 #define EXPR(Node, Parent) case Stmt::Node##Class:
4005 #include "clang/AST/StmtNodes.inc"
4006     {
4007       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
4008 
4009       if (SDK == SDK_StmtExprResult)
4010         E = getSema().ActOnStmtExprResult(E);
4011       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
4012     }
4013   }
4014 
4015   return S;
4016 }
4017 
4018 template<typename Derived>
4019 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
4020   if (!S)
4021     return S;
4022 
4023   switch (S->getClauseKind()) {
4024   default: break;
4025   // Transform individual clause nodes
4026 #define GEN_CLANG_CLAUSE_CLASS
4027 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
4028   case Enum:                                                                   \
4029     return getDerived().Transform##Class(cast<Class>(S));
4030 #include "llvm/Frontend/OpenMP/OMP.inc"
4031   }
4032 
4033   return S;
4034 }
4035 
4036 
4037 template<typename Derived>
4038 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
4039   if (!E)
4040     return E;
4041 
4042   switch (E->getStmtClass()) {
4043     case Stmt::NoStmtClass: break;
4044 #define STMT(Node, Parent) case Stmt::Node##Class: break;
4045 #define ABSTRACT_STMT(Stmt)
4046 #define EXPR(Node, Parent)                                              \
4047     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
4048 #include "clang/AST/StmtNodes.inc"
4049   }
4050 
4051   return E;
4052 }
4053 
4054 template<typename Derived>
4055 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
4056                                                         bool NotCopyInit) {
4057   // Initializers are instantiated like expressions, except that various outer
4058   // layers are stripped.
4059   if (!Init)
4060     return Init;
4061 
4062   if (auto *FE = dyn_cast<FullExpr>(Init))
4063     Init = FE->getSubExpr();
4064 
4065   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
4066     OpaqueValueExpr *OVE = AIL->getCommonExpr();
4067     Init = OVE->getSourceExpr();
4068   }
4069 
4070   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
4071     Init = MTE->getSubExpr();
4072 
4073   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
4074     Init = Binder->getSubExpr();
4075 
4076   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
4077     Init = ICE->getSubExprAsWritten();
4078 
4079   if (CXXStdInitializerListExpr *ILE =
4080           dyn_cast<CXXStdInitializerListExpr>(Init))
4081     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
4082 
4083   // If this is copy-initialization, we only need to reconstruct
4084   // InitListExprs. Other forms of copy-initialization will be a no-op if
4085   // the initializer is already the right type.
4086   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
4087   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
4088     return getDerived().TransformExpr(Init);
4089 
4090   // Revert value-initialization back to empty parens.
4091   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
4092     SourceRange Parens = VIE->getSourceRange();
4093     return getDerived().RebuildParenListExpr(Parens.getBegin(), std::nullopt,
4094                                              Parens.getEnd());
4095   }
4096 
4097   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
4098   if (isa<ImplicitValueInitExpr>(Init))
4099     return getDerived().RebuildParenListExpr(SourceLocation(), std::nullopt,
4100                                              SourceLocation());
4101 
4102   // Revert initialization by constructor back to a parenthesized or braced list
4103   // of expressions. Any other form of initializer can just be reused directly.
4104   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
4105     return getDerived().TransformExpr(Init);
4106 
4107   // If the initialization implicitly converted an initializer list to a
4108   // std::initializer_list object, unwrap the std::initializer_list too.
4109   if (Construct && Construct->isStdInitListInitialization())
4110     return TransformInitializer(Construct->getArg(0), NotCopyInit);
4111 
4112   // Enter a list-init context if this was list initialization.
4113   EnterExpressionEvaluationContext Context(
4114       getSema(), EnterExpressionEvaluationContext::InitList,
4115       Construct->isListInitialization());
4116 
4117   SmallVector<Expr*, 8> NewArgs;
4118   bool ArgChanged = false;
4119   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
4120                                   /*IsCall*/true, NewArgs, &ArgChanged))
4121     return ExprError();
4122 
4123   // If this was list initialization, revert to syntactic list form.
4124   if (Construct->isListInitialization())
4125     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
4126                                         Construct->getEndLoc());
4127 
4128   // Build a ParenListExpr to represent anything else.
4129   SourceRange Parens = Construct->getParenOrBraceRange();
4130   if (Parens.isInvalid()) {
4131     // This was a variable declaration's initialization for which no initializer
4132     // was specified.
4133     assert(NewArgs.empty() &&
4134            "no parens or braces but have direct init with arguments?");
4135     return ExprEmpty();
4136   }
4137   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
4138                                            Parens.getEnd());
4139 }
4140 
4141 template<typename Derived>
4142 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
4143                                             unsigned NumInputs,
4144                                             bool IsCall,
4145                                       SmallVectorImpl<Expr *> &Outputs,
4146                                             bool *ArgChanged) {
4147   for (unsigned I = 0; I != NumInputs; ++I) {
4148     // If requested, drop call arguments that need to be dropped.
4149     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
4150       if (ArgChanged)
4151         *ArgChanged = true;
4152 
4153       break;
4154     }
4155 
4156     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
4157       Expr *Pattern = Expansion->getPattern();
4158 
4159       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4160       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4161       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4162 
4163       // Determine whether the set of unexpanded parameter packs can and should
4164       // be expanded.
4165       bool Expand = true;
4166       bool RetainExpansion = false;
4167       std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4168       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4169       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4170                                                Pattern->getSourceRange(),
4171                                                Unexpanded,
4172                                                Expand, RetainExpansion,
4173                                                NumExpansions))
4174         return true;
4175 
4176       if (!Expand) {
4177         // The transform has determined that we should perform a simple
4178         // transformation on the pack expansion, producing another pack
4179         // expansion.
4180         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4181         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4182         if (OutPattern.isInvalid())
4183           return true;
4184 
4185         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4186                                                 Expansion->getEllipsisLoc(),
4187                                                            NumExpansions);
4188         if (Out.isInvalid())
4189           return true;
4190 
4191         if (ArgChanged)
4192           *ArgChanged = true;
4193         Outputs.push_back(Out.get());
4194         continue;
4195       }
4196 
4197       // Record right away that the argument was changed.  This needs
4198       // to happen even if the array expands to nothing.
4199       if (ArgChanged) *ArgChanged = true;
4200 
4201       // The transform has determined that we should perform an elementwise
4202       // expansion of the pattern. Do so.
4203       for (unsigned I = 0; I != *NumExpansions; ++I) {
4204         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4205         ExprResult Out = getDerived().TransformExpr(Pattern);
4206         if (Out.isInvalid())
4207           return true;
4208 
4209         if (Out.get()->containsUnexpandedParameterPack()) {
4210           Out = getDerived().RebuildPackExpansion(
4211               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4212           if (Out.isInvalid())
4213             return true;
4214         }
4215 
4216         Outputs.push_back(Out.get());
4217       }
4218 
4219       // If we're supposed to retain a pack expansion, do so by temporarily
4220       // forgetting the partially-substituted parameter pack.
4221       if (RetainExpansion) {
4222         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4223 
4224         ExprResult Out = getDerived().TransformExpr(Pattern);
4225         if (Out.isInvalid())
4226           return true;
4227 
4228         Out = getDerived().RebuildPackExpansion(
4229             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4230         if (Out.isInvalid())
4231           return true;
4232 
4233         Outputs.push_back(Out.get());
4234       }
4235 
4236       continue;
4237     }
4238 
4239     ExprResult Result =
4240       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4241              : getDerived().TransformExpr(Inputs[I]);
4242     if (Result.isInvalid())
4243       return true;
4244 
4245     if (Result.get() != Inputs[I] && ArgChanged)
4246       *ArgChanged = true;
4247 
4248     Outputs.push_back(Result.get());
4249   }
4250 
4251   return false;
4252 }
4253 
4254 template <typename Derived>
4255 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4256     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4257   if (Var) {
4258     VarDecl *ConditionVar = cast_or_null<VarDecl>(
4259         getDerived().TransformDefinition(Var->getLocation(), Var));
4260 
4261     if (!ConditionVar)
4262       return Sema::ConditionError();
4263 
4264     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4265   }
4266 
4267   if (Expr) {
4268     ExprResult CondExpr = getDerived().TransformExpr(Expr);
4269 
4270     if (CondExpr.isInvalid())
4271       return Sema::ConditionError();
4272 
4273     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4274                                     /*MissingOK=*/true);
4275   }
4276 
4277   return Sema::ConditionResult();
4278 }
4279 
4280 template <typename Derived>
4281 NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4282     NestedNameSpecifierLoc NNS, QualType ObjectType,
4283     NamedDecl *FirstQualifierInScope) {
4284   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4285 
4286   auto insertNNS = [&Qualifiers](NestedNameSpecifierLoc NNS) {
4287     for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4288          Qualifier = Qualifier.getPrefix())
4289       Qualifiers.push_back(Qualifier);
4290   };
4291   insertNNS(NNS);
4292 
4293   CXXScopeSpec SS;
4294   while (!Qualifiers.empty()) {
4295     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4296     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4297 
4298     switch (QNNS->getKind()) {
4299     case NestedNameSpecifier::Identifier: {
4300       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4301                                       Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4302                                       ObjectType);
4303       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4304                                               SS, FirstQualifierInScope, false))
4305         return NestedNameSpecifierLoc();
4306       break;
4307     }
4308 
4309     case NestedNameSpecifier::Namespace: {
4310       NamespaceDecl *NS =
4311           cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4312               Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4313       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4314       break;
4315     }
4316 
4317     case NestedNameSpecifier::NamespaceAlias: {
4318       NamespaceAliasDecl *Alias =
4319           cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4320               Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4321       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4322                 Q.getLocalEndLoc());
4323       break;
4324     }
4325 
4326     case NestedNameSpecifier::Global:
4327       // There is no meaningful transformation that one could perform on the
4328       // global scope.
4329       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4330       break;
4331 
4332     case NestedNameSpecifier::Super: {
4333       CXXRecordDecl *RD =
4334           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4335               SourceLocation(), QNNS->getAsRecordDecl()));
4336       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4337       break;
4338     }
4339 
4340     case NestedNameSpecifier::TypeSpecWithTemplate:
4341     case NestedNameSpecifier::TypeSpec: {
4342       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4343                                               FirstQualifierInScope, SS);
4344 
4345       if (!TL)
4346         return NestedNameSpecifierLoc();
4347 
4348       QualType T = TL.getType();
4349       if (T->isDependentType() || T->isRecordType() ||
4350           (SemaRef.getLangOpts().CPlusPlus11 && T->isEnumeralType())) {
4351         if (T->isEnumeralType())
4352           SemaRef.Diag(TL.getBeginLoc(),
4353                        diag::warn_cxx98_compat_enum_nested_name_spec);
4354 
4355         if (const auto ETL = TL.getAs<ElaboratedTypeLoc>()) {
4356           SS.Adopt(ETL.getQualifierLoc());
4357           TL = ETL.getNamedTypeLoc();
4358         }
4359         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4360                   Q.getLocalEndLoc());
4361         break;
4362       }
4363       // If the nested-name-specifier is an invalid type def, don't emit an
4364       // error because a previous error should have already been emitted.
4365       TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>();
4366       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4367         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4368             << T << SS.getRange();
4369       }
4370       return NestedNameSpecifierLoc();
4371     }
4372     }
4373 
4374     // The qualifier-in-scope and object type only apply to the leftmost entity.
4375     FirstQualifierInScope = nullptr;
4376     ObjectType = QualType();
4377   }
4378 
4379   // Don't rebuild the nested-name-specifier if we don't have to.
4380   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4381       !getDerived().AlwaysRebuild())
4382     return NNS;
4383 
4384   // If we can re-use the source-location data from the original
4385   // nested-name-specifier, do so.
4386   if (SS.location_size() == NNS.getDataLength() &&
4387       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4388     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4389 
4390   // Allocate new nested-name-specifier location information.
4391   return SS.getWithLocInContext(SemaRef.Context);
4392 }
4393 
4394 template<typename Derived>
4395 DeclarationNameInfo
4396 TreeTransform<Derived>
4397 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4398   DeclarationName Name = NameInfo.getName();
4399   if (!Name)
4400     return DeclarationNameInfo();
4401 
4402   switch (Name.getNameKind()) {
4403   case DeclarationName::Identifier:
4404   case DeclarationName::ObjCZeroArgSelector:
4405   case DeclarationName::ObjCOneArgSelector:
4406   case DeclarationName::ObjCMultiArgSelector:
4407   case DeclarationName::CXXOperatorName:
4408   case DeclarationName::CXXLiteralOperatorName:
4409   case DeclarationName::CXXUsingDirective:
4410     return NameInfo;
4411 
4412   case DeclarationName::CXXDeductionGuideName: {
4413     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4414     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4415         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4416     if (!NewTemplate)
4417       return DeclarationNameInfo();
4418 
4419     DeclarationNameInfo NewNameInfo(NameInfo);
4420     NewNameInfo.setName(
4421         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4422     return NewNameInfo;
4423   }
4424 
4425   case DeclarationName::CXXConstructorName:
4426   case DeclarationName::CXXDestructorName:
4427   case DeclarationName::CXXConversionFunctionName: {
4428     TypeSourceInfo *NewTInfo;
4429     CanQualType NewCanTy;
4430     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4431       NewTInfo = getDerived().TransformType(OldTInfo);
4432       if (!NewTInfo)
4433         return DeclarationNameInfo();
4434       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4435     }
4436     else {
4437       NewTInfo = nullptr;
4438       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4439       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4440       if (NewT.isNull())
4441         return DeclarationNameInfo();
4442       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4443     }
4444 
4445     DeclarationName NewName
4446       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4447                                                            NewCanTy);
4448     DeclarationNameInfo NewNameInfo(NameInfo);
4449     NewNameInfo.setName(NewName);
4450     NewNameInfo.setNamedTypeInfo(NewTInfo);
4451     return NewNameInfo;
4452   }
4453   }
4454 
4455   llvm_unreachable("Unknown name kind.");
4456 }
4457 
4458 template<typename Derived>
4459 TemplateName
4460 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4461                                               TemplateName Name,
4462                                               SourceLocation NameLoc,
4463                                               QualType ObjectType,
4464                                               NamedDecl *FirstQualifierInScope,
4465                                               bool AllowInjectedClassName) {
4466   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4467     TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4468     assert(Template && "qualified template name must refer to a template");
4469 
4470     TemplateDecl *TransTemplate
4471       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4472                                                               Template));
4473     if (!TransTemplate)
4474       return TemplateName();
4475 
4476     if (!getDerived().AlwaysRebuild() &&
4477         SS.getScopeRep() == QTN->getQualifier() &&
4478         TransTemplate == Template)
4479       return Name;
4480 
4481     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4482                                             TransTemplate);
4483   }
4484 
4485   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4486     if (SS.getScopeRep()) {
4487       // These apply to the scope specifier, not the template.
4488       ObjectType = QualType();
4489       FirstQualifierInScope = nullptr;
4490     }
4491 
4492     if (!getDerived().AlwaysRebuild() &&
4493         SS.getScopeRep() == DTN->getQualifier() &&
4494         ObjectType.isNull())
4495       return Name;
4496 
4497     // FIXME: Preserve the location of the "template" keyword.
4498     SourceLocation TemplateKWLoc = NameLoc;
4499 
4500     if (DTN->isIdentifier()) {
4501       return getDerived().RebuildTemplateName(SS,
4502                                               TemplateKWLoc,
4503                                               *DTN->getIdentifier(),
4504                                               NameLoc,
4505                                               ObjectType,
4506                                               FirstQualifierInScope,
4507                                               AllowInjectedClassName);
4508     }
4509 
4510     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4511                                             DTN->getOperator(), NameLoc,
4512                                             ObjectType, AllowInjectedClassName);
4513   }
4514 
4515   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4516     TemplateDecl *TransTemplate
4517       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4518                                                               Template));
4519     if (!TransTemplate)
4520       return TemplateName();
4521 
4522     if (!getDerived().AlwaysRebuild() &&
4523         TransTemplate == Template)
4524       return Name;
4525 
4526     return TemplateName(TransTemplate);
4527   }
4528 
4529   if (SubstTemplateTemplateParmPackStorage *SubstPack
4530       = Name.getAsSubstTemplateTemplateParmPack()) {
4531     return getDerived().RebuildTemplateName(
4532         SubstPack->getArgumentPack(), SubstPack->getAssociatedDecl(),
4533         SubstPack->getIndex(), SubstPack->getFinal());
4534   }
4535 
4536   // These should be getting filtered out before they reach the AST.
4537   llvm_unreachable("overloaded function decl survived to here");
4538 }
4539 
4540 template<typename Derived>
4541 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4542                                          const TemplateArgument &Arg,
4543                                          TemplateArgumentLoc &Output) {
4544   Output = getSema().getTrivialTemplateArgumentLoc(
4545       Arg, QualType(), getDerived().getBaseLocation());
4546 }
4547 
4548 template <typename Derived>
4549 bool TreeTransform<Derived>::TransformTemplateArgument(
4550     const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4551     bool Uneval) {
4552   const TemplateArgument &Arg = Input.getArgument();
4553   switch (Arg.getKind()) {
4554   case TemplateArgument::Null:
4555   case TemplateArgument::Pack:
4556     llvm_unreachable("Unexpected TemplateArgument");
4557 
4558   case TemplateArgument::Integral:
4559   case TemplateArgument::NullPtr:
4560   case TemplateArgument::Declaration: {
4561     // Transform a resolved template argument straight to a resolved template
4562     // argument. We get here when substituting into an already-substituted
4563     // template type argument during concept satisfaction checking.
4564     QualType T = Arg.getNonTypeTemplateArgumentType();
4565     QualType NewT = getDerived().TransformType(T);
4566     if (NewT.isNull())
4567       return true;
4568 
4569     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4570                        ? Arg.getAsDecl()
4571                        : nullptr;
4572     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4573                               getDerived().getBaseLocation(), D))
4574                         : nullptr;
4575     if (D && !NewD)
4576       return true;
4577 
4578     if (NewT == T && D == NewD)
4579       Output = Input;
4580     else if (Arg.getKind() == TemplateArgument::Integral)
4581       Output = TemplateArgumentLoc(
4582           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4583           TemplateArgumentLocInfo());
4584     else if (Arg.getKind() == TemplateArgument::NullPtr)
4585       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4586                                    TemplateArgumentLocInfo());
4587     else
4588       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4589                                    TemplateArgumentLocInfo());
4590 
4591     return false;
4592   }
4593 
4594   case TemplateArgument::Type: {
4595     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4596     if (!DI)
4597       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4598 
4599     DI = getDerived().TransformType(DI);
4600     if (!DI)
4601       return true;
4602 
4603     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4604     return false;
4605   }
4606 
4607   case TemplateArgument::Template: {
4608     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4609     if (QualifierLoc) {
4610       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4611       if (!QualifierLoc)
4612         return true;
4613     }
4614 
4615     CXXScopeSpec SS;
4616     SS.Adopt(QualifierLoc);
4617     TemplateName Template = getDerived().TransformTemplateName(
4618         SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4619     if (Template.isNull())
4620       return true;
4621 
4622     Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4623                                  QualifierLoc, Input.getTemplateNameLoc());
4624     return false;
4625   }
4626 
4627   case TemplateArgument::TemplateExpansion:
4628     llvm_unreachable("Caller should expand pack expansions");
4629 
4630   case TemplateArgument::Expression: {
4631     // Template argument expressions are constant expressions.
4632     EnterExpressionEvaluationContext Unevaluated(
4633         getSema(),
4634         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4635                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4636         Sema::ReuseLambdaContextDecl, /*ExprContext=*/
4637         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4638 
4639     Expr *InputExpr = Input.getSourceExpression();
4640     if (!InputExpr)
4641       InputExpr = Input.getArgument().getAsExpr();
4642 
4643     ExprResult E = getDerived().TransformExpr(InputExpr);
4644     E = SemaRef.ActOnConstantExpression(E);
4645     if (E.isInvalid())
4646       return true;
4647     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4648     return false;
4649   }
4650   }
4651 
4652   // Work around bogus GCC warning
4653   return true;
4654 }
4655 
4656 /// Iterator adaptor that invents template argument location information
4657 /// for each of the template arguments in its underlying iterator.
4658 template<typename Derived, typename InputIterator>
4659 class TemplateArgumentLocInventIterator {
4660   TreeTransform<Derived> &Self;
4661   InputIterator Iter;
4662 
4663 public:
4664   typedef TemplateArgumentLoc value_type;
4665   typedef TemplateArgumentLoc reference;
4666   typedef typename std::iterator_traits<InputIterator>::difference_type
4667     difference_type;
4668   typedef std::input_iterator_tag iterator_category;
4669 
4670   class pointer {
4671     TemplateArgumentLoc Arg;
4672 
4673   public:
4674     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4675 
4676     const TemplateArgumentLoc *operator->() const { return &Arg; }
4677   };
4678 
4679   TemplateArgumentLocInventIterator() { }
4680 
4681   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4682                                              InputIterator Iter)
4683     : Self(Self), Iter(Iter) { }
4684 
4685   TemplateArgumentLocInventIterator &operator++() {
4686     ++Iter;
4687     return *this;
4688   }
4689 
4690   TemplateArgumentLocInventIterator operator++(int) {
4691     TemplateArgumentLocInventIterator Old(*this);
4692     ++(*this);
4693     return Old;
4694   }
4695 
4696   reference operator*() const {
4697     TemplateArgumentLoc Result;
4698     Self.InventTemplateArgumentLoc(*Iter, Result);
4699     return Result;
4700   }
4701 
4702   pointer operator->() const { return pointer(**this); }
4703 
4704   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4705                          const TemplateArgumentLocInventIterator &Y) {
4706     return X.Iter == Y.Iter;
4707   }
4708 
4709   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4710                          const TemplateArgumentLocInventIterator &Y) {
4711     return X.Iter != Y.Iter;
4712   }
4713 };
4714 
4715 template<typename Derived>
4716 template<typename InputIterator>
4717 bool TreeTransform<Derived>::TransformTemplateArguments(
4718     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4719     bool Uneval) {
4720   for (; First != Last; ++First) {
4721     TemplateArgumentLoc Out;
4722     TemplateArgumentLoc In = *First;
4723 
4724     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4725       // Unpack argument packs, which we translate them into separate
4726       // arguments.
4727       // FIXME: We could do much better if we could guarantee that the
4728       // TemplateArgumentLocInfo for the pack expansion would be usable for
4729       // all of the template arguments in the argument pack.
4730       typedef TemplateArgumentLocInventIterator<Derived,
4731                                                 TemplateArgument::pack_iterator>
4732         PackLocIterator;
4733       if (TransformTemplateArguments(PackLocIterator(*this,
4734                                                  In.getArgument().pack_begin()),
4735                                      PackLocIterator(*this,
4736                                                    In.getArgument().pack_end()),
4737                                      Outputs, Uneval))
4738         return true;
4739 
4740       continue;
4741     }
4742 
4743     if (In.getArgument().isPackExpansion()) {
4744       // We have a pack expansion, for which we will be substituting into
4745       // the pattern.
4746       SourceLocation Ellipsis;
4747       std::optional<unsigned> OrigNumExpansions;
4748       TemplateArgumentLoc Pattern
4749         = getSema().getTemplateArgumentPackExpansionPattern(
4750               In, Ellipsis, OrigNumExpansions);
4751 
4752       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4753       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4754       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4755 
4756       // Determine whether the set of unexpanded parameter packs can and should
4757       // be expanded.
4758       bool Expand = true;
4759       bool RetainExpansion = false;
4760       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4761       if (getDerived().TryExpandParameterPacks(Ellipsis,
4762                                                Pattern.getSourceRange(),
4763                                                Unexpanded,
4764                                                Expand,
4765                                                RetainExpansion,
4766                                                NumExpansions))
4767         return true;
4768 
4769       if (!Expand) {
4770         // The transform has determined that we should perform a simple
4771         // transformation on the pack expansion, producing another pack
4772         // expansion.
4773         TemplateArgumentLoc OutPattern;
4774         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4775         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4776           return true;
4777 
4778         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4779                                                 NumExpansions);
4780         if (Out.getArgument().isNull())
4781           return true;
4782 
4783         Outputs.addArgument(Out);
4784         continue;
4785       }
4786 
4787       // The transform has determined that we should perform an elementwise
4788       // expansion of the pattern. Do so.
4789       for (unsigned I = 0; I != *NumExpansions; ++I) {
4790         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4791 
4792         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4793           return true;
4794 
4795         if (Out.getArgument().containsUnexpandedParameterPack()) {
4796           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4797                                                   OrigNumExpansions);
4798           if (Out.getArgument().isNull())
4799             return true;
4800         }
4801 
4802         Outputs.addArgument(Out);
4803       }
4804 
4805       // If we're supposed to retain a pack expansion, do so by temporarily
4806       // forgetting the partially-substituted parameter pack.
4807       if (RetainExpansion) {
4808         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4809 
4810         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4811           return true;
4812 
4813         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4814                                                 OrigNumExpansions);
4815         if (Out.getArgument().isNull())
4816           return true;
4817 
4818         Outputs.addArgument(Out);
4819       }
4820 
4821       continue;
4822     }
4823 
4824     // The simple case:
4825     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4826       return true;
4827 
4828     Outputs.addArgument(Out);
4829   }
4830 
4831   return false;
4832 
4833 }
4834 
4835 //===----------------------------------------------------------------------===//
4836 // Type transformation
4837 //===----------------------------------------------------------------------===//
4838 
4839 template<typename Derived>
4840 QualType TreeTransform<Derived>::TransformType(QualType T) {
4841   if (getDerived().AlreadyTransformed(T))
4842     return T;
4843 
4844   // Temporary workaround.  All of these transformations should
4845   // eventually turn into transformations on TypeLocs.
4846   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4847                                                 getDerived().getBaseLocation());
4848 
4849   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4850 
4851   if (!NewDI)
4852     return QualType();
4853 
4854   return NewDI->getType();
4855 }
4856 
4857 template<typename Derived>
4858 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4859   // Refine the base location to the type's location.
4860   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4861                        getDerived().getBaseEntity());
4862   if (getDerived().AlreadyTransformed(DI->getType()))
4863     return DI;
4864 
4865   TypeLocBuilder TLB;
4866 
4867   TypeLoc TL = DI->getTypeLoc();
4868   TLB.reserve(TL.getFullDataSize());
4869 
4870   QualType Result = getDerived().TransformType(TLB, TL);
4871   if (Result.isNull())
4872     return nullptr;
4873 
4874   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4875 }
4876 
4877 template<typename Derived>
4878 QualType
4879 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4880   switch (T.getTypeLocClass()) {
4881 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4882 #define TYPELOC(CLASS, PARENT)                                                 \
4883   case TypeLoc::CLASS:                                                         \
4884     return getDerived().Transform##CLASS##Type(TLB,                            \
4885                                                T.castAs<CLASS##TypeLoc>());
4886 #include "clang/AST/TypeLocNodes.def"
4887   }
4888 
4889   llvm_unreachable("unhandled type loc!");
4890 }
4891 
4892 template<typename Derived>
4893 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4894   if (!isa<DependentNameType>(T))
4895     return TransformType(T);
4896 
4897   if (getDerived().AlreadyTransformed(T))
4898     return T;
4899   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4900                                                 getDerived().getBaseLocation());
4901   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4902   return NewDI ? NewDI->getType() : QualType();
4903 }
4904 
4905 template<typename Derived>
4906 TypeSourceInfo *
4907 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4908   if (!isa<DependentNameType>(DI->getType()))
4909     return TransformType(DI);
4910 
4911   // Refine the base location to the type's location.
4912   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4913                        getDerived().getBaseEntity());
4914   if (getDerived().AlreadyTransformed(DI->getType()))
4915     return DI;
4916 
4917   TypeLocBuilder TLB;
4918 
4919   TypeLoc TL = DI->getTypeLoc();
4920   TLB.reserve(TL.getFullDataSize());
4921 
4922   auto QTL = TL.getAs<QualifiedTypeLoc>();
4923   if (QTL)
4924     TL = QTL.getUnqualifiedLoc();
4925 
4926   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4927 
4928   QualType Result = getDerived().TransformDependentNameType(
4929       TLB, DNTL, /*DeducedTSTContext*/true);
4930   if (Result.isNull())
4931     return nullptr;
4932 
4933   if (QTL) {
4934     Result = getDerived().RebuildQualifiedType(Result, QTL);
4935     if (Result.isNull())
4936       return nullptr;
4937     TLB.TypeWasModifiedSafely(Result);
4938   }
4939 
4940   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4941 }
4942 
4943 template<typename Derived>
4944 QualType
4945 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4946                                                QualifiedTypeLoc T) {
4947   QualType Result;
4948   TypeLoc UnqualTL = T.getUnqualifiedLoc();
4949   auto SuppressObjCLifetime =
4950       T.getType().getLocalQualifiers().hasObjCLifetime();
4951   if (auto TTP = UnqualTL.getAs<TemplateTypeParmTypeLoc>()) {
4952     Result = getDerived().TransformTemplateTypeParmType(TLB, TTP,
4953                                                         SuppressObjCLifetime);
4954   } else if (auto STTP = UnqualTL.getAs<SubstTemplateTypeParmPackTypeLoc>()) {
4955     Result = getDerived().TransformSubstTemplateTypeParmPackType(
4956         TLB, STTP, SuppressObjCLifetime);
4957   } else {
4958     Result = getDerived().TransformType(TLB, UnqualTL);
4959   }
4960 
4961   if (Result.isNull())
4962     return QualType();
4963 
4964   Result = getDerived().RebuildQualifiedType(Result, T);
4965 
4966   if (Result.isNull())
4967     return QualType();
4968 
4969   // RebuildQualifiedType might have updated the type, but not in a way
4970   // that invalidates the TypeLoc. (There's no location information for
4971   // qualifiers.)
4972   TLB.TypeWasModifiedSafely(Result);
4973 
4974   return Result;
4975 }
4976 
4977 template <typename Derived>
4978 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4979                                                       QualifiedTypeLoc TL) {
4980 
4981   SourceLocation Loc = TL.getBeginLoc();
4982   Qualifiers Quals = TL.getType().getLocalQualifiers();
4983 
4984   if ((T.getAddressSpace() != LangAS::Default &&
4985        Quals.getAddressSpace() != LangAS::Default) &&
4986       T.getAddressSpace() != Quals.getAddressSpace()) {
4987     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4988         << TL.getType() << T;
4989     return QualType();
4990   }
4991 
4992   // C++ [dcl.fct]p7:
4993   //   [When] adding cv-qualifications on top of the function type [...] the
4994   //   cv-qualifiers are ignored.
4995   if (T->isFunctionType()) {
4996     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4997                                                      Quals.getAddressSpace());
4998     return T;
4999   }
5000 
5001   // C++ [dcl.ref]p1:
5002   //   when the cv-qualifiers are introduced through the use of a typedef-name
5003   //   or decltype-specifier [...] the cv-qualifiers are ignored.
5004   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
5005   // applied to a reference type.
5006   if (T->isReferenceType()) {
5007     // The only qualifier that applies to a reference type is restrict.
5008     if (!Quals.hasRestrict())
5009       return T;
5010     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
5011   }
5012 
5013   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
5014   // resulting type.
5015   if (Quals.hasObjCLifetime()) {
5016     if (!T->isObjCLifetimeType() && !T->isDependentType())
5017       Quals.removeObjCLifetime();
5018     else if (T.getObjCLifetime()) {
5019       // Objective-C ARC:
5020       //   A lifetime qualifier applied to a substituted template parameter
5021       //   overrides the lifetime qualifier from the template argument.
5022       const AutoType *AutoTy;
5023       if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
5024         // 'auto' types behave the same way as template parameters.
5025         QualType Deduced = AutoTy->getDeducedType();
5026         Qualifiers Qs = Deduced.getQualifiers();
5027         Qs.removeObjCLifetime();
5028         Deduced =
5029             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
5030         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
5031                                         AutoTy->isDependentType(),
5032                                         /*isPack=*/false,
5033                                         AutoTy->getTypeConstraintConcept(),
5034                                         AutoTy->getTypeConstraintArguments());
5035       } else {
5036         // Otherwise, complain about the addition of a qualifier to an
5037         // already-qualified type.
5038         // FIXME: Why is this check not in Sema::BuildQualifiedType?
5039         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
5040         Quals.removeObjCLifetime();
5041       }
5042     }
5043   }
5044 
5045   return SemaRef.BuildQualifiedType(T, Loc, Quals);
5046 }
5047 
5048 template<typename Derived>
5049 TypeLoc
5050 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
5051                                                    QualType ObjectType,
5052                                                    NamedDecl *UnqualLookup,
5053                                                    CXXScopeSpec &SS) {
5054   if (getDerived().AlreadyTransformed(TL.getType()))
5055     return TL;
5056 
5057   TypeSourceInfo *TSI =
5058       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
5059   if (TSI)
5060     return TSI->getTypeLoc();
5061   return TypeLoc();
5062 }
5063 
5064 template<typename Derived>
5065 TypeSourceInfo *
5066 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
5067                                                    QualType ObjectType,
5068                                                    NamedDecl *UnqualLookup,
5069                                                    CXXScopeSpec &SS) {
5070   if (getDerived().AlreadyTransformed(TSInfo->getType()))
5071     return TSInfo;
5072 
5073   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
5074                                    UnqualLookup, SS);
5075 }
5076 
5077 template <typename Derived>
5078 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
5079     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
5080     CXXScopeSpec &SS) {
5081   QualType T = TL.getType();
5082   assert(!getDerived().AlreadyTransformed(T));
5083 
5084   TypeLocBuilder TLB;
5085   QualType Result;
5086 
5087   if (isa<TemplateSpecializationType>(T)) {
5088     TemplateSpecializationTypeLoc SpecTL =
5089         TL.castAs<TemplateSpecializationTypeLoc>();
5090 
5091     TemplateName Template = getDerived().TransformTemplateName(
5092         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
5093         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
5094     if (Template.isNull())
5095       return nullptr;
5096 
5097     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
5098                                                               Template);
5099   } else if (isa<DependentTemplateSpecializationType>(T)) {
5100     DependentTemplateSpecializationTypeLoc SpecTL =
5101         TL.castAs<DependentTemplateSpecializationTypeLoc>();
5102 
5103     TemplateName Template
5104       = getDerived().RebuildTemplateName(SS,
5105                                          SpecTL.getTemplateKeywordLoc(),
5106                                          *SpecTL.getTypePtr()->getIdentifier(),
5107                                          SpecTL.getTemplateNameLoc(),
5108                                          ObjectType, UnqualLookup,
5109                                          /*AllowInjectedClassName*/true);
5110     if (Template.isNull())
5111       return nullptr;
5112 
5113     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
5114                                                                        SpecTL,
5115                                                                        Template,
5116                                                                        SS);
5117   } else {
5118     // Nothing special needs to be done for these.
5119     Result = getDerived().TransformType(TLB, TL);
5120   }
5121 
5122   if (Result.isNull())
5123     return nullptr;
5124 
5125   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
5126 }
5127 
5128 template <class TyLoc> static inline
5129 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
5130   TyLoc NewT = TLB.push<TyLoc>(T.getType());
5131   NewT.setNameLoc(T.getNameLoc());
5132   return T.getType();
5133 }
5134 
5135 template<typename Derived>
5136 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
5137                                                       BuiltinTypeLoc T) {
5138   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
5139   NewT.setBuiltinLoc(T.getBuiltinLoc());
5140   if (T.needsExtraLocalData())
5141     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
5142   return T.getType();
5143 }
5144 
5145 template<typename Derived>
5146 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
5147                                                       ComplexTypeLoc T) {
5148   // FIXME: recurse?
5149   return TransformTypeSpecType(TLB, T);
5150 }
5151 
5152 template <typename Derived>
5153 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
5154                                                        AdjustedTypeLoc TL) {
5155   // Adjustments applied during transformation are handled elsewhere.
5156   return getDerived().TransformType(TLB, TL.getOriginalLoc());
5157 }
5158 
5159 template<typename Derived>
5160 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5161                                                       DecayedTypeLoc TL) {
5162   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5163   if (OriginalType.isNull())
5164     return QualType();
5165 
5166   QualType Result = TL.getType();
5167   if (getDerived().AlwaysRebuild() ||
5168       OriginalType != TL.getOriginalLoc().getType())
5169     Result = SemaRef.Context.getDecayedType(OriginalType);
5170   TLB.push<DecayedTypeLoc>(Result);
5171   // Nothing to set for DecayedTypeLoc.
5172   return Result;
5173 }
5174 
5175 template<typename Derived>
5176 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5177                                                       PointerTypeLoc TL) {
5178   QualType PointeeType
5179     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5180   if (PointeeType.isNull())
5181     return QualType();
5182 
5183   QualType Result = TL.getType();
5184   if (PointeeType->getAs<ObjCObjectType>()) {
5185     // A dependent pointer type 'T *' has is being transformed such
5186     // that an Objective-C class type is being replaced for 'T'. The
5187     // resulting pointer type is an ObjCObjectPointerType, not a
5188     // PointerType.
5189     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5190 
5191     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5192     NewT.setStarLoc(TL.getStarLoc());
5193     return Result;
5194   }
5195 
5196   if (getDerived().AlwaysRebuild() ||
5197       PointeeType != TL.getPointeeLoc().getType()) {
5198     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5199     if (Result.isNull())
5200       return QualType();
5201   }
5202 
5203   // Objective-C ARC can add lifetime qualifiers to the type that we're
5204   // pointing to.
5205   TLB.TypeWasModifiedSafely(Result->getPointeeType());
5206 
5207   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5208   NewT.setSigilLoc(TL.getSigilLoc());
5209   return Result;
5210 }
5211 
5212 template<typename Derived>
5213 QualType
5214 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5215                                                   BlockPointerTypeLoc TL) {
5216   QualType PointeeType
5217     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5218   if (PointeeType.isNull())
5219     return QualType();
5220 
5221   QualType Result = TL.getType();
5222   if (getDerived().AlwaysRebuild() ||
5223       PointeeType != TL.getPointeeLoc().getType()) {
5224     Result = getDerived().RebuildBlockPointerType(PointeeType,
5225                                                   TL.getSigilLoc());
5226     if (Result.isNull())
5227       return QualType();
5228   }
5229 
5230   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5231   NewT.setSigilLoc(TL.getSigilLoc());
5232   return Result;
5233 }
5234 
5235 /// Transforms a reference type.  Note that somewhat paradoxically we
5236 /// don't care whether the type itself is an l-value type or an r-value
5237 /// type;  we only care if the type was *written* as an l-value type
5238 /// or an r-value type.
5239 template<typename Derived>
5240 QualType
5241 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5242                                                ReferenceTypeLoc TL) {
5243   const ReferenceType *T = TL.getTypePtr();
5244 
5245   // Note that this works with the pointee-as-written.
5246   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5247   if (PointeeType.isNull())
5248     return QualType();
5249 
5250   QualType Result = TL.getType();
5251   if (getDerived().AlwaysRebuild() ||
5252       PointeeType != T->getPointeeTypeAsWritten()) {
5253     Result = getDerived().RebuildReferenceType(PointeeType,
5254                                                T->isSpelledAsLValue(),
5255                                                TL.getSigilLoc());
5256     if (Result.isNull())
5257       return QualType();
5258   }
5259 
5260   // Objective-C ARC can add lifetime qualifiers to the type that we're
5261   // referring to.
5262   TLB.TypeWasModifiedSafely(
5263       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5264 
5265   // r-value references can be rebuilt as l-value references.
5266   ReferenceTypeLoc NewTL;
5267   if (isa<LValueReferenceType>(Result))
5268     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5269   else
5270     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5271   NewTL.setSigilLoc(TL.getSigilLoc());
5272 
5273   return Result;
5274 }
5275 
5276 template<typename Derived>
5277 QualType
5278 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5279                                                  LValueReferenceTypeLoc TL) {
5280   return TransformReferenceType(TLB, TL);
5281 }
5282 
5283 template<typename Derived>
5284 QualType
5285 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5286                                                  RValueReferenceTypeLoc TL) {
5287   return TransformReferenceType(TLB, TL);
5288 }
5289 
5290 template<typename Derived>
5291 QualType
5292 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5293                                                    MemberPointerTypeLoc TL) {
5294   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5295   if (PointeeType.isNull())
5296     return QualType();
5297 
5298   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5299   TypeSourceInfo *NewClsTInfo = nullptr;
5300   if (OldClsTInfo) {
5301     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5302     if (!NewClsTInfo)
5303       return QualType();
5304   }
5305 
5306   const MemberPointerType *T = TL.getTypePtr();
5307   QualType OldClsType = QualType(T->getClass(), 0);
5308   QualType NewClsType;
5309   if (NewClsTInfo)
5310     NewClsType = NewClsTInfo->getType();
5311   else {
5312     NewClsType = getDerived().TransformType(OldClsType);
5313     if (NewClsType.isNull())
5314       return QualType();
5315   }
5316 
5317   QualType Result = TL.getType();
5318   if (getDerived().AlwaysRebuild() ||
5319       PointeeType != T->getPointeeType() ||
5320       NewClsType != OldClsType) {
5321     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5322                                                    TL.getStarLoc());
5323     if (Result.isNull())
5324       return QualType();
5325   }
5326 
5327   // If we had to adjust the pointee type when building a member pointer, make
5328   // sure to push TypeLoc info for it.
5329   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5330   if (MPT && PointeeType != MPT->getPointeeType()) {
5331     assert(isa<AdjustedType>(MPT->getPointeeType()));
5332     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5333   }
5334 
5335   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5336   NewTL.setSigilLoc(TL.getSigilLoc());
5337   NewTL.setClassTInfo(NewClsTInfo);
5338 
5339   return Result;
5340 }
5341 
5342 template<typename Derived>
5343 QualType
5344 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5345                                                    ConstantArrayTypeLoc TL) {
5346   const ConstantArrayType *T = TL.getTypePtr();
5347   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5348   if (ElementType.isNull())
5349     return QualType();
5350 
5351   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5352   Expr *OldSize = TL.getSizeExpr();
5353   if (!OldSize)
5354     OldSize = const_cast<Expr*>(T->getSizeExpr());
5355   Expr *NewSize = nullptr;
5356   if (OldSize) {
5357     EnterExpressionEvaluationContext Unevaluated(
5358         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5359     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5360     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5361   }
5362 
5363   QualType Result = TL.getType();
5364   if (getDerived().AlwaysRebuild() ||
5365       ElementType != T->getElementType() ||
5366       (T->getSizeExpr() && NewSize != OldSize)) {
5367     Result = getDerived().RebuildConstantArrayType(ElementType,
5368                                                    T->getSizeModifier(),
5369                                                    T->getSize(), NewSize,
5370                                              T->getIndexTypeCVRQualifiers(),
5371                                                    TL.getBracketsRange());
5372     if (Result.isNull())
5373       return QualType();
5374   }
5375 
5376   // We might have either a ConstantArrayType or a VariableArrayType now:
5377   // a ConstantArrayType is allowed to have an element type which is a
5378   // VariableArrayType if the type is dependent.  Fortunately, all array
5379   // types have the same location layout.
5380   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5381   NewTL.setLBracketLoc(TL.getLBracketLoc());
5382   NewTL.setRBracketLoc(TL.getRBracketLoc());
5383   NewTL.setSizeExpr(NewSize);
5384 
5385   return Result;
5386 }
5387 
5388 template<typename Derived>
5389 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5390                                               TypeLocBuilder &TLB,
5391                                               IncompleteArrayTypeLoc TL) {
5392   const IncompleteArrayType *T = TL.getTypePtr();
5393   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5394   if (ElementType.isNull())
5395     return QualType();
5396 
5397   QualType Result = TL.getType();
5398   if (getDerived().AlwaysRebuild() ||
5399       ElementType != T->getElementType()) {
5400     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5401                                                      T->getSizeModifier(),
5402                                            T->getIndexTypeCVRQualifiers(),
5403                                                      TL.getBracketsRange());
5404     if (Result.isNull())
5405       return QualType();
5406   }
5407 
5408   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5409   NewTL.setLBracketLoc(TL.getLBracketLoc());
5410   NewTL.setRBracketLoc(TL.getRBracketLoc());
5411   NewTL.setSizeExpr(nullptr);
5412 
5413   return Result;
5414 }
5415 
5416 template<typename Derived>
5417 QualType
5418 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5419                                                    VariableArrayTypeLoc TL) {
5420   const VariableArrayType *T = TL.getTypePtr();
5421   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5422   if (ElementType.isNull())
5423     return QualType();
5424 
5425   ExprResult SizeResult;
5426   {
5427     EnterExpressionEvaluationContext Context(
5428         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5429     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5430   }
5431   if (SizeResult.isInvalid())
5432     return QualType();
5433   SizeResult =
5434       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5435   if (SizeResult.isInvalid())
5436     return QualType();
5437 
5438   Expr *Size = SizeResult.get();
5439 
5440   QualType Result = TL.getType();
5441   if (getDerived().AlwaysRebuild() ||
5442       ElementType != T->getElementType() ||
5443       Size != T->getSizeExpr()) {
5444     Result = getDerived().RebuildVariableArrayType(ElementType,
5445                                                    T->getSizeModifier(),
5446                                                    Size,
5447                                              T->getIndexTypeCVRQualifiers(),
5448                                                    TL.getBracketsRange());
5449     if (Result.isNull())
5450       return QualType();
5451   }
5452 
5453   // We might have constant size array now, but fortunately it has the same
5454   // location layout.
5455   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5456   NewTL.setLBracketLoc(TL.getLBracketLoc());
5457   NewTL.setRBracketLoc(TL.getRBracketLoc());
5458   NewTL.setSizeExpr(Size);
5459 
5460   return Result;
5461 }
5462 
5463 template<typename Derived>
5464 QualType
5465 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5466                                              DependentSizedArrayTypeLoc TL) {
5467   const DependentSizedArrayType *T = TL.getTypePtr();
5468   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5469   if (ElementType.isNull())
5470     return QualType();
5471 
5472   // Array bounds are constant expressions.
5473   EnterExpressionEvaluationContext Unevaluated(
5474       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5475 
5476   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5477   Expr *origSize = TL.getSizeExpr();
5478   if (!origSize) origSize = T->getSizeExpr();
5479 
5480   ExprResult sizeResult
5481     = getDerived().TransformExpr(origSize);
5482   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5483   if (sizeResult.isInvalid())
5484     return QualType();
5485 
5486   Expr *size = sizeResult.get();
5487 
5488   QualType Result = TL.getType();
5489   if (getDerived().AlwaysRebuild() ||
5490       ElementType != T->getElementType() ||
5491       size != origSize) {
5492     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5493                                                          T->getSizeModifier(),
5494                                                          size,
5495                                                 T->getIndexTypeCVRQualifiers(),
5496                                                         TL.getBracketsRange());
5497     if (Result.isNull())
5498       return QualType();
5499   }
5500 
5501   // We might have any sort of array type now, but fortunately they
5502   // all have the same location layout.
5503   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5504   NewTL.setLBracketLoc(TL.getLBracketLoc());
5505   NewTL.setRBracketLoc(TL.getRBracketLoc());
5506   NewTL.setSizeExpr(size);
5507 
5508   return Result;
5509 }
5510 
5511 template <typename Derived>
5512 QualType TreeTransform<Derived>::TransformDependentVectorType(
5513     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5514   const DependentVectorType *T = TL.getTypePtr();
5515   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5516   if (ElementType.isNull())
5517     return QualType();
5518 
5519   EnterExpressionEvaluationContext Unevaluated(
5520       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5521 
5522   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5523   Size = SemaRef.ActOnConstantExpression(Size);
5524   if (Size.isInvalid())
5525     return QualType();
5526 
5527   QualType Result = TL.getType();
5528   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5529       Size.get() != T->getSizeExpr()) {
5530     Result = getDerived().RebuildDependentVectorType(
5531         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5532     if (Result.isNull())
5533       return QualType();
5534   }
5535 
5536   // Result might be dependent or not.
5537   if (isa<DependentVectorType>(Result)) {
5538     DependentVectorTypeLoc NewTL =
5539         TLB.push<DependentVectorTypeLoc>(Result);
5540     NewTL.setNameLoc(TL.getNameLoc());
5541   } else {
5542     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5543     NewTL.setNameLoc(TL.getNameLoc());
5544   }
5545 
5546   return Result;
5547 }
5548 
5549 template<typename Derived>
5550 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5551                                       TypeLocBuilder &TLB,
5552                                       DependentSizedExtVectorTypeLoc TL) {
5553   const DependentSizedExtVectorType *T = TL.getTypePtr();
5554 
5555   // FIXME: ext vector locs should be nested
5556   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5557   if (ElementType.isNull())
5558     return QualType();
5559 
5560   // Vector sizes are constant expressions.
5561   EnterExpressionEvaluationContext Unevaluated(
5562       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5563 
5564   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5565   Size = SemaRef.ActOnConstantExpression(Size);
5566   if (Size.isInvalid())
5567     return QualType();
5568 
5569   QualType Result = TL.getType();
5570   if (getDerived().AlwaysRebuild() ||
5571       ElementType != T->getElementType() ||
5572       Size.get() != T->getSizeExpr()) {
5573     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5574                                                              Size.get(),
5575                                                          T->getAttributeLoc());
5576     if (Result.isNull())
5577       return QualType();
5578   }
5579 
5580   // Result might be dependent or not.
5581   if (isa<DependentSizedExtVectorType>(Result)) {
5582     DependentSizedExtVectorTypeLoc NewTL
5583       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5584     NewTL.setNameLoc(TL.getNameLoc());
5585   } else {
5586     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5587     NewTL.setNameLoc(TL.getNameLoc());
5588   }
5589 
5590   return Result;
5591 }
5592 
5593 template <typename Derived>
5594 QualType
5595 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5596                                                     ConstantMatrixTypeLoc TL) {
5597   const ConstantMatrixType *T = TL.getTypePtr();
5598   QualType ElementType = getDerived().TransformType(T->getElementType());
5599   if (ElementType.isNull())
5600     return QualType();
5601 
5602   QualType Result = TL.getType();
5603   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5604     Result = getDerived().RebuildConstantMatrixType(
5605         ElementType, T->getNumRows(), T->getNumColumns());
5606     if (Result.isNull())
5607       return QualType();
5608   }
5609 
5610   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5611   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5612   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5613   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5614   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5615 
5616   return Result;
5617 }
5618 
5619 template <typename Derived>
5620 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5621     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5622   const DependentSizedMatrixType *T = TL.getTypePtr();
5623 
5624   QualType ElementType = getDerived().TransformType(T->getElementType());
5625   if (ElementType.isNull()) {
5626     return QualType();
5627   }
5628 
5629   // Matrix dimensions are constant expressions.
5630   EnterExpressionEvaluationContext Unevaluated(
5631       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5632 
5633   Expr *origRows = TL.getAttrRowOperand();
5634   if (!origRows)
5635     origRows = T->getRowExpr();
5636   Expr *origColumns = TL.getAttrColumnOperand();
5637   if (!origColumns)
5638     origColumns = T->getColumnExpr();
5639 
5640   ExprResult rowResult = getDerived().TransformExpr(origRows);
5641   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5642   if (rowResult.isInvalid())
5643     return QualType();
5644 
5645   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5646   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5647   if (columnResult.isInvalid())
5648     return QualType();
5649 
5650   Expr *rows = rowResult.get();
5651   Expr *columns = columnResult.get();
5652 
5653   QualType Result = TL.getType();
5654   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5655       rows != origRows || columns != origColumns) {
5656     Result = getDerived().RebuildDependentSizedMatrixType(
5657         ElementType, rows, columns, T->getAttributeLoc());
5658 
5659     if (Result.isNull())
5660       return QualType();
5661   }
5662 
5663   // We might have any sort of matrix type now, but fortunately they
5664   // all have the same location layout.
5665   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5666   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5667   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5668   NewTL.setAttrRowOperand(rows);
5669   NewTL.setAttrColumnOperand(columns);
5670   return Result;
5671 }
5672 
5673 template <typename Derived>
5674 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5675     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5676   const DependentAddressSpaceType *T = TL.getTypePtr();
5677 
5678   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5679 
5680   if (pointeeType.isNull())
5681     return QualType();
5682 
5683   // Address spaces are constant expressions.
5684   EnterExpressionEvaluationContext Unevaluated(
5685       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5686 
5687   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5688   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5689   if (AddrSpace.isInvalid())
5690     return QualType();
5691 
5692   QualType Result = TL.getType();
5693   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5694       AddrSpace.get() != T->getAddrSpaceExpr()) {
5695     Result = getDerived().RebuildDependentAddressSpaceType(
5696         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5697     if (Result.isNull())
5698       return QualType();
5699   }
5700 
5701   // Result might be dependent or not.
5702   if (isa<DependentAddressSpaceType>(Result)) {
5703     DependentAddressSpaceTypeLoc NewTL =
5704         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5705 
5706     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5707     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5708     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5709 
5710   } else {
5711     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5712         Result, getDerived().getBaseLocation());
5713     TransformType(TLB, DI->getTypeLoc());
5714   }
5715 
5716   return Result;
5717 }
5718 
5719 template <typename Derived>
5720 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5721                                                      VectorTypeLoc TL) {
5722   const VectorType *T = TL.getTypePtr();
5723   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5724   if (ElementType.isNull())
5725     return QualType();
5726 
5727   QualType Result = TL.getType();
5728   if (getDerived().AlwaysRebuild() ||
5729       ElementType != T->getElementType()) {
5730     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5731                                             T->getVectorKind());
5732     if (Result.isNull())
5733       return QualType();
5734   }
5735 
5736   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5737   NewTL.setNameLoc(TL.getNameLoc());
5738 
5739   return Result;
5740 }
5741 
5742 template<typename Derived>
5743 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5744                                                         ExtVectorTypeLoc 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().RebuildExtVectorType(ElementType,
5754                                                T->getNumElements(),
5755                                                /*FIXME*/ SourceLocation());
5756     if (Result.isNull())
5757       return QualType();
5758   }
5759 
5760   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5761   NewTL.setNameLoc(TL.getNameLoc());
5762 
5763   return Result;
5764 }
5765 
5766 template <typename Derived>
5767 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5768     ParmVarDecl *OldParm, int indexAdjustment,
5769     std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
5770   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5771   TypeSourceInfo *NewDI = nullptr;
5772 
5773   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5774     // If we're substituting into a pack expansion type and we know the
5775     // length we want to expand to, just substitute for the pattern.
5776     TypeLoc OldTL = OldDI->getTypeLoc();
5777     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5778 
5779     TypeLocBuilder TLB;
5780     TypeLoc NewTL = OldDI->getTypeLoc();
5781     TLB.reserve(NewTL.getFullDataSize());
5782 
5783     QualType Result = getDerived().TransformType(TLB,
5784                                                OldExpansionTL.getPatternLoc());
5785     if (Result.isNull())
5786       return nullptr;
5787 
5788     Result = RebuildPackExpansionType(Result,
5789                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5790                                       OldExpansionTL.getEllipsisLoc(),
5791                                       NumExpansions);
5792     if (Result.isNull())
5793       return nullptr;
5794 
5795     PackExpansionTypeLoc NewExpansionTL
5796       = TLB.push<PackExpansionTypeLoc>(Result);
5797     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5798     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5799   } else
5800     NewDI = getDerived().TransformType(OldDI);
5801   if (!NewDI)
5802     return nullptr;
5803 
5804   if (NewDI == OldDI && indexAdjustment == 0)
5805     return OldParm;
5806 
5807   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5808                                              OldParm->getDeclContext(),
5809                                              OldParm->getInnerLocStart(),
5810                                              OldParm->getLocation(),
5811                                              OldParm->getIdentifier(),
5812                                              NewDI->getType(),
5813                                              NewDI,
5814                                              OldParm->getStorageClass(),
5815                                              /* DefArg */ nullptr);
5816   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5817                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5818   transformedLocalDecl(OldParm, {newParm});
5819   return newParm;
5820 }
5821 
5822 template <typename Derived>
5823 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5824     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5825     const QualType *ParamTypes,
5826     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5827     SmallVectorImpl<QualType> &OutParamTypes,
5828     SmallVectorImpl<ParmVarDecl *> *PVars,
5829     Sema::ExtParameterInfoBuilder &PInfos,
5830     unsigned *LastParamTransformed) {
5831   int indexAdjustment = 0;
5832 
5833   unsigned NumParams = Params.size();
5834   for (unsigned i = 0; i != NumParams; ++i) {
5835     if (LastParamTransformed)
5836       *LastParamTransformed = i;
5837     if (ParmVarDecl *OldParm = Params[i]) {
5838       assert(OldParm->getFunctionScopeIndex() == i);
5839 
5840       std::optional<unsigned> NumExpansions;
5841       ParmVarDecl *NewParm = nullptr;
5842       if (OldParm->isParameterPack()) {
5843         // We have a function parameter pack that may need to be expanded.
5844         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5845 
5846         // Find the parameter packs that could be expanded.
5847         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5848         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5849         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5850         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5851 
5852         // Determine whether we should expand the parameter packs.
5853         bool ShouldExpand = false;
5854         bool RetainExpansion = false;
5855         std::optional<unsigned> OrigNumExpansions;
5856         if (Unexpanded.size() > 0) {
5857           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5858           NumExpansions = OrigNumExpansions;
5859           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5860                                                    Pattern.getSourceRange(),
5861                                                    Unexpanded,
5862                                                    ShouldExpand,
5863                                                    RetainExpansion,
5864                                                    NumExpansions)) {
5865             return true;
5866           }
5867         } else {
5868 #ifndef NDEBUG
5869           const AutoType *AT =
5870               Pattern.getType().getTypePtr()->getContainedAutoType();
5871           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5872                  "Could not find parameter packs or undeduced auto type!");
5873 #endif
5874         }
5875 
5876         if (ShouldExpand) {
5877           // Expand the function parameter pack into multiple, separate
5878           // parameters.
5879           getDerived().ExpandingFunctionParameterPack(OldParm);
5880           for (unsigned I = 0; I != *NumExpansions; ++I) {
5881             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5882             ParmVarDecl *NewParm
5883               = getDerived().TransformFunctionTypeParam(OldParm,
5884                                                         indexAdjustment++,
5885                                                         OrigNumExpansions,
5886                                                 /*ExpectParameterPack=*/false);
5887             if (!NewParm)
5888               return true;
5889 
5890             if (ParamInfos)
5891               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5892             OutParamTypes.push_back(NewParm->getType());
5893             if (PVars)
5894               PVars->push_back(NewParm);
5895           }
5896 
5897           // If we're supposed to retain a pack expansion, do so by temporarily
5898           // forgetting the partially-substituted parameter pack.
5899           if (RetainExpansion) {
5900             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5901             ParmVarDecl *NewParm
5902               = getDerived().TransformFunctionTypeParam(OldParm,
5903                                                         indexAdjustment++,
5904                                                         OrigNumExpansions,
5905                                                 /*ExpectParameterPack=*/false);
5906             if (!NewParm)
5907               return true;
5908 
5909             if (ParamInfos)
5910               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5911             OutParamTypes.push_back(NewParm->getType());
5912             if (PVars)
5913               PVars->push_back(NewParm);
5914           }
5915 
5916           // The next parameter should have the same adjustment as the
5917           // last thing we pushed, but we post-incremented indexAdjustment
5918           // on every push.  Also, if we push nothing, the adjustment should
5919           // go down by one.
5920           indexAdjustment--;
5921 
5922           // We're done with the pack expansion.
5923           continue;
5924         }
5925 
5926         // We'll substitute the parameter now without expanding the pack
5927         // expansion.
5928         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5929         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5930                                                           indexAdjustment,
5931                                                           NumExpansions,
5932                                                   /*ExpectParameterPack=*/true);
5933         assert(NewParm->isParameterPack() &&
5934                "Parameter pack no longer a parameter pack after "
5935                "transformation.");
5936       } else {
5937         NewParm = getDerived().TransformFunctionTypeParam(
5938             OldParm, indexAdjustment, std::nullopt,
5939             /*ExpectParameterPack=*/false);
5940       }
5941 
5942       if (!NewParm)
5943         return true;
5944 
5945       if (ParamInfos)
5946         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5947       OutParamTypes.push_back(NewParm->getType());
5948       if (PVars)
5949         PVars->push_back(NewParm);
5950       continue;
5951     }
5952 
5953     // Deal with the possibility that we don't have a parameter
5954     // declaration for this parameter.
5955     assert(ParamTypes);
5956     QualType OldType = ParamTypes[i];
5957     bool IsPackExpansion = false;
5958     std::optional<unsigned> NumExpansions;
5959     QualType NewType;
5960     if (const PackExpansionType *Expansion
5961                                        = dyn_cast<PackExpansionType>(OldType)) {
5962       // We have a function parameter pack that may need to be expanded.
5963       QualType Pattern = Expansion->getPattern();
5964       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5965       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5966 
5967       // Determine whether we should expand the parameter packs.
5968       bool ShouldExpand = false;
5969       bool RetainExpansion = false;
5970       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5971                                                Unexpanded,
5972                                                ShouldExpand,
5973                                                RetainExpansion,
5974                                                NumExpansions)) {
5975         return true;
5976       }
5977 
5978       if (ShouldExpand) {
5979         // Expand the function parameter pack into multiple, separate
5980         // parameters.
5981         for (unsigned I = 0; I != *NumExpansions; ++I) {
5982           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5983           QualType NewType = getDerived().TransformType(Pattern);
5984           if (NewType.isNull())
5985             return true;
5986 
5987           if (NewType->containsUnexpandedParameterPack()) {
5988             NewType = getSema().getASTContext().getPackExpansionType(
5989                 NewType, std::nullopt);
5990 
5991             if (NewType.isNull())
5992               return true;
5993           }
5994 
5995           if (ParamInfos)
5996             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5997           OutParamTypes.push_back(NewType);
5998           if (PVars)
5999             PVars->push_back(nullptr);
6000         }
6001 
6002         // We're done with the pack expansion.
6003         continue;
6004       }
6005 
6006       // If we're supposed to retain a pack expansion, do so by temporarily
6007       // forgetting the partially-substituted parameter pack.
6008       if (RetainExpansion) {
6009         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
6010         QualType NewType = getDerived().TransformType(Pattern);
6011         if (NewType.isNull())
6012           return true;
6013 
6014         if (ParamInfos)
6015           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6016         OutParamTypes.push_back(NewType);
6017         if (PVars)
6018           PVars->push_back(nullptr);
6019       }
6020 
6021       // We'll substitute the parameter now without expanding the pack
6022       // expansion.
6023       OldType = Expansion->getPattern();
6024       IsPackExpansion = true;
6025       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6026       NewType = getDerived().TransformType(OldType);
6027     } else {
6028       NewType = getDerived().TransformType(OldType);
6029     }
6030 
6031     if (NewType.isNull())
6032       return true;
6033 
6034     if (IsPackExpansion)
6035       NewType = getSema().Context.getPackExpansionType(NewType,
6036                                                        NumExpansions);
6037 
6038     if (ParamInfos)
6039       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6040     OutParamTypes.push_back(NewType);
6041     if (PVars)
6042       PVars->push_back(nullptr);
6043   }
6044 
6045 #ifndef NDEBUG
6046   if (PVars) {
6047     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
6048       if (ParmVarDecl *parm = (*PVars)[i])
6049         assert(parm->getFunctionScopeIndex() == i);
6050   }
6051 #endif
6052 
6053   return false;
6054 }
6055 
6056 template<typename Derived>
6057 QualType
6058 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
6059                                                    FunctionProtoTypeLoc TL) {
6060   SmallVector<QualType, 4> ExceptionStorage;
6061   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
6062   return getDerived().TransformFunctionProtoType(
6063       TLB, TL, nullptr, Qualifiers(),
6064       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
6065         return This->getDerived().TransformExceptionSpec(
6066             TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
6067       });
6068 }
6069 
6070 template<typename Derived> template<typename Fn>
6071 QualType TreeTransform<Derived>::TransformFunctionProtoType(
6072     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
6073     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
6074 
6075   // Transform the parameters and return type.
6076   //
6077   // We are required to instantiate the params and return type in source order.
6078   // When the function has a trailing return type, we instantiate the
6079   // parameters before the return type,  since the return type can then refer
6080   // to the parameters themselves (via decltype, sizeof, etc.).
6081   //
6082   SmallVector<QualType, 4> ParamTypes;
6083   SmallVector<ParmVarDecl*, 4> ParamDecls;
6084   Sema::ExtParameterInfoBuilder ExtParamInfos;
6085   const FunctionProtoType *T = TL.getTypePtr();
6086 
6087   QualType ResultType;
6088 
6089   if (T->hasTrailingReturn()) {
6090     if (getDerived().TransformFunctionTypeParams(
6091             TL.getBeginLoc(), TL.getParams(),
6092             TL.getTypePtr()->param_type_begin(),
6093             T->getExtParameterInfosOrNull(),
6094             ParamTypes, &ParamDecls, ExtParamInfos))
6095       return QualType();
6096 
6097     {
6098       // C++11 [expr.prim.general]p3:
6099       //   If a declaration declares a member function or member function
6100       //   template of a class X, the expression this is a prvalue of type
6101       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6102       //   and the end of the function-definition, member-declarator, or
6103       //   declarator.
6104       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
6105 
6106       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6107       if (ResultType.isNull())
6108         return QualType();
6109     }
6110   }
6111   else {
6112     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6113     if (ResultType.isNull())
6114       return QualType();
6115 
6116     if (getDerived().TransformFunctionTypeParams(
6117             TL.getBeginLoc(), TL.getParams(),
6118             TL.getTypePtr()->param_type_begin(),
6119             T->getExtParameterInfosOrNull(),
6120             ParamTypes, &ParamDecls, ExtParamInfos))
6121       return QualType();
6122   }
6123 
6124   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
6125 
6126   bool EPIChanged = false;
6127   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
6128     return QualType();
6129 
6130   // Handle extended parameter information.
6131   if (auto NewExtParamInfos =
6132         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
6133     if (!EPI.ExtParameterInfos ||
6134         llvm::ArrayRef(EPI.ExtParameterInfos, TL.getNumParams()) !=
6135             llvm::ArrayRef(NewExtParamInfos, ParamTypes.size())) {
6136       EPIChanged = true;
6137     }
6138     EPI.ExtParameterInfos = NewExtParamInfos;
6139   } else if (EPI.ExtParameterInfos) {
6140     EPIChanged = true;
6141     EPI.ExtParameterInfos = nullptr;
6142   }
6143 
6144   QualType Result = TL.getType();
6145   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
6146       T->getParamTypes() != llvm::ArrayRef(ParamTypes) || EPIChanged) {
6147     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
6148     if (Result.isNull())
6149       return QualType();
6150   }
6151 
6152   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
6153   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6154   NewTL.setLParenLoc(TL.getLParenLoc());
6155   NewTL.setRParenLoc(TL.getRParenLoc());
6156   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
6157   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6158   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
6159     NewTL.setParam(i, ParamDecls[i]);
6160 
6161   return Result;
6162 }
6163 
6164 template<typename Derived>
6165 bool TreeTransform<Derived>::TransformExceptionSpec(
6166     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6167     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6168   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
6169 
6170   // Instantiate a dynamic noexcept expression, if any.
6171   if (isComputedNoexcept(ESI.Type)) {
6172     EnterExpressionEvaluationContext Unevaluated(
6173         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6174     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6175     if (NoexceptExpr.isInvalid())
6176       return true;
6177 
6178     ExceptionSpecificationType EST = ESI.Type;
6179     NoexceptExpr =
6180         getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6181     if (NoexceptExpr.isInvalid())
6182       return true;
6183 
6184     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6185       Changed = true;
6186     ESI.NoexceptExpr = NoexceptExpr.get();
6187     ESI.Type = EST;
6188   }
6189 
6190   if (ESI.Type != EST_Dynamic)
6191     return false;
6192 
6193   // Instantiate a dynamic exception specification's type.
6194   for (QualType T : ESI.Exceptions) {
6195     if (const PackExpansionType *PackExpansion =
6196             T->getAs<PackExpansionType>()) {
6197       Changed = true;
6198 
6199       // We have a pack expansion. Instantiate it.
6200       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6201       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6202                                               Unexpanded);
6203       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6204 
6205       // Determine whether the set of unexpanded parameter packs can and
6206       // should
6207       // be expanded.
6208       bool Expand = false;
6209       bool RetainExpansion = false;
6210       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6211       // FIXME: Track the location of the ellipsis (and track source location
6212       // information for the types in the exception specification in general).
6213       if (getDerived().TryExpandParameterPacks(
6214               Loc, SourceRange(), Unexpanded, Expand,
6215               RetainExpansion, NumExpansions))
6216         return true;
6217 
6218       if (!Expand) {
6219         // We can't expand this pack expansion into separate arguments yet;
6220         // just substitute into the pattern and create a new pack expansion
6221         // type.
6222         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6223         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6224         if (U.isNull())
6225           return true;
6226 
6227         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6228         Exceptions.push_back(U);
6229         continue;
6230       }
6231 
6232       // Substitute into the pack expansion pattern for each slice of the
6233       // pack.
6234       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6235         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6236 
6237         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6238         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6239           return true;
6240 
6241         Exceptions.push_back(U);
6242       }
6243     } else {
6244       QualType U = getDerived().TransformType(T);
6245       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6246         return true;
6247       if (T != U)
6248         Changed = true;
6249 
6250       Exceptions.push_back(U);
6251     }
6252   }
6253 
6254   ESI.Exceptions = Exceptions;
6255   if (ESI.Exceptions.empty())
6256     ESI.Type = EST_DynamicNone;
6257   return false;
6258 }
6259 
6260 template<typename Derived>
6261 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6262                                                  TypeLocBuilder &TLB,
6263                                                  FunctionNoProtoTypeLoc TL) {
6264   const FunctionNoProtoType *T = TL.getTypePtr();
6265   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6266   if (ResultType.isNull())
6267     return QualType();
6268 
6269   QualType Result = TL.getType();
6270   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6271     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6272 
6273   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6274   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6275   NewTL.setLParenLoc(TL.getLParenLoc());
6276   NewTL.setRParenLoc(TL.getRParenLoc());
6277   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6278 
6279   return Result;
6280 }
6281 
6282 template <typename Derived>
6283 QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6284     TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6285   const UnresolvedUsingType *T = TL.getTypePtr();
6286   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6287   if (!D)
6288     return QualType();
6289 
6290   QualType Result = TL.getType();
6291   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6292     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6293     if (Result.isNull())
6294       return QualType();
6295   }
6296 
6297   // We might get an arbitrary type spec type back.  We should at
6298   // least always get a type spec type, though.
6299   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6300   NewTL.setNameLoc(TL.getNameLoc());
6301 
6302   return Result;
6303 }
6304 
6305 template <typename Derived>
6306 QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6307                                                     UsingTypeLoc TL) {
6308   const UsingType *T = TL.getTypePtr();
6309 
6310   auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6311       TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6312   if (!Found)
6313     return QualType();
6314 
6315   QualType Underlying = getDerived().TransformType(T->desugar());
6316   if (Underlying.isNull())
6317     return QualType();
6318 
6319   QualType Result = TL.getType();
6320   if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6321       Underlying != T->getUnderlyingType()) {
6322     Result = getDerived().RebuildUsingType(Found, Underlying);
6323     if (Result.isNull())
6324       return QualType();
6325   }
6326 
6327   TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6328   return Result;
6329 }
6330 
6331 template<typename Derived>
6332 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6333                                                       TypedefTypeLoc TL) {
6334   const TypedefType *T = TL.getTypePtr();
6335   TypedefNameDecl *Typedef
6336     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6337                                                                T->getDecl()));
6338   if (!Typedef)
6339     return QualType();
6340 
6341   QualType Result = TL.getType();
6342   if (getDerived().AlwaysRebuild() ||
6343       Typedef != T->getDecl()) {
6344     Result = getDerived().RebuildTypedefType(Typedef);
6345     if (Result.isNull())
6346       return QualType();
6347   }
6348 
6349   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6350   NewTL.setNameLoc(TL.getNameLoc());
6351 
6352   return Result;
6353 }
6354 
6355 template<typename Derived>
6356 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6357                                                       TypeOfExprTypeLoc TL) {
6358   // typeof expressions are not potentially evaluated contexts
6359   EnterExpressionEvaluationContext Unevaluated(
6360       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6361       Sema::ReuseLambdaContextDecl);
6362 
6363   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6364   if (E.isInvalid())
6365     return QualType();
6366 
6367   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6368   if (E.isInvalid())
6369     return QualType();
6370 
6371   QualType Result = TL.getType();
6372   TypeOfKind Kind = Result->getAs<TypeOfExprType>()->getKind();
6373   if (getDerived().AlwaysRebuild() || E.get() != TL.getUnderlyingExpr()) {
6374     Result =
6375         getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc(), Kind);
6376     if (Result.isNull())
6377       return QualType();
6378   }
6379 
6380   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6381   NewTL.setTypeofLoc(TL.getTypeofLoc());
6382   NewTL.setLParenLoc(TL.getLParenLoc());
6383   NewTL.setRParenLoc(TL.getRParenLoc());
6384 
6385   return Result;
6386 }
6387 
6388 template<typename Derived>
6389 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6390                                                      TypeOfTypeLoc TL) {
6391   TypeSourceInfo* Old_Under_TI = TL.getUnmodifiedTInfo();
6392   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6393   if (!New_Under_TI)
6394     return QualType();
6395 
6396   QualType Result = TL.getType();
6397   TypeOfKind Kind = Result->getAs<TypeOfType>()->getKind();
6398   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6399     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType(), Kind);
6400     if (Result.isNull())
6401       return QualType();
6402   }
6403 
6404   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6405   NewTL.setTypeofLoc(TL.getTypeofLoc());
6406   NewTL.setLParenLoc(TL.getLParenLoc());
6407   NewTL.setRParenLoc(TL.getRParenLoc());
6408   NewTL.setUnmodifiedTInfo(New_Under_TI);
6409 
6410   return Result;
6411 }
6412 
6413 template<typename Derived>
6414 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6415                                                        DecltypeTypeLoc TL) {
6416   const DecltypeType *T = TL.getTypePtr();
6417 
6418   // decltype expressions are not potentially evaluated contexts
6419   EnterExpressionEvaluationContext Unevaluated(
6420       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6421       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6422 
6423   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6424   if (E.isInvalid())
6425     return QualType();
6426 
6427   E = getSema().ActOnDecltypeExpression(E.get());
6428   if (E.isInvalid())
6429     return QualType();
6430 
6431   QualType Result = TL.getType();
6432   if (getDerived().AlwaysRebuild() ||
6433       E.get() != T->getUnderlyingExpr()) {
6434     Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6435     if (Result.isNull())
6436       return QualType();
6437   }
6438   else E.get();
6439 
6440   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6441   NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6442   NewTL.setRParenLoc(TL.getRParenLoc());
6443   return Result;
6444 }
6445 
6446 template<typename Derived>
6447 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6448                                                             TypeLocBuilder &TLB,
6449                                                      UnaryTransformTypeLoc TL) {
6450   QualType Result = TL.getType();
6451   if (Result->isDependentType()) {
6452     const UnaryTransformType *T = TL.getTypePtr();
6453     QualType NewBase =
6454       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6455     Result = getDerived().RebuildUnaryTransformType(NewBase,
6456                                                     T->getUTTKind(),
6457                                                     TL.getKWLoc());
6458     if (Result.isNull())
6459       return QualType();
6460   }
6461 
6462   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6463   NewTL.setKWLoc(TL.getKWLoc());
6464   NewTL.setParensRange(TL.getParensRange());
6465   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6466   return Result;
6467 }
6468 
6469 template<typename Derived>
6470 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6471     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6472   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6473 
6474   CXXScopeSpec SS;
6475   TemplateName TemplateName = getDerived().TransformTemplateName(
6476       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6477   if (TemplateName.isNull())
6478     return QualType();
6479 
6480   QualType OldDeduced = T->getDeducedType();
6481   QualType NewDeduced;
6482   if (!OldDeduced.isNull()) {
6483     NewDeduced = getDerived().TransformType(OldDeduced);
6484     if (NewDeduced.isNull())
6485       return QualType();
6486   }
6487 
6488   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6489       TemplateName, NewDeduced);
6490   if (Result.isNull())
6491     return QualType();
6492 
6493   DeducedTemplateSpecializationTypeLoc NewTL =
6494       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6495   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6496 
6497   return Result;
6498 }
6499 
6500 template<typename Derived>
6501 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6502                                                      RecordTypeLoc TL) {
6503   const RecordType *T = TL.getTypePtr();
6504   RecordDecl *Record
6505     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6506                                                           T->getDecl()));
6507   if (!Record)
6508     return QualType();
6509 
6510   QualType Result = TL.getType();
6511   if (getDerived().AlwaysRebuild() ||
6512       Record != T->getDecl()) {
6513     Result = getDerived().RebuildRecordType(Record);
6514     if (Result.isNull())
6515       return QualType();
6516   }
6517 
6518   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6519   NewTL.setNameLoc(TL.getNameLoc());
6520 
6521   return Result;
6522 }
6523 
6524 template<typename Derived>
6525 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6526                                                    EnumTypeLoc TL) {
6527   const EnumType *T = TL.getTypePtr();
6528   EnumDecl *Enum
6529     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6530                                                         T->getDecl()));
6531   if (!Enum)
6532     return QualType();
6533 
6534   QualType Result = TL.getType();
6535   if (getDerived().AlwaysRebuild() ||
6536       Enum != T->getDecl()) {
6537     Result = getDerived().RebuildEnumType(Enum);
6538     if (Result.isNull())
6539       return QualType();
6540   }
6541 
6542   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6543   NewTL.setNameLoc(TL.getNameLoc());
6544 
6545   return Result;
6546 }
6547 
6548 template<typename Derived>
6549 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6550                                          TypeLocBuilder &TLB,
6551                                          InjectedClassNameTypeLoc TL) {
6552   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6553                                        TL.getTypePtr()->getDecl());
6554   if (!D) return QualType();
6555 
6556   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6557   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6558   return T;
6559 }
6560 
6561 template<typename Derived>
6562 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6563                                                 TypeLocBuilder &TLB,
6564                                                 TemplateTypeParmTypeLoc TL) {
6565   return getDerived().TransformTemplateTypeParmType(
6566       TLB, TL,
6567       /*SuppressObjCLifetime=*/false);
6568 }
6569 
6570 template <typename Derived>
6571 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6572     TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL, bool) {
6573   return TransformTypeSpecType(TLB, TL);
6574 }
6575 
6576 template<typename Derived>
6577 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6578                                          TypeLocBuilder &TLB,
6579                                          SubstTemplateTypeParmTypeLoc TL) {
6580   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6581 
6582   Decl *NewReplaced =
6583       getDerived().TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
6584 
6585   // Substitute into the replacement type, which itself might involve something
6586   // that needs to be transformed. This only tends to occur with default
6587   // template arguments of template template parameters.
6588   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6589   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6590   if (Replacement.isNull())
6591     return QualType();
6592 
6593   QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
6594       Replacement, NewReplaced, T->getIndex(), T->getPackIndex());
6595 
6596   // Propagate type-source information.
6597   SubstTemplateTypeParmTypeLoc NewTL
6598     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6599   NewTL.setNameLoc(TL.getNameLoc());
6600   return Result;
6601 
6602 }
6603 
6604 template<typename Derived>
6605 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6606                                           TypeLocBuilder &TLB,
6607                                           SubstTemplateTypeParmPackTypeLoc TL) {
6608   return getDerived().TransformSubstTemplateTypeParmPackType(
6609       TLB, TL, /*SuppressObjCLifetime=*/false);
6610 }
6611 
6612 template <typename Derived>
6613 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6614     TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, bool) {
6615   return TransformTypeSpecType(TLB, TL);
6616 }
6617 
6618 template<typename Derived>
6619 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6620                                                         TypeLocBuilder &TLB,
6621                                            TemplateSpecializationTypeLoc TL) {
6622   const TemplateSpecializationType *T = TL.getTypePtr();
6623 
6624   // The nested-name-specifier never matters in a TemplateSpecializationType,
6625   // because we can't have a dependent nested-name-specifier anyway.
6626   CXXScopeSpec SS;
6627   TemplateName Template
6628     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6629                                          TL.getTemplateNameLoc());
6630   if (Template.isNull())
6631     return QualType();
6632 
6633   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6634 }
6635 
6636 template<typename Derived>
6637 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6638                                                      AtomicTypeLoc TL) {
6639   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6640   if (ValueType.isNull())
6641     return QualType();
6642 
6643   QualType Result = TL.getType();
6644   if (getDerived().AlwaysRebuild() ||
6645       ValueType != TL.getValueLoc().getType()) {
6646     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6647     if (Result.isNull())
6648       return QualType();
6649   }
6650 
6651   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6652   NewTL.setKWLoc(TL.getKWLoc());
6653   NewTL.setLParenLoc(TL.getLParenLoc());
6654   NewTL.setRParenLoc(TL.getRParenLoc());
6655 
6656   return Result;
6657 }
6658 
6659 template <typename Derived>
6660 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6661                                                    PipeTypeLoc 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() || ValueType != TL.getValueLoc().getType()) {
6668     const PipeType *PT = Result->castAs<PipeType>();
6669     bool isReadPipe = PT->isReadOnly();
6670     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6671     if (Result.isNull())
6672       return QualType();
6673   }
6674 
6675   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6676   NewTL.setKWLoc(TL.getKWLoc());
6677 
6678   return Result;
6679 }
6680 
6681 template <typename Derived>
6682 QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6683                                                      BitIntTypeLoc TL) {
6684   const BitIntType *EIT = TL.getTypePtr();
6685   QualType Result = TL.getType();
6686 
6687   if (getDerived().AlwaysRebuild()) {
6688     Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6689                                             EIT->getNumBits(), TL.getNameLoc());
6690     if (Result.isNull())
6691       return QualType();
6692   }
6693 
6694   BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6695   NewTL.setNameLoc(TL.getNameLoc());
6696   return Result;
6697 }
6698 
6699 template <typename Derived>
6700 QualType TreeTransform<Derived>::TransformDependentBitIntType(
6701     TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6702   const DependentBitIntType *EIT = TL.getTypePtr();
6703 
6704   EnterExpressionEvaluationContext Unevaluated(
6705       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6706   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6707   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6708 
6709   if (BitsExpr.isInvalid())
6710     return QualType();
6711 
6712   QualType Result = TL.getType();
6713 
6714   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6715     Result = getDerived().RebuildDependentBitIntType(
6716         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6717 
6718     if (Result.isNull())
6719       return QualType();
6720   }
6721 
6722   if (isa<DependentBitIntType>(Result)) {
6723     DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6724     NewTL.setNameLoc(TL.getNameLoc());
6725   } else {
6726     BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6727     NewTL.setNameLoc(TL.getNameLoc());
6728   }
6729   return Result;
6730 }
6731 
6732   /// Simple iterator that traverses the template arguments in a
6733   /// container that provides a \c getArgLoc() member function.
6734   ///
6735   /// This iterator is intended to be used with the iterator form of
6736   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6737   template<typename ArgLocContainer>
6738   class TemplateArgumentLocContainerIterator {
6739     ArgLocContainer *Container;
6740     unsigned Index;
6741 
6742   public:
6743     typedef TemplateArgumentLoc value_type;
6744     typedef TemplateArgumentLoc reference;
6745     typedef int difference_type;
6746     typedef std::input_iterator_tag iterator_category;
6747 
6748     class pointer {
6749       TemplateArgumentLoc Arg;
6750 
6751     public:
6752       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6753 
6754       const TemplateArgumentLoc *operator->() const {
6755         return &Arg;
6756       }
6757     };
6758 
6759 
6760     TemplateArgumentLocContainerIterator() {}
6761 
6762     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6763                                  unsigned Index)
6764       : Container(&Container), Index(Index) { }
6765 
6766     TemplateArgumentLocContainerIterator &operator++() {
6767       ++Index;
6768       return *this;
6769     }
6770 
6771     TemplateArgumentLocContainerIterator operator++(int) {
6772       TemplateArgumentLocContainerIterator Old(*this);
6773       ++(*this);
6774       return Old;
6775     }
6776 
6777     TemplateArgumentLoc operator*() const {
6778       return Container->getArgLoc(Index);
6779     }
6780 
6781     pointer operator->() const {
6782       return pointer(Container->getArgLoc(Index));
6783     }
6784 
6785     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6786                            const TemplateArgumentLocContainerIterator &Y) {
6787       return X.Container == Y.Container && X.Index == Y.Index;
6788     }
6789 
6790     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6791                            const TemplateArgumentLocContainerIterator &Y) {
6792       return !(X == Y);
6793     }
6794   };
6795 
6796 template<typename Derived>
6797 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6798                                                    AutoTypeLoc TL) {
6799   const AutoType *T = TL.getTypePtr();
6800   QualType OldDeduced = T->getDeducedType();
6801   QualType NewDeduced;
6802   if (!OldDeduced.isNull()) {
6803     NewDeduced = getDerived().TransformType(OldDeduced);
6804     if (NewDeduced.isNull())
6805       return QualType();
6806   }
6807 
6808   ConceptDecl *NewCD = nullptr;
6809   TemplateArgumentListInfo NewTemplateArgs;
6810   NestedNameSpecifierLoc NewNestedNameSpec;
6811   if (T->isConstrained()) {
6812     NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6813         TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6814 
6815     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6816     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6817     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6818     if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6819                                                 ArgIterator(TL,
6820                                                             TL.getNumArgs()),
6821                                                 NewTemplateArgs))
6822       return QualType();
6823 
6824     if (TL.getNestedNameSpecifierLoc()) {
6825       NewNestedNameSpec
6826         = getDerived().TransformNestedNameSpecifierLoc(
6827             TL.getNestedNameSpecifierLoc());
6828       if (!NewNestedNameSpec)
6829         return QualType();
6830     }
6831   }
6832 
6833   QualType Result = TL.getType();
6834   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6835       T->isDependentType() || T->isConstrained()) {
6836     // FIXME: Maybe don't rebuild if all template arguments are the same.
6837     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6838     NewArgList.reserve(NewTemplateArgs.size());
6839     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6840       NewArgList.push_back(ArgLoc.getArgument());
6841     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6842                                           NewArgList);
6843     if (Result.isNull())
6844       return QualType();
6845   }
6846 
6847   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6848   NewTL.setNameLoc(TL.getNameLoc());
6849   NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6850   NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6851   NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6852   NewTL.setFoundDecl(TL.getFoundDecl());
6853   NewTL.setLAngleLoc(TL.getLAngleLoc());
6854   NewTL.setRAngleLoc(TL.getRAngleLoc());
6855   NewTL.setRParenLoc(TL.getRParenLoc());
6856   for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6857     NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6858 
6859   return Result;
6860 }
6861 
6862 template <typename Derived>
6863 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6864                                                         TypeLocBuilder &TLB,
6865                                            TemplateSpecializationTypeLoc TL,
6866                                                       TemplateName Template) {
6867   TemplateArgumentListInfo NewTemplateArgs;
6868   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6869   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6870   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6871     ArgIterator;
6872   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6873                                               ArgIterator(TL, TL.getNumArgs()),
6874                                               NewTemplateArgs))
6875     return QualType();
6876 
6877   // FIXME: maybe don't rebuild if all the template arguments are the same.
6878 
6879   QualType Result =
6880     getDerived().RebuildTemplateSpecializationType(Template,
6881                                                    TL.getTemplateNameLoc(),
6882                                                    NewTemplateArgs);
6883 
6884   if (!Result.isNull()) {
6885     // Specializations of template template parameters are represented as
6886     // TemplateSpecializationTypes, and substitution of type alias templates
6887     // within a dependent context can transform them into
6888     // DependentTemplateSpecializationTypes.
6889     if (isa<DependentTemplateSpecializationType>(Result)) {
6890       DependentTemplateSpecializationTypeLoc NewTL
6891         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6892       NewTL.setElaboratedKeywordLoc(SourceLocation());
6893       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6894       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6895       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6896       NewTL.setLAngleLoc(TL.getLAngleLoc());
6897       NewTL.setRAngleLoc(TL.getRAngleLoc());
6898       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6899         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6900       return Result;
6901     }
6902 
6903     TemplateSpecializationTypeLoc NewTL
6904       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6905     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6906     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6907     NewTL.setLAngleLoc(TL.getLAngleLoc());
6908     NewTL.setRAngleLoc(TL.getRAngleLoc());
6909     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6910       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6911   }
6912 
6913   return Result;
6914 }
6915 
6916 template <typename Derived>
6917 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6918                                      TypeLocBuilder &TLB,
6919                                      DependentTemplateSpecializationTypeLoc TL,
6920                                      TemplateName Template,
6921                                      CXXScopeSpec &SS) {
6922   TemplateArgumentListInfo NewTemplateArgs;
6923   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6924   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6925   typedef TemplateArgumentLocContainerIterator<
6926             DependentTemplateSpecializationTypeLoc> ArgIterator;
6927   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6928                                               ArgIterator(TL, TL.getNumArgs()),
6929                                               NewTemplateArgs))
6930     return QualType();
6931 
6932   // FIXME: maybe don't rebuild if all the template arguments are the same.
6933 
6934   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6935     QualType Result = getSema().Context.getDependentTemplateSpecializationType(
6936         TL.getTypePtr()->getKeyword(), DTN->getQualifier(),
6937         DTN->getIdentifier(), NewTemplateArgs.arguments());
6938 
6939     DependentTemplateSpecializationTypeLoc NewTL
6940       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6941     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6942     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6943     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6944     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6945     NewTL.setLAngleLoc(TL.getLAngleLoc());
6946     NewTL.setRAngleLoc(TL.getRAngleLoc());
6947     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6948       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6949     return Result;
6950   }
6951 
6952   QualType Result
6953     = getDerived().RebuildTemplateSpecializationType(Template,
6954                                                      TL.getTemplateNameLoc(),
6955                                                      NewTemplateArgs);
6956 
6957   if (!Result.isNull()) {
6958     /// FIXME: Wrap this in an elaborated-type-specifier?
6959     TemplateSpecializationTypeLoc NewTL
6960       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6961     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6962     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6963     NewTL.setLAngleLoc(TL.getLAngleLoc());
6964     NewTL.setRAngleLoc(TL.getRAngleLoc());
6965     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6966       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6967   }
6968 
6969   return Result;
6970 }
6971 
6972 template<typename Derived>
6973 QualType
6974 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6975                                                 ElaboratedTypeLoc TL) {
6976   const ElaboratedType *T = TL.getTypePtr();
6977 
6978   NestedNameSpecifierLoc QualifierLoc;
6979   // NOTE: the qualifier in an ElaboratedType is optional.
6980   if (TL.getQualifierLoc()) {
6981     QualifierLoc
6982       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6983     if (!QualifierLoc)
6984       return QualType();
6985   }
6986 
6987   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6988   if (NamedT.isNull())
6989     return QualType();
6990 
6991   // C++0x [dcl.type.elab]p2:
6992   //   If the identifier resolves to a typedef-name or the simple-template-id
6993   //   resolves to an alias template specialization, the
6994   //   elaborated-type-specifier is ill-formed.
6995   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6996     if (const TemplateSpecializationType *TST =
6997           NamedT->getAs<TemplateSpecializationType>()) {
6998       TemplateName Template = TST->getTemplateName();
6999       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
7000               Template.getAsTemplateDecl())) {
7001         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
7002                      diag::err_tag_reference_non_tag)
7003             << TAT << Sema::NTK_TypeAliasTemplate
7004             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
7005         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
7006       }
7007     }
7008   }
7009 
7010   QualType Result = TL.getType();
7011   if (getDerived().AlwaysRebuild() ||
7012       QualifierLoc != TL.getQualifierLoc() ||
7013       NamedT != T->getNamedType()) {
7014     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
7015                                                 T->getKeyword(),
7016                                                 QualifierLoc, NamedT);
7017     if (Result.isNull())
7018       return QualType();
7019   }
7020 
7021   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7022   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7023   NewTL.setQualifierLoc(QualifierLoc);
7024   return Result;
7025 }
7026 
7027 template<typename Derived>
7028 QualType TreeTransform<Derived>::TransformAttributedType(
7029                                                 TypeLocBuilder &TLB,
7030                                                 AttributedTypeLoc TL) {
7031   const AttributedType *oldType = TL.getTypePtr();
7032   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
7033   if (modifiedType.isNull())
7034     return QualType();
7035 
7036   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
7037   const Attr *oldAttr = TL.getAttr();
7038   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
7039   if (oldAttr && !newAttr)
7040     return QualType();
7041 
7042   QualType result = TL.getType();
7043 
7044   // FIXME: dependent operand expressions?
7045   if (getDerived().AlwaysRebuild() ||
7046       modifiedType != oldType->getModifiedType()) {
7047     // TODO: this is really lame; we should really be rebuilding the
7048     // equivalent type from first principles.
7049     QualType equivalentType
7050       = getDerived().TransformType(oldType->getEquivalentType());
7051     if (equivalentType.isNull())
7052       return QualType();
7053 
7054     // Check whether we can add nullability; it is only represented as
7055     // type sugar, and therefore cannot be diagnosed in any other way.
7056     if (auto nullability = oldType->getImmediateNullability()) {
7057       if (!modifiedType->canHaveNullability()) {
7058         SemaRef.Diag((TL.getAttr() ? TL.getAttr()->getLocation()
7059                                    : TL.getModifiedLoc().getBeginLoc()),
7060                      diag::err_nullability_nonpointer)
7061             << DiagNullabilityKind(*nullability, false) << modifiedType;
7062         return QualType();
7063       }
7064     }
7065 
7066     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
7067                                                modifiedType,
7068                                                equivalentType);
7069   }
7070 
7071   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
7072   newTL.setAttr(newAttr);
7073   return result;
7074 }
7075 
7076 template <typename Derived>
7077 QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
7078     TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
7079   // The BTFTagAttributedType is available for C only.
7080   llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType");
7081 }
7082 
7083 template<typename Derived>
7084 QualType
7085 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
7086                                            ParenTypeLoc TL) {
7087   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7088   if (Inner.isNull())
7089     return QualType();
7090 
7091   QualType Result = TL.getType();
7092   if (getDerived().AlwaysRebuild() ||
7093       Inner != TL.getInnerLoc().getType()) {
7094     Result = getDerived().RebuildParenType(Inner);
7095     if (Result.isNull())
7096       return QualType();
7097   }
7098 
7099   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
7100   NewTL.setLParenLoc(TL.getLParenLoc());
7101   NewTL.setRParenLoc(TL.getRParenLoc());
7102   return Result;
7103 }
7104 
7105 template <typename Derived>
7106 QualType
7107 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
7108                                                     MacroQualifiedTypeLoc TL) {
7109   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7110   if (Inner.isNull())
7111     return QualType();
7112 
7113   QualType Result = TL.getType();
7114   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
7115     Result =
7116         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
7117     if (Result.isNull())
7118       return QualType();
7119   }
7120 
7121   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
7122   NewTL.setExpansionLoc(TL.getExpansionLoc());
7123   return Result;
7124 }
7125 
7126 template<typename Derived>
7127 QualType TreeTransform<Derived>::TransformDependentNameType(
7128     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
7129   return TransformDependentNameType(TLB, TL, false);
7130 }
7131 
7132 template<typename Derived>
7133 QualType TreeTransform<Derived>::TransformDependentNameType(
7134     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
7135   const DependentNameType *T = TL.getTypePtr();
7136 
7137   NestedNameSpecifierLoc QualifierLoc
7138     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7139   if (!QualifierLoc)
7140     return QualType();
7141 
7142   QualType Result
7143     = getDerived().RebuildDependentNameType(T->getKeyword(),
7144                                             TL.getElaboratedKeywordLoc(),
7145                                             QualifierLoc,
7146                                             T->getIdentifier(),
7147                                             TL.getNameLoc(),
7148                                             DeducedTSTContext);
7149   if (Result.isNull())
7150     return QualType();
7151 
7152   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
7153     QualType NamedT = ElabT->getNamedType();
7154     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
7155 
7156     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7157     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7158     NewTL.setQualifierLoc(QualifierLoc);
7159   } else {
7160     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
7161     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7162     NewTL.setQualifierLoc(QualifierLoc);
7163     NewTL.setNameLoc(TL.getNameLoc());
7164   }
7165   return Result;
7166 }
7167 
7168 template<typename Derived>
7169 QualType TreeTransform<Derived>::
7170           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7171                                  DependentTemplateSpecializationTypeLoc TL) {
7172   NestedNameSpecifierLoc QualifierLoc;
7173   if (TL.getQualifierLoc()) {
7174     QualifierLoc
7175       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7176     if (!QualifierLoc)
7177       return QualType();
7178   }
7179 
7180   return getDerived()
7181            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7182 }
7183 
7184 template<typename Derived>
7185 QualType TreeTransform<Derived>::
7186 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7187                                    DependentTemplateSpecializationTypeLoc TL,
7188                                        NestedNameSpecifierLoc QualifierLoc) {
7189   const DependentTemplateSpecializationType *T = TL.getTypePtr();
7190 
7191   TemplateArgumentListInfo NewTemplateArgs;
7192   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7193   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7194 
7195   typedef TemplateArgumentLocContainerIterator<
7196   DependentTemplateSpecializationTypeLoc> ArgIterator;
7197   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7198                                               ArgIterator(TL, TL.getNumArgs()),
7199                                               NewTemplateArgs))
7200     return QualType();
7201 
7202   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7203       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7204       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7205       /*AllowInjectedClassName*/ false);
7206   if (Result.isNull())
7207     return QualType();
7208 
7209   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7210     QualType NamedT = ElabT->getNamedType();
7211 
7212     // Copy information relevant to the template specialization.
7213     TemplateSpecializationTypeLoc NamedTL
7214       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7215     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7216     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7217     NamedTL.setLAngleLoc(TL.getLAngleLoc());
7218     NamedTL.setRAngleLoc(TL.getRAngleLoc());
7219     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7220       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7221 
7222     // Copy information relevant to the elaborated type.
7223     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7224     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7225     NewTL.setQualifierLoc(QualifierLoc);
7226   } else if (isa<DependentTemplateSpecializationType>(Result)) {
7227     DependentTemplateSpecializationTypeLoc SpecTL
7228       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7229     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7230     SpecTL.setQualifierLoc(QualifierLoc);
7231     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7232     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7233     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7234     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7235     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7236       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7237   } else {
7238     TemplateSpecializationTypeLoc SpecTL
7239       = TLB.push<TemplateSpecializationTypeLoc>(Result);
7240     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7241     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7242     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7243     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7244     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7245       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7246   }
7247   return Result;
7248 }
7249 
7250 template<typename Derived>
7251 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7252                                                       PackExpansionTypeLoc TL) {
7253   QualType Pattern
7254     = getDerived().TransformType(TLB, TL.getPatternLoc());
7255   if (Pattern.isNull())
7256     return QualType();
7257 
7258   QualType Result = TL.getType();
7259   if (getDerived().AlwaysRebuild() ||
7260       Pattern != TL.getPatternLoc().getType()) {
7261     Result = getDerived().RebuildPackExpansionType(Pattern,
7262                                            TL.getPatternLoc().getSourceRange(),
7263                                                    TL.getEllipsisLoc(),
7264                                            TL.getTypePtr()->getNumExpansions());
7265     if (Result.isNull())
7266       return QualType();
7267   }
7268 
7269   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7270   NewT.setEllipsisLoc(TL.getEllipsisLoc());
7271   return Result;
7272 }
7273 
7274 template<typename Derived>
7275 QualType
7276 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7277                                                    ObjCInterfaceTypeLoc TL) {
7278   // ObjCInterfaceType is never dependent.
7279   TLB.pushFullCopy(TL);
7280   return TL.getType();
7281 }
7282 
7283 template<typename Derived>
7284 QualType
7285 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7286                                                    ObjCTypeParamTypeLoc TL) {
7287   const ObjCTypeParamType *T = TL.getTypePtr();
7288   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7289       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7290   if (!OTP)
7291     return QualType();
7292 
7293   QualType Result = TL.getType();
7294   if (getDerived().AlwaysRebuild() ||
7295       OTP != T->getDecl()) {
7296     Result = getDerived().RebuildObjCTypeParamType(
7297         OTP, TL.getProtocolLAngleLoc(),
7298         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7299         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7300     if (Result.isNull())
7301       return QualType();
7302   }
7303 
7304   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7305   if (TL.getNumProtocols()) {
7306     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7307     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7308       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7309     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7310   }
7311   return Result;
7312 }
7313 
7314 template<typename Derived>
7315 QualType
7316 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7317                                                 ObjCObjectTypeLoc TL) {
7318   // Transform base type.
7319   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7320   if (BaseType.isNull())
7321     return QualType();
7322 
7323   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7324 
7325   // Transform type arguments.
7326   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7327   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7328     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7329     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7330     QualType TypeArg = TypeArgInfo->getType();
7331     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7332       AnyChanged = true;
7333 
7334       // We have a pack expansion. Instantiate it.
7335       const auto *PackExpansion = PackExpansionLoc.getType()
7336                                     ->castAs<PackExpansionType>();
7337       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7338       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7339                                               Unexpanded);
7340       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
7341 
7342       // Determine whether the set of unexpanded parameter packs can
7343       // and should be expanded.
7344       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7345       bool Expand = false;
7346       bool RetainExpansion = false;
7347       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7348       if (getDerived().TryExpandParameterPacks(
7349             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7350             Unexpanded, Expand, RetainExpansion, NumExpansions))
7351         return QualType();
7352 
7353       if (!Expand) {
7354         // We can't expand this pack expansion into separate arguments yet;
7355         // just substitute into the pattern and create a new pack expansion
7356         // type.
7357         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7358 
7359         TypeLocBuilder TypeArgBuilder;
7360         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7361         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7362                                                              PatternLoc);
7363         if (NewPatternType.isNull())
7364           return QualType();
7365 
7366         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7367                                       NewPatternType, NumExpansions);
7368         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7369         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7370         NewTypeArgInfos.push_back(
7371           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7372         continue;
7373       }
7374 
7375       // Substitute into the pack expansion pattern for each slice of the
7376       // pack.
7377       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7378         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7379 
7380         TypeLocBuilder TypeArgBuilder;
7381         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7382 
7383         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7384                                                          PatternLoc);
7385         if (NewTypeArg.isNull())
7386           return QualType();
7387 
7388         NewTypeArgInfos.push_back(
7389           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7390       }
7391 
7392       continue;
7393     }
7394 
7395     TypeLocBuilder TypeArgBuilder;
7396     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7397     QualType NewTypeArg =
7398         getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7399     if (NewTypeArg.isNull())
7400       return QualType();
7401 
7402     // If nothing changed, just keep the old TypeSourceInfo.
7403     if (NewTypeArg == TypeArg) {
7404       NewTypeArgInfos.push_back(TypeArgInfo);
7405       continue;
7406     }
7407 
7408     NewTypeArgInfos.push_back(
7409       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7410     AnyChanged = true;
7411   }
7412 
7413   QualType Result = TL.getType();
7414   if (getDerived().AlwaysRebuild() || AnyChanged) {
7415     // Rebuild the type.
7416     Result = getDerived().RebuildObjCObjectType(
7417         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7418         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7419         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7420         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7421 
7422     if (Result.isNull())
7423       return QualType();
7424   }
7425 
7426   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7427   NewT.setHasBaseTypeAsWritten(true);
7428   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7429   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7430     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7431   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7432   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7433   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7434     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7435   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7436   return Result;
7437 }
7438 
7439 template<typename Derived>
7440 QualType
7441 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7442                                                ObjCObjectPointerTypeLoc TL) {
7443   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7444   if (PointeeType.isNull())
7445     return QualType();
7446 
7447   QualType Result = TL.getType();
7448   if (getDerived().AlwaysRebuild() ||
7449       PointeeType != TL.getPointeeLoc().getType()) {
7450     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7451                                                        TL.getStarLoc());
7452     if (Result.isNull())
7453       return QualType();
7454   }
7455 
7456   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7457   NewT.setStarLoc(TL.getStarLoc());
7458   return Result;
7459 }
7460 
7461 //===----------------------------------------------------------------------===//
7462 // Statement transformation
7463 //===----------------------------------------------------------------------===//
7464 template<typename Derived>
7465 StmtResult
7466 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7467   return S;
7468 }
7469 
7470 template<typename Derived>
7471 StmtResult
7472 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7473   return getDerived().TransformCompoundStmt(S, false);
7474 }
7475 
7476 template<typename Derived>
7477 StmtResult
7478 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7479                                               bool IsStmtExpr) {
7480   Sema::CompoundScopeRAII CompoundScope(getSema());
7481   Sema::FPFeaturesStateRAII FPSave(getSema());
7482   if (S->hasStoredFPFeatures())
7483     getSema().resetFPOptions(
7484         S->getStoredFPFeatures().applyOverrides(getSema().getLangOpts()));
7485 
7486   const Stmt *ExprResult = S->getStmtExprResult();
7487   bool SubStmtInvalid = false;
7488   bool SubStmtChanged = false;
7489   SmallVector<Stmt*, 8> Statements;
7490   for (auto *B : S->body()) {
7491     StmtResult Result = getDerived().TransformStmt(
7492         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7493 
7494     if (Result.isInvalid()) {
7495       // Immediately fail if this was a DeclStmt, since it's very
7496       // likely that this will cause problems for future statements.
7497       if (isa<DeclStmt>(B))
7498         return StmtError();
7499 
7500       // Otherwise, just keep processing substatements and fail later.
7501       SubStmtInvalid = true;
7502       continue;
7503     }
7504 
7505     SubStmtChanged = SubStmtChanged || Result.get() != B;
7506     Statements.push_back(Result.getAs<Stmt>());
7507   }
7508 
7509   if (SubStmtInvalid)
7510     return StmtError();
7511 
7512   if (!getDerived().AlwaysRebuild() &&
7513       !SubStmtChanged)
7514     return S;
7515 
7516   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7517                                           Statements,
7518                                           S->getRBracLoc(),
7519                                           IsStmtExpr);
7520 }
7521 
7522 template<typename Derived>
7523 StmtResult
7524 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7525   ExprResult LHS, RHS;
7526   {
7527     EnterExpressionEvaluationContext Unevaluated(
7528         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7529 
7530     // Transform the left-hand case value.
7531     LHS = getDerived().TransformExpr(S->getLHS());
7532     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7533     if (LHS.isInvalid())
7534       return StmtError();
7535 
7536     // Transform the right-hand case value (for the GNU case-range extension).
7537     RHS = getDerived().TransformExpr(S->getRHS());
7538     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7539     if (RHS.isInvalid())
7540       return StmtError();
7541   }
7542 
7543   // Build the case statement.
7544   // Case statements are always rebuilt so that they will attached to their
7545   // transformed switch statement.
7546   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7547                                                        LHS.get(),
7548                                                        S->getEllipsisLoc(),
7549                                                        RHS.get(),
7550                                                        S->getColonLoc());
7551   if (Case.isInvalid())
7552     return StmtError();
7553 
7554   // Transform the statement following the case
7555   StmtResult SubStmt =
7556       getDerived().TransformStmt(S->getSubStmt());
7557   if (SubStmt.isInvalid())
7558     return StmtError();
7559 
7560   // Attach the body to the case statement
7561   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7562 }
7563 
7564 template <typename Derived>
7565 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7566   // Transform the statement following the default case
7567   StmtResult SubStmt =
7568       getDerived().TransformStmt(S->getSubStmt());
7569   if (SubStmt.isInvalid())
7570     return StmtError();
7571 
7572   // Default statements are always rebuilt
7573   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7574                                          SubStmt.get());
7575 }
7576 
7577 template<typename Derived>
7578 StmtResult
7579 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7580   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7581   if (SubStmt.isInvalid())
7582     return StmtError();
7583 
7584   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7585                                         S->getDecl());
7586   if (!LD)
7587     return StmtError();
7588 
7589   // If we're transforming "in-place" (we're not creating new local
7590   // declarations), assume we're replacing the old label statement
7591   // and clear out the reference to it.
7592   if (LD == S->getDecl())
7593     S->getDecl()->setStmt(nullptr);
7594 
7595   // FIXME: Pass the real colon location in.
7596   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7597                                        cast<LabelDecl>(LD), SourceLocation(),
7598                                        SubStmt.get());
7599 }
7600 
7601 template <typename Derived>
7602 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7603   if (!R)
7604     return R;
7605 
7606   switch (R->getKind()) {
7607 // Transform attributes by calling TransformXXXAttr.
7608 #define ATTR(X)                                                                \
7609   case attr::X:                                                                \
7610     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7611 #include "clang/Basic/AttrList.inc"
7612   }
7613   return R;
7614 }
7615 
7616 template <typename Derived>
7617 const Attr *TreeTransform<Derived>::TransformStmtAttr(const Stmt *OrigS,
7618                                                       const Stmt *InstS,
7619                                                       const Attr *R) {
7620   if (!R)
7621     return R;
7622 
7623   switch (R->getKind()) {
7624 // Transform attributes by calling TransformStmtXXXAttr.
7625 #define ATTR(X)                                                                \
7626   case attr::X:                                                                \
7627     return getDerived().TransformStmt##X##Attr(OrigS, InstS, cast<X##Attr>(R));
7628 #include "clang/Basic/AttrList.inc"
7629   }
7630   return TransformAttr(R);
7631 }
7632 
7633 template <typename Derived>
7634 StmtResult
7635 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7636                                                 StmtDiscardKind SDK) {
7637   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7638   if (SubStmt.isInvalid())
7639     return StmtError();
7640 
7641   bool AttrsChanged = false;
7642   SmallVector<const Attr *, 1> Attrs;
7643 
7644   // Visit attributes and keep track if any are transformed.
7645   for (const auto *I : S->getAttrs()) {
7646     const Attr *R =
7647         getDerived().TransformStmtAttr(S->getSubStmt(), SubStmt.get(), I);
7648     AttrsChanged |= (I != R);
7649     if (R)
7650       Attrs.push_back(R);
7651   }
7652 
7653   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7654     return S;
7655 
7656   // If transforming the attributes failed for all of the attributes in the
7657   // statement, don't make an AttributedStmt without attributes.
7658   if (Attrs.empty())
7659     return SubStmt;
7660 
7661   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7662                                             SubStmt.get());
7663 }
7664 
7665 template<typename Derived>
7666 StmtResult
7667 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7668   // Transform the initialization statement
7669   StmtResult Init = getDerived().TransformStmt(S->getInit());
7670   if (Init.isInvalid())
7671     return StmtError();
7672 
7673   Sema::ConditionResult Cond;
7674   if (!S->isConsteval()) {
7675     // Transform the condition
7676     Cond = getDerived().TransformCondition(
7677         S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7678         S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7679                          : Sema::ConditionKind::Boolean);
7680     if (Cond.isInvalid())
7681       return StmtError();
7682   }
7683 
7684   // If this is a constexpr if, determine which arm we should instantiate.
7685   std::optional<bool> ConstexprConditionValue;
7686   if (S->isConstexpr())
7687     ConstexprConditionValue = Cond.getKnownValue();
7688 
7689   // Transform the "then" branch.
7690   StmtResult Then;
7691   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7692     Then = getDerived().TransformStmt(S->getThen());
7693     if (Then.isInvalid())
7694       return StmtError();
7695   } else {
7696     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7697   }
7698 
7699   // Transform the "else" branch.
7700   StmtResult Else;
7701   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7702     Else = getDerived().TransformStmt(S->getElse());
7703     if (Else.isInvalid())
7704       return StmtError();
7705   }
7706 
7707   if (!getDerived().AlwaysRebuild() &&
7708       Init.get() == S->getInit() &&
7709       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7710       Then.get() == S->getThen() &&
7711       Else.get() == S->getElse())
7712     return S;
7713 
7714   return getDerived().RebuildIfStmt(
7715       S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7716       S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7717 }
7718 
7719 template<typename Derived>
7720 StmtResult
7721 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7722   // Transform the initialization statement
7723   StmtResult Init = getDerived().TransformStmt(S->getInit());
7724   if (Init.isInvalid())
7725     return StmtError();
7726 
7727   // Transform the condition.
7728   Sema::ConditionResult Cond = getDerived().TransformCondition(
7729       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7730       Sema::ConditionKind::Switch);
7731   if (Cond.isInvalid())
7732     return StmtError();
7733 
7734   // Rebuild the switch statement.
7735   StmtResult Switch =
7736       getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7737                                           Init.get(), Cond, S->getRParenLoc());
7738   if (Switch.isInvalid())
7739     return StmtError();
7740 
7741   // Transform the body of the switch statement.
7742   StmtResult Body = getDerived().TransformStmt(S->getBody());
7743   if (Body.isInvalid())
7744     return StmtError();
7745 
7746   // Complete the switch statement.
7747   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7748                                             Body.get());
7749 }
7750 
7751 template<typename Derived>
7752 StmtResult
7753 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7754   // Transform the condition
7755   Sema::ConditionResult Cond = getDerived().TransformCondition(
7756       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7757       Sema::ConditionKind::Boolean);
7758   if (Cond.isInvalid())
7759     return StmtError();
7760 
7761   // Transform the body
7762   StmtResult Body = getDerived().TransformStmt(S->getBody());
7763   if (Body.isInvalid())
7764     return StmtError();
7765 
7766   if (!getDerived().AlwaysRebuild() &&
7767       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7768       Body.get() == S->getBody())
7769     return Owned(S);
7770 
7771   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7772                                        Cond, S->getRParenLoc(), Body.get());
7773 }
7774 
7775 template<typename Derived>
7776 StmtResult
7777 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7778   // Transform the body
7779   StmtResult Body = getDerived().TransformStmt(S->getBody());
7780   if (Body.isInvalid())
7781     return StmtError();
7782 
7783   // Transform the condition
7784   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7785   if (Cond.isInvalid())
7786     return StmtError();
7787 
7788   if (!getDerived().AlwaysRebuild() &&
7789       Cond.get() == S->getCond() &&
7790       Body.get() == S->getBody())
7791     return S;
7792 
7793   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7794                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7795                                     S->getRParenLoc());
7796 }
7797 
7798 template<typename Derived>
7799 StmtResult
7800 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7801   if (getSema().getLangOpts().OpenMP)
7802     getSema().startOpenMPLoop();
7803 
7804   // Transform the initialization statement
7805   StmtResult Init = getDerived().TransformStmt(S->getInit());
7806   if (Init.isInvalid())
7807     return StmtError();
7808 
7809   // In OpenMP loop region loop control variable must be captured and be
7810   // private. Perform analysis of first part (if any).
7811   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7812     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7813 
7814   // Transform the condition
7815   Sema::ConditionResult Cond = getDerived().TransformCondition(
7816       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7817       Sema::ConditionKind::Boolean);
7818   if (Cond.isInvalid())
7819     return StmtError();
7820 
7821   // Transform the increment
7822   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7823   if (Inc.isInvalid())
7824     return StmtError();
7825 
7826   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7827   if (S->getInc() && !FullInc.get())
7828     return StmtError();
7829 
7830   // Transform the body
7831   StmtResult Body = getDerived().TransformStmt(S->getBody());
7832   if (Body.isInvalid())
7833     return StmtError();
7834 
7835   if (!getDerived().AlwaysRebuild() &&
7836       Init.get() == S->getInit() &&
7837       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7838       Inc.get() == S->getInc() &&
7839       Body.get() == S->getBody())
7840     return S;
7841 
7842   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7843                                      Init.get(), Cond, FullInc,
7844                                      S->getRParenLoc(), Body.get());
7845 }
7846 
7847 template<typename Derived>
7848 StmtResult
7849 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7850   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7851                                         S->getLabel());
7852   if (!LD)
7853     return StmtError();
7854 
7855   // Goto statements must always be rebuilt, to resolve the label.
7856   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7857                                       cast<LabelDecl>(LD));
7858 }
7859 
7860 template<typename Derived>
7861 StmtResult
7862 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7863   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7864   if (Target.isInvalid())
7865     return StmtError();
7866   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7867 
7868   if (!getDerived().AlwaysRebuild() &&
7869       Target.get() == S->getTarget())
7870     return S;
7871 
7872   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7873                                               Target.get());
7874 }
7875 
7876 template<typename Derived>
7877 StmtResult
7878 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7879   return S;
7880 }
7881 
7882 template<typename Derived>
7883 StmtResult
7884 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7885   return S;
7886 }
7887 
7888 template<typename Derived>
7889 StmtResult
7890 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7891   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7892                                                         /*NotCopyInit*/false);
7893   if (Result.isInvalid())
7894     return StmtError();
7895 
7896   // FIXME: We always rebuild the return statement because there is no way
7897   // to tell whether the return type of the function has changed.
7898   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7899 }
7900 
7901 template<typename Derived>
7902 StmtResult
7903 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7904   bool DeclChanged = false;
7905   SmallVector<Decl *, 4> Decls;
7906   for (auto *D : S->decls()) {
7907     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7908     if (!Transformed)
7909       return StmtError();
7910 
7911     if (Transformed != D)
7912       DeclChanged = true;
7913 
7914     Decls.push_back(Transformed);
7915   }
7916 
7917   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7918     return S;
7919 
7920   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7921 }
7922 
7923 template<typename Derived>
7924 StmtResult
7925 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7926 
7927   SmallVector<Expr*, 8> Constraints;
7928   SmallVector<Expr*, 8> Exprs;
7929   SmallVector<IdentifierInfo *, 4> Names;
7930 
7931   ExprResult AsmString;
7932   SmallVector<Expr*, 8> Clobbers;
7933 
7934   bool ExprsChanged = false;
7935 
7936   // Go through the outputs.
7937   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7938     Names.push_back(S->getOutputIdentifier(I));
7939 
7940     // No need to transform the constraint literal.
7941     Constraints.push_back(S->getOutputConstraintLiteral(I));
7942 
7943     // Transform the output expr.
7944     Expr *OutputExpr = S->getOutputExpr(I);
7945     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7946     if (Result.isInvalid())
7947       return StmtError();
7948 
7949     ExprsChanged |= Result.get() != OutputExpr;
7950 
7951     Exprs.push_back(Result.get());
7952   }
7953 
7954   // Go through the inputs.
7955   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7956     Names.push_back(S->getInputIdentifier(I));
7957 
7958     // No need to transform the constraint literal.
7959     Constraints.push_back(S->getInputConstraintLiteral(I));
7960 
7961     // Transform the input expr.
7962     Expr *InputExpr = S->getInputExpr(I);
7963     ExprResult Result = getDerived().TransformExpr(InputExpr);
7964     if (Result.isInvalid())
7965       return StmtError();
7966 
7967     ExprsChanged |= Result.get() != InputExpr;
7968 
7969     Exprs.push_back(Result.get());
7970   }
7971 
7972   // Go through the Labels.
7973   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7974     Names.push_back(S->getLabelIdentifier(I));
7975 
7976     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7977     if (Result.isInvalid())
7978       return StmtError();
7979     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7980     Exprs.push_back(Result.get());
7981   }
7982   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7983     return S;
7984 
7985   // Go through the clobbers.
7986   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7987     Clobbers.push_back(S->getClobberStringLiteral(I));
7988 
7989   // No need to transform the asm string literal.
7990   AsmString = S->getAsmString();
7991   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7992                                         S->isVolatile(), S->getNumOutputs(),
7993                                         S->getNumInputs(), Names.data(),
7994                                         Constraints, Exprs, AsmString.get(),
7995                                         Clobbers, S->getNumLabels(),
7996                                         S->getRParenLoc());
7997 }
7998 
7999 template<typename Derived>
8000 StmtResult
8001 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
8002   ArrayRef<Token> AsmToks = llvm::ArrayRef(S->getAsmToks(), S->getNumAsmToks());
8003 
8004   bool HadError = false, HadChange = false;
8005 
8006   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
8007   SmallVector<Expr*, 8> TransformedExprs;
8008   TransformedExprs.reserve(SrcExprs.size());
8009   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
8010     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
8011     if (!Result.isUsable()) {
8012       HadError = true;
8013     } else {
8014       HadChange |= (Result.get() != SrcExprs[i]);
8015       TransformedExprs.push_back(Result.get());
8016     }
8017   }
8018 
8019   if (HadError) return StmtError();
8020   if (!HadChange && !getDerived().AlwaysRebuild())
8021     return Owned(S);
8022 
8023   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
8024                                        AsmToks, S->getAsmString(),
8025                                        S->getNumOutputs(), S->getNumInputs(),
8026                                        S->getAllConstraints(), S->getClobbers(),
8027                                        TransformedExprs, S->getEndLoc());
8028 }
8029 
8030 // C++ Coroutines
8031 template<typename Derived>
8032 StmtResult
8033 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
8034   auto *ScopeInfo = SemaRef.getCurFunction();
8035   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
8036   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
8037          ScopeInfo->NeedsCoroutineSuspends &&
8038          ScopeInfo->CoroutineSuspends.first == nullptr &&
8039          ScopeInfo->CoroutineSuspends.second == nullptr &&
8040          "expected clean scope info");
8041 
8042   // Set that we have (possibly-invalid) suspend points before we do anything
8043   // that may fail.
8044   ScopeInfo->setNeedsCoroutineSuspends(false);
8045 
8046   // We re-build the coroutine promise object (and the coroutine parameters its
8047   // type and constructor depend on) based on the types used in our current
8048   // function. We must do so, and set it on the current FunctionScopeInfo,
8049   // before attempting to transform the other parts of the coroutine body
8050   // statement, such as the implicit suspend statements (because those
8051   // statements reference the FunctionScopeInfo::CoroutinePromise).
8052   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
8053     return StmtError();
8054   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
8055   if (!Promise)
8056     return StmtError();
8057   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
8058   ScopeInfo->CoroutinePromise = Promise;
8059 
8060   // Transform the implicit coroutine statements constructed using dependent
8061   // types during the previous parse: initial and final suspensions, the return
8062   // object, and others. We also transform the coroutine function's body.
8063   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
8064   if (InitSuspend.isInvalid())
8065     return StmtError();
8066   StmtResult FinalSuspend =
8067       getDerived().TransformStmt(S->getFinalSuspendStmt());
8068   if (FinalSuspend.isInvalid() ||
8069       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
8070     return StmtError();
8071   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
8072   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
8073 
8074   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
8075   if (BodyRes.isInvalid())
8076     return StmtError();
8077 
8078   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
8079   if (Builder.isInvalid())
8080     return StmtError();
8081 
8082   Expr *ReturnObject = S->getReturnValueInit();
8083   assert(ReturnObject && "the return object is expected to be valid");
8084   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
8085                                                      /*NoCopyInit*/ false);
8086   if (Res.isInvalid())
8087     return StmtError();
8088   Builder.ReturnValue = Res.get();
8089 
8090   // If during the previous parse the coroutine still had a dependent promise
8091   // statement, we may need to build some implicit coroutine statements
8092   // (such as exception and fallthrough handlers) for the first time.
8093   if (S->hasDependentPromiseType()) {
8094     // We can only build these statements, however, if the current promise type
8095     // is not dependent.
8096     if (!Promise->getType()->isDependentType()) {
8097       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
8098              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
8099              "these nodes should not have been built yet");
8100       if (!Builder.buildDependentStatements())
8101         return StmtError();
8102     }
8103   } else {
8104     if (auto *OnFallthrough = S->getFallthroughHandler()) {
8105       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
8106       if (Res.isInvalid())
8107         return StmtError();
8108       Builder.OnFallthrough = Res.get();
8109     }
8110 
8111     if (auto *OnException = S->getExceptionHandler()) {
8112       StmtResult Res = getDerived().TransformStmt(OnException);
8113       if (Res.isInvalid())
8114         return StmtError();
8115       Builder.OnException = Res.get();
8116     }
8117 
8118     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
8119       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
8120       if (Res.isInvalid())
8121         return StmtError();
8122       Builder.ReturnStmtOnAllocFailure = Res.get();
8123     }
8124 
8125     // Transform any additional statements we may have already built
8126     assert(S->getAllocate() && S->getDeallocate() &&
8127            "allocation and deallocation calls must already be built");
8128     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
8129     if (AllocRes.isInvalid())
8130       return StmtError();
8131     Builder.Allocate = AllocRes.get();
8132 
8133     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
8134     if (DeallocRes.isInvalid())
8135       return StmtError();
8136     Builder.Deallocate = DeallocRes.get();
8137 
8138     if (auto *ResultDecl = S->getResultDecl()) {
8139       StmtResult Res = getDerived().TransformStmt(ResultDecl);
8140       if (Res.isInvalid())
8141         return StmtError();
8142       Builder.ResultDecl = Res.get();
8143     }
8144 
8145     if (auto *ReturnStmt = S->getReturnStmt()) {
8146       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
8147       if (Res.isInvalid())
8148         return StmtError();
8149       Builder.ReturnStmt = Res.get();
8150     }
8151   }
8152 
8153   return getDerived().RebuildCoroutineBodyStmt(Builder);
8154 }
8155 
8156 template<typename Derived>
8157 StmtResult
8158 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
8159   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
8160                                                         /*NotCopyInit*/false);
8161   if (Result.isInvalid())
8162     return StmtError();
8163 
8164   // Always rebuild; we don't know if this needs to be injected into a new
8165   // context or if the promise type has changed.
8166   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
8167                                           S->isImplicit());
8168 }
8169 
8170 template <typename Derived>
8171 ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
8172   ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
8173                                                          /*NotCopyInit*/ false);
8174   if (Operand.isInvalid())
8175     return ExprError();
8176 
8177   // Rebuild the common-expr from the operand rather than transforming it
8178   // separately.
8179 
8180   // FIXME: getCurScope() should not be used during template instantiation.
8181   // We should pick up the set of unqualified lookup results for operator
8182   // co_await during the initial parse.
8183   ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
8184       getSema().getCurScope(), E->getKeywordLoc());
8185 
8186   // Always rebuild; we don't know if this needs to be injected into a new
8187   // context or if the promise type has changed.
8188   return getDerived().RebuildCoawaitExpr(
8189       E->getKeywordLoc(), Operand.get(),
8190       cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
8191 }
8192 
8193 template <typename Derived>
8194 ExprResult
8195 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
8196   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
8197                                                         /*NotCopyInit*/ false);
8198   if (OperandResult.isInvalid())
8199     return ExprError();
8200 
8201   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
8202           E->getOperatorCoawaitLookup());
8203 
8204   if (LookupResult.isInvalid())
8205     return ExprError();
8206 
8207   // Always rebuild; we don't know if this needs to be injected into a new
8208   // context or if the promise type has changed.
8209   return getDerived().RebuildDependentCoawaitExpr(
8210       E->getKeywordLoc(), OperandResult.get(),
8211       cast<UnresolvedLookupExpr>(LookupResult.get()));
8212 }
8213 
8214 template<typename Derived>
8215 ExprResult
8216 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8217   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8218                                                         /*NotCopyInit*/false);
8219   if (Result.isInvalid())
8220     return ExprError();
8221 
8222   // Always rebuild; we don't know if this needs to be injected into a new
8223   // context or if the promise type has changed.
8224   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8225 }
8226 
8227 // Objective-C Statements.
8228 
8229 template<typename Derived>
8230 StmtResult
8231 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8232   // Transform the body of the @try.
8233   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8234   if (TryBody.isInvalid())
8235     return StmtError();
8236 
8237   // Transform the @catch statements (if present).
8238   bool AnyCatchChanged = false;
8239   SmallVector<Stmt*, 8> CatchStmts;
8240   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8241     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8242     if (Catch.isInvalid())
8243       return StmtError();
8244     if (Catch.get() != S->getCatchStmt(I))
8245       AnyCatchChanged = true;
8246     CatchStmts.push_back(Catch.get());
8247   }
8248 
8249   // Transform the @finally statement (if present).
8250   StmtResult Finally;
8251   if (S->getFinallyStmt()) {
8252     Finally = getDerived().TransformStmt(S->getFinallyStmt());
8253     if (Finally.isInvalid())
8254       return StmtError();
8255   }
8256 
8257   // If nothing changed, just retain this statement.
8258   if (!getDerived().AlwaysRebuild() &&
8259       TryBody.get() == S->getTryBody() &&
8260       !AnyCatchChanged &&
8261       Finally.get() == S->getFinallyStmt())
8262     return S;
8263 
8264   // Build a new statement.
8265   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8266                                            CatchStmts, Finally.get());
8267 }
8268 
8269 template<typename Derived>
8270 StmtResult
8271 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8272   // Transform the @catch parameter, if there is one.
8273   VarDecl *Var = nullptr;
8274   if (VarDecl *FromVar = S->getCatchParamDecl()) {
8275     TypeSourceInfo *TSInfo = nullptr;
8276     if (FromVar->getTypeSourceInfo()) {
8277       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8278       if (!TSInfo)
8279         return StmtError();
8280     }
8281 
8282     QualType T;
8283     if (TSInfo)
8284       T = TSInfo->getType();
8285     else {
8286       T = getDerived().TransformType(FromVar->getType());
8287       if (T.isNull())
8288         return StmtError();
8289     }
8290 
8291     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8292     if (!Var)
8293       return StmtError();
8294   }
8295 
8296   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8297   if (Body.isInvalid())
8298     return StmtError();
8299 
8300   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8301                                              S->getRParenLoc(),
8302                                              Var, Body.get());
8303 }
8304 
8305 template<typename Derived>
8306 StmtResult
8307 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8308   // Transform the body.
8309   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8310   if (Body.isInvalid())
8311     return StmtError();
8312 
8313   // If nothing changed, just retain this statement.
8314   if (!getDerived().AlwaysRebuild() &&
8315       Body.get() == S->getFinallyBody())
8316     return S;
8317 
8318   // Build a new statement.
8319   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8320                                                Body.get());
8321 }
8322 
8323 template<typename Derived>
8324 StmtResult
8325 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8326   ExprResult Operand;
8327   if (S->getThrowExpr()) {
8328     Operand = getDerived().TransformExpr(S->getThrowExpr());
8329     if (Operand.isInvalid())
8330       return StmtError();
8331   }
8332 
8333   if (!getDerived().AlwaysRebuild() &&
8334       Operand.get() == S->getThrowExpr())
8335     return S;
8336 
8337   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8338 }
8339 
8340 template<typename Derived>
8341 StmtResult
8342 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8343                                                   ObjCAtSynchronizedStmt *S) {
8344   // Transform the object we are locking.
8345   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8346   if (Object.isInvalid())
8347     return StmtError();
8348   Object =
8349     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8350                                                   Object.get());
8351   if (Object.isInvalid())
8352     return StmtError();
8353 
8354   // Transform the body.
8355   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8356   if (Body.isInvalid())
8357     return StmtError();
8358 
8359   // If nothing change, just retain the current statement.
8360   if (!getDerived().AlwaysRebuild() &&
8361       Object.get() == S->getSynchExpr() &&
8362       Body.get() == S->getSynchBody())
8363     return S;
8364 
8365   // Build a new statement.
8366   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8367                                                     Object.get(), Body.get());
8368 }
8369 
8370 template<typename Derived>
8371 StmtResult
8372 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8373                                               ObjCAutoreleasePoolStmt *S) {
8374   // Transform the body.
8375   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8376   if (Body.isInvalid())
8377     return StmtError();
8378 
8379   // If nothing changed, just retain this statement.
8380   if (!getDerived().AlwaysRebuild() &&
8381       Body.get() == S->getSubStmt())
8382     return S;
8383 
8384   // Build a new statement.
8385   return getDerived().RebuildObjCAutoreleasePoolStmt(
8386                         S->getAtLoc(), Body.get());
8387 }
8388 
8389 template<typename Derived>
8390 StmtResult
8391 TreeTransform<Derived>::TransformObjCForCollectionStmt(
8392                                                   ObjCForCollectionStmt *S) {
8393   // Transform the element statement.
8394   StmtResult Element =
8395       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8396   if (Element.isInvalid())
8397     return StmtError();
8398 
8399   // Transform the collection expression.
8400   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8401   if (Collection.isInvalid())
8402     return StmtError();
8403 
8404   // Transform the body.
8405   StmtResult Body = getDerived().TransformStmt(S->getBody());
8406   if (Body.isInvalid())
8407     return StmtError();
8408 
8409   // If nothing changed, just retain this statement.
8410   if (!getDerived().AlwaysRebuild() &&
8411       Element.get() == S->getElement() &&
8412       Collection.get() == S->getCollection() &&
8413       Body.get() == S->getBody())
8414     return S;
8415 
8416   // Build a new statement.
8417   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8418                                                    Element.get(),
8419                                                    Collection.get(),
8420                                                    S->getRParenLoc(),
8421                                                    Body.get());
8422 }
8423 
8424 template <typename Derived>
8425 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8426   // Transform the exception declaration, if any.
8427   VarDecl *Var = nullptr;
8428   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8429     TypeSourceInfo *T =
8430         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8431     if (!T)
8432       return StmtError();
8433 
8434     Var = getDerived().RebuildExceptionDecl(
8435         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8436         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8437     if (!Var || Var->isInvalidDecl())
8438       return StmtError();
8439   }
8440 
8441   // Transform the actual exception handler.
8442   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8443   if (Handler.isInvalid())
8444     return StmtError();
8445 
8446   if (!getDerived().AlwaysRebuild() && !Var &&
8447       Handler.get() == S->getHandlerBlock())
8448     return S;
8449 
8450   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8451 }
8452 
8453 template <typename Derived>
8454 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8455   // Transform the try block itself.
8456   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8457   if (TryBlock.isInvalid())
8458     return StmtError();
8459 
8460   // Transform the handlers.
8461   bool HandlerChanged = false;
8462   SmallVector<Stmt *, 8> Handlers;
8463   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8464     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8465     if (Handler.isInvalid())
8466       return StmtError();
8467 
8468     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8469     Handlers.push_back(Handler.getAs<Stmt>());
8470   }
8471 
8472   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8473       !HandlerChanged)
8474     return S;
8475 
8476   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8477                                         Handlers);
8478 }
8479 
8480 template<typename Derived>
8481 StmtResult
8482 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8483   StmtResult Init =
8484       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8485   if (Init.isInvalid())
8486     return StmtError();
8487 
8488   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8489   if (Range.isInvalid())
8490     return StmtError();
8491 
8492   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8493   if (Begin.isInvalid())
8494     return StmtError();
8495   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8496   if (End.isInvalid())
8497     return StmtError();
8498 
8499   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8500   if (Cond.isInvalid())
8501     return StmtError();
8502   if (Cond.get())
8503     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8504   if (Cond.isInvalid())
8505     return StmtError();
8506   if (Cond.get())
8507     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8508 
8509   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8510   if (Inc.isInvalid())
8511     return StmtError();
8512   if (Inc.get())
8513     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8514 
8515   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8516   if (LoopVar.isInvalid())
8517     return StmtError();
8518 
8519   StmtResult NewStmt = S;
8520   if (getDerived().AlwaysRebuild() ||
8521       Init.get() != S->getInit() ||
8522       Range.get() != S->getRangeStmt() ||
8523       Begin.get() != S->getBeginStmt() ||
8524       End.get() != S->getEndStmt() ||
8525       Cond.get() != S->getCond() ||
8526       Inc.get() != S->getInc() ||
8527       LoopVar.get() != S->getLoopVarStmt()) {
8528     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8529                                                   S->getCoawaitLoc(), Init.get(),
8530                                                   S->getColonLoc(), Range.get(),
8531                                                   Begin.get(), End.get(),
8532                                                   Cond.get(),
8533                                                   Inc.get(), LoopVar.get(),
8534                                                   S->getRParenLoc());
8535     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8536       // Might not have attached any initializer to the loop variable.
8537       getSema().ActOnInitializerError(
8538           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8539       return StmtError();
8540     }
8541   }
8542 
8543   StmtResult Body = getDerived().TransformStmt(S->getBody());
8544   if (Body.isInvalid())
8545     return StmtError();
8546 
8547   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8548   // it now so we have a new statement to attach the body to.
8549   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8550     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8551                                                   S->getCoawaitLoc(), Init.get(),
8552                                                   S->getColonLoc(), Range.get(),
8553                                                   Begin.get(), End.get(),
8554                                                   Cond.get(),
8555                                                   Inc.get(), LoopVar.get(),
8556                                                   S->getRParenLoc());
8557     if (NewStmt.isInvalid())
8558       return StmtError();
8559   }
8560 
8561   if (NewStmt.get() == S)
8562     return S;
8563 
8564   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8565 }
8566 
8567 template<typename Derived>
8568 StmtResult
8569 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8570                                                     MSDependentExistsStmt *S) {
8571   // Transform the nested-name-specifier, if any.
8572   NestedNameSpecifierLoc QualifierLoc;
8573   if (S->getQualifierLoc()) {
8574     QualifierLoc
8575       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8576     if (!QualifierLoc)
8577       return StmtError();
8578   }
8579 
8580   // Transform the declaration name.
8581   DeclarationNameInfo NameInfo = S->getNameInfo();
8582   if (NameInfo.getName()) {
8583     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8584     if (!NameInfo.getName())
8585       return StmtError();
8586   }
8587 
8588   // Check whether anything changed.
8589   if (!getDerived().AlwaysRebuild() &&
8590       QualifierLoc == S->getQualifierLoc() &&
8591       NameInfo.getName() == S->getNameInfo().getName())
8592     return S;
8593 
8594   // Determine whether this name exists, if we can.
8595   CXXScopeSpec SS;
8596   SS.Adopt(QualifierLoc);
8597   bool Dependent = false;
8598   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8599   case Sema::IER_Exists:
8600     if (S->isIfExists())
8601       break;
8602 
8603     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8604 
8605   case Sema::IER_DoesNotExist:
8606     if (S->isIfNotExists())
8607       break;
8608 
8609     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8610 
8611   case Sema::IER_Dependent:
8612     Dependent = true;
8613     break;
8614 
8615   case Sema::IER_Error:
8616     return StmtError();
8617   }
8618 
8619   // We need to continue with the instantiation, so do so now.
8620   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8621   if (SubStmt.isInvalid())
8622     return StmtError();
8623 
8624   // If we have resolved the name, just transform to the substatement.
8625   if (!Dependent)
8626     return SubStmt;
8627 
8628   // The name is still dependent, so build a dependent expression again.
8629   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8630                                                    S->isIfExists(),
8631                                                    QualifierLoc,
8632                                                    NameInfo,
8633                                                    SubStmt.get());
8634 }
8635 
8636 template<typename Derived>
8637 ExprResult
8638 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8639   NestedNameSpecifierLoc QualifierLoc;
8640   if (E->getQualifierLoc()) {
8641     QualifierLoc
8642     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8643     if (!QualifierLoc)
8644       return ExprError();
8645   }
8646 
8647   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8648     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8649   if (!PD)
8650     return ExprError();
8651 
8652   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8653   if (Base.isInvalid())
8654     return ExprError();
8655 
8656   return new (SemaRef.getASTContext())
8657       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8658                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8659                         QualifierLoc, E->getMemberLoc());
8660 }
8661 
8662 template <typename Derived>
8663 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8664     MSPropertySubscriptExpr *E) {
8665   auto BaseRes = getDerived().TransformExpr(E->getBase());
8666   if (BaseRes.isInvalid())
8667     return ExprError();
8668   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8669   if (IdxRes.isInvalid())
8670     return ExprError();
8671 
8672   if (!getDerived().AlwaysRebuild() &&
8673       BaseRes.get() == E->getBase() &&
8674       IdxRes.get() == E->getIdx())
8675     return E;
8676 
8677   return getDerived().RebuildArraySubscriptExpr(
8678       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8679 }
8680 
8681 template <typename Derived>
8682 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8683   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8684   if (TryBlock.isInvalid())
8685     return StmtError();
8686 
8687   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8688   if (Handler.isInvalid())
8689     return StmtError();
8690 
8691   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8692       Handler.get() == S->getHandler())
8693     return S;
8694 
8695   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8696                                         TryBlock.get(), Handler.get());
8697 }
8698 
8699 template <typename Derived>
8700 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8701   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8702   if (Block.isInvalid())
8703     return StmtError();
8704 
8705   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8706 }
8707 
8708 template <typename Derived>
8709 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8710   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8711   if (FilterExpr.isInvalid())
8712     return StmtError();
8713 
8714   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8715   if (Block.isInvalid())
8716     return StmtError();
8717 
8718   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8719                                            Block.get());
8720 }
8721 
8722 template <typename Derived>
8723 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8724   if (isa<SEHFinallyStmt>(Handler))
8725     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8726   else
8727     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8728 }
8729 
8730 template<typename Derived>
8731 StmtResult
8732 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8733   return S;
8734 }
8735 
8736 //===----------------------------------------------------------------------===//
8737 // OpenMP directive transformation
8738 //===----------------------------------------------------------------------===//
8739 
8740 template <typename Derived>
8741 StmtResult
8742 TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8743   // OMPCanonicalLoops are eliminated during transformation, since they will be
8744   // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8745   // after transformation.
8746   return getDerived().TransformStmt(L->getLoopStmt());
8747 }
8748 
8749 template <typename Derived>
8750 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8751     OMPExecutableDirective *D) {
8752 
8753   // Transform the clauses
8754   llvm::SmallVector<OMPClause *, 16> TClauses;
8755   ArrayRef<OMPClause *> Clauses = D->clauses();
8756   TClauses.reserve(Clauses.size());
8757   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8758        I != E; ++I) {
8759     if (*I) {
8760       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8761       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8762       getDerived().getSema().EndOpenMPClause();
8763       if (Clause)
8764         TClauses.push_back(Clause);
8765     } else {
8766       TClauses.push_back(nullptr);
8767     }
8768   }
8769   StmtResult AssociatedStmt;
8770   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8771     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8772                                                   /*CurScope=*/nullptr);
8773     StmtResult Body;
8774     {
8775       Sema::CompoundScopeRAII CompoundScope(getSema());
8776       Stmt *CS;
8777       if (D->getDirectiveKind() == OMPD_atomic ||
8778           D->getDirectiveKind() == OMPD_critical ||
8779           D->getDirectiveKind() == OMPD_section ||
8780           D->getDirectiveKind() == OMPD_master)
8781         CS = D->getAssociatedStmt();
8782       else
8783         CS = D->getRawStmt();
8784       Body = getDerived().TransformStmt(CS);
8785       if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8786           getSema().getLangOpts().OpenMPIRBuilder)
8787         Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8788     }
8789     AssociatedStmt =
8790         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8791     if (AssociatedStmt.isInvalid()) {
8792       return StmtError();
8793     }
8794   }
8795   if (TClauses.size() != Clauses.size()) {
8796     return StmtError();
8797   }
8798 
8799   // Transform directive name for 'omp critical' directive.
8800   DeclarationNameInfo DirName;
8801   if (D->getDirectiveKind() == OMPD_critical) {
8802     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8803     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8804   }
8805   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8806   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8807     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8808   } else if (D->getDirectiveKind() == OMPD_cancel) {
8809     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8810   }
8811 
8812   return getDerived().RebuildOMPExecutableDirective(
8813       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8814       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8815 }
8816 
8817 template <typename Derived>
8818 StmtResult
8819 TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8820   // TODO: Fix This
8821   SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8822       << getOpenMPDirectiveName(D->getDirectiveKind());
8823   return StmtError();
8824 }
8825 
8826 template <typename Derived>
8827 StmtResult
8828 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8829   DeclarationNameInfo DirName;
8830   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8831                                              D->getBeginLoc());
8832   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8833   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8834   return Res;
8835 }
8836 
8837 template <typename Derived>
8838 StmtResult
8839 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8840   DeclarationNameInfo DirName;
8841   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8842                                              D->getBeginLoc());
8843   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8844   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8845   return Res;
8846 }
8847 
8848 template <typename Derived>
8849 StmtResult
8850 TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8851   DeclarationNameInfo DirName;
8852   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8853                                              nullptr, D->getBeginLoc());
8854   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8855   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8856   return Res;
8857 }
8858 
8859 template <typename Derived>
8860 StmtResult
8861 TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8862   DeclarationNameInfo DirName;
8863   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8864                                              nullptr, D->getBeginLoc());
8865   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8866   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8867   return Res;
8868 }
8869 
8870 template <typename Derived>
8871 StmtResult
8872 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8873   DeclarationNameInfo DirName;
8874   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8875                                              D->getBeginLoc());
8876   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8877   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8878   return Res;
8879 }
8880 
8881 template <typename Derived>
8882 StmtResult
8883 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8884   DeclarationNameInfo DirName;
8885   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8886                                              D->getBeginLoc());
8887   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8888   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8889   return Res;
8890 }
8891 
8892 template <typename Derived>
8893 StmtResult
8894 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8895   DeclarationNameInfo DirName;
8896   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8897                                              D->getBeginLoc());
8898   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8899   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8900   return Res;
8901 }
8902 
8903 template <typename Derived>
8904 StmtResult
8905 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8906   DeclarationNameInfo DirName;
8907   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8908                                              D->getBeginLoc());
8909   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8910   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8911   return Res;
8912 }
8913 
8914 template <typename Derived>
8915 StmtResult
8916 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8917   DeclarationNameInfo DirName;
8918   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8919                                              D->getBeginLoc());
8920   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8921   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8922   return Res;
8923 }
8924 
8925 template <typename Derived>
8926 StmtResult
8927 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8928   DeclarationNameInfo DirName;
8929   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8930                                              D->getBeginLoc());
8931   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8932   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8933   return Res;
8934 }
8935 
8936 template <typename Derived>
8937 StmtResult
8938 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8939   getDerived().getSema().StartOpenMPDSABlock(
8940       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8941   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8942   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8943   return Res;
8944 }
8945 
8946 template <typename Derived>
8947 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8948     OMPParallelForDirective *D) {
8949   DeclarationNameInfo DirName;
8950   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8951                                              nullptr, D->getBeginLoc());
8952   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8953   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8954   return Res;
8955 }
8956 
8957 template <typename Derived>
8958 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8959     OMPParallelForSimdDirective *D) {
8960   DeclarationNameInfo DirName;
8961   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8962                                              nullptr, D->getBeginLoc());
8963   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8964   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8965   return Res;
8966 }
8967 
8968 template <typename Derived>
8969 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8970     OMPParallelMasterDirective *D) {
8971   DeclarationNameInfo DirName;
8972   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8973                                              nullptr, D->getBeginLoc());
8974   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8975   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8976   return Res;
8977 }
8978 
8979 template <typename Derived>
8980 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
8981     OMPParallelMaskedDirective *D) {
8982   DeclarationNameInfo DirName;
8983   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
8984                                              nullptr, D->getBeginLoc());
8985   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8986   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8987   return Res;
8988 }
8989 
8990 template <typename Derived>
8991 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8992     OMPParallelSectionsDirective *D) {
8993   DeclarationNameInfo DirName;
8994   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8995                                              nullptr, D->getBeginLoc());
8996   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8997   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8998   return Res;
8999 }
9000 
9001 template <typename Derived>
9002 StmtResult
9003 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
9004   DeclarationNameInfo DirName;
9005   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
9006                                              D->getBeginLoc());
9007   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9008   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9009   return Res;
9010 }
9011 
9012 template <typename Derived>
9013 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
9014     OMPTaskyieldDirective *D) {
9015   DeclarationNameInfo DirName;
9016   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
9017                                              D->getBeginLoc());
9018   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9019   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9020   return Res;
9021 }
9022 
9023 template <typename Derived>
9024 StmtResult
9025 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
9026   DeclarationNameInfo DirName;
9027   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
9028                                              D->getBeginLoc());
9029   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9030   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9031   return Res;
9032 }
9033 
9034 template <typename Derived>
9035 StmtResult
9036 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
9037   DeclarationNameInfo DirName;
9038   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
9039                                              D->getBeginLoc());
9040   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9041   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9042   return Res;
9043 }
9044 
9045 template <typename Derived>
9046 StmtResult
9047 TreeTransform<Derived>::TransformOMPErrorDirective(OMPErrorDirective *D) {
9048   DeclarationNameInfo DirName;
9049   getDerived().getSema().StartOpenMPDSABlock(OMPD_error, DirName, nullptr,
9050                                              D->getBeginLoc());
9051   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9052   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9053   return Res;
9054 }
9055 
9056 template <typename Derived>
9057 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
9058     OMPTaskgroupDirective *D) {
9059   DeclarationNameInfo DirName;
9060   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
9061                                              D->getBeginLoc());
9062   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9063   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9064   return Res;
9065 }
9066 
9067 template <typename Derived>
9068 StmtResult
9069 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
9070   DeclarationNameInfo DirName;
9071   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
9072                                              D->getBeginLoc());
9073   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9074   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9075   return Res;
9076 }
9077 
9078 template <typename Derived>
9079 StmtResult
9080 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
9081   DeclarationNameInfo DirName;
9082   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
9083                                              D->getBeginLoc());
9084   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9085   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9086   return Res;
9087 }
9088 
9089 template <typename Derived>
9090 StmtResult
9091 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
9092   DeclarationNameInfo DirName;
9093   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
9094                                              D->getBeginLoc());
9095   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9096   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9097   return Res;
9098 }
9099 
9100 template <typename Derived>
9101 StmtResult
9102 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
9103   DeclarationNameInfo DirName;
9104   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
9105                                              D->getBeginLoc());
9106   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9107   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9108   return Res;
9109 }
9110 
9111 template <typename Derived>
9112 StmtResult
9113 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
9114   DeclarationNameInfo DirName;
9115   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
9116                                              D->getBeginLoc());
9117   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9118   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9119   return Res;
9120 }
9121 
9122 template <typename Derived>
9123 StmtResult
9124 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
9125   DeclarationNameInfo DirName;
9126   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
9127                                              D->getBeginLoc());
9128   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9129   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9130   return Res;
9131 }
9132 
9133 template <typename Derived>
9134 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
9135     OMPTargetDataDirective *D) {
9136   DeclarationNameInfo DirName;
9137   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
9138                                              D->getBeginLoc());
9139   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9140   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9141   return Res;
9142 }
9143 
9144 template <typename Derived>
9145 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
9146     OMPTargetEnterDataDirective *D) {
9147   DeclarationNameInfo DirName;
9148   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
9149                                              nullptr, D->getBeginLoc());
9150   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9151   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9152   return Res;
9153 }
9154 
9155 template <typename Derived>
9156 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
9157     OMPTargetExitDataDirective *D) {
9158   DeclarationNameInfo DirName;
9159   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
9160                                              nullptr, D->getBeginLoc());
9161   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9162   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9163   return Res;
9164 }
9165 
9166 template <typename Derived>
9167 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
9168     OMPTargetParallelDirective *D) {
9169   DeclarationNameInfo DirName;
9170   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
9171                                              nullptr, D->getBeginLoc());
9172   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9173   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9174   return Res;
9175 }
9176 
9177 template <typename Derived>
9178 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
9179     OMPTargetParallelForDirective *D) {
9180   DeclarationNameInfo DirName;
9181   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
9182                                              nullptr, D->getBeginLoc());
9183   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9184   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9185   return Res;
9186 }
9187 
9188 template <typename Derived>
9189 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
9190     OMPTargetUpdateDirective *D) {
9191   DeclarationNameInfo DirName;
9192   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
9193                                              nullptr, D->getBeginLoc());
9194   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9195   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9196   return Res;
9197 }
9198 
9199 template <typename Derived>
9200 StmtResult
9201 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
9202   DeclarationNameInfo DirName;
9203   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
9204                                              D->getBeginLoc());
9205   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9206   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9207   return Res;
9208 }
9209 
9210 template <typename Derived>
9211 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
9212     OMPCancellationPointDirective *D) {
9213   DeclarationNameInfo DirName;
9214   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9215                                              nullptr, D->getBeginLoc());
9216   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9217   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9218   return Res;
9219 }
9220 
9221 template <typename Derived>
9222 StmtResult
9223 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9224   DeclarationNameInfo DirName;
9225   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9226                                              D->getBeginLoc());
9227   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9228   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9229   return Res;
9230 }
9231 
9232 template <typename Derived>
9233 StmtResult
9234 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9235   DeclarationNameInfo DirName;
9236   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9237                                              D->getBeginLoc());
9238   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9239   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9240   return Res;
9241 }
9242 
9243 template <typename Derived>
9244 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9245     OMPTaskLoopSimdDirective *D) {
9246   DeclarationNameInfo DirName;
9247   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9248                                              nullptr, D->getBeginLoc());
9249   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9250   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9251   return Res;
9252 }
9253 
9254 template <typename Derived>
9255 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9256     OMPMasterTaskLoopDirective *D) {
9257   DeclarationNameInfo DirName;
9258   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9259                                              nullptr, D->getBeginLoc());
9260   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9261   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9262   return Res;
9263 }
9264 
9265 template <typename Derived>
9266 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9267     OMPMaskedTaskLoopDirective *D) {
9268   DeclarationNameInfo DirName;
9269   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9270                                              nullptr, D->getBeginLoc());
9271   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9272   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9273   return Res;
9274 }
9275 
9276 template <typename Derived>
9277 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9278     OMPMasterTaskLoopSimdDirective *D) {
9279   DeclarationNameInfo DirName;
9280   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9281                                              nullptr, D->getBeginLoc());
9282   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9283   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9284   return Res;
9285 }
9286 
9287 template <typename Derived>
9288 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9289     OMPMaskedTaskLoopSimdDirective *D) {
9290   DeclarationNameInfo DirName;
9291   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9292                                              nullptr, D->getBeginLoc());
9293   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9294   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9295   return Res;
9296 }
9297 
9298 template <typename Derived>
9299 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9300     OMPParallelMasterTaskLoopDirective *D) {
9301   DeclarationNameInfo DirName;
9302   getDerived().getSema().StartOpenMPDSABlock(
9303       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9304   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9305   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9306   return Res;
9307 }
9308 
9309 template <typename Derived>
9310 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9311     OMPParallelMaskedTaskLoopDirective *D) {
9312   DeclarationNameInfo DirName;
9313   getDerived().getSema().StartOpenMPDSABlock(
9314       OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9315   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9316   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9317   return Res;
9318 }
9319 
9320 template <typename Derived>
9321 StmtResult
9322 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9323     OMPParallelMasterTaskLoopSimdDirective *D) {
9324   DeclarationNameInfo DirName;
9325   getDerived().getSema().StartOpenMPDSABlock(
9326       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9327   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9328   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9329   return Res;
9330 }
9331 
9332 template <typename Derived>
9333 StmtResult
9334 TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9335     OMPParallelMaskedTaskLoopSimdDirective *D) {
9336   DeclarationNameInfo DirName;
9337   getDerived().getSema().StartOpenMPDSABlock(
9338       OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9339   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9340   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9341   return Res;
9342 }
9343 
9344 template <typename Derived>
9345 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9346     OMPDistributeDirective *D) {
9347   DeclarationNameInfo DirName;
9348   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9349                                              D->getBeginLoc());
9350   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9351   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9352   return Res;
9353 }
9354 
9355 template <typename Derived>
9356 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9357     OMPDistributeParallelForDirective *D) {
9358   DeclarationNameInfo DirName;
9359   getDerived().getSema().StartOpenMPDSABlock(
9360       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9361   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9362   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9363   return Res;
9364 }
9365 
9366 template <typename Derived>
9367 StmtResult
9368 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9369     OMPDistributeParallelForSimdDirective *D) {
9370   DeclarationNameInfo DirName;
9371   getDerived().getSema().StartOpenMPDSABlock(
9372       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9373   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9374   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9375   return Res;
9376 }
9377 
9378 template <typename Derived>
9379 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9380     OMPDistributeSimdDirective *D) {
9381   DeclarationNameInfo DirName;
9382   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9383                                              nullptr, D->getBeginLoc());
9384   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9385   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9386   return Res;
9387 }
9388 
9389 template <typename Derived>
9390 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9391     OMPTargetParallelForSimdDirective *D) {
9392   DeclarationNameInfo DirName;
9393   getDerived().getSema().StartOpenMPDSABlock(
9394       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9395   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9396   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9397   return Res;
9398 }
9399 
9400 template <typename Derived>
9401 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9402     OMPTargetSimdDirective *D) {
9403   DeclarationNameInfo DirName;
9404   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9405                                              D->getBeginLoc());
9406   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9407   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9408   return Res;
9409 }
9410 
9411 template <typename Derived>
9412 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9413     OMPTeamsDistributeDirective *D) {
9414   DeclarationNameInfo DirName;
9415   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9416                                              nullptr, D->getBeginLoc());
9417   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9418   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9419   return Res;
9420 }
9421 
9422 template <typename Derived>
9423 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9424     OMPTeamsDistributeSimdDirective *D) {
9425   DeclarationNameInfo DirName;
9426   getDerived().getSema().StartOpenMPDSABlock(
9427       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9428   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9429   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9430   return Res;
9431 }
9432 
9433 template <typename Derived>
9434 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9435     OMPTeamsDistributeParallelForSimdDirective *D) {
9436   DeclarationNameInfo DirName;
9437   getDerived().getSema().StartOpenMPDSABlock(
9438       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9439       D->getBeginLoc());
9440   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9441   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9442   return Res;
9443 }
9444 
9445 template <typename Derived>
9446 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9447     OMPTeamsDistributeParallelForDirective *D) {
9448   DeclarationNameInfo DirName;
9449   getDerived().getSema().StartOpenMPDSABlock(
9450       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9451   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9452   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9453   return Res;
9454 }
9455 
9456 template <typename Derived>
9457 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9458     OMPTargetTeamsDirective *D) {
9459   DeclarationNameInfo DirName;
9460   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9461                                              nullptr, D->getBeginLoc());
9462   auto Res = getDerived().TransformOMPExecutableDirective(D);
9463   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9464   return Res;
9465 }
9466 
9467 template <typename Derived>
9468 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9469     OMPTargetTeamsDistributeDirective *D) {
9470   DeclarationNameInfo DirName;
9471   getDerived().getSema().StartOpenMPDSABlock(
9472       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9473   auto Res = getDerived().TransformOMPExecutableDirective(D);
9474   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9475   return Res;
9476 }
9477 
9478 template <typename Derived>
9479 StmtResult
9480 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9481     OMPTargetTeamsDistributeParallelForDirective *D) {
9482   DeclarationNameInfo DirName;
9483   getDerived().getSema().StartOpenMPDSABlock(
9484       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9485       D->getBeginLoc());
9486   auto Res = getDerived().TransformOMPExecutableDirective(D);
9487   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9488   return Res;
9489 }
9490 
9491 template <typename Derived>
9492 StmtResult TreeTransform<Derived>::
9493     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9494         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9495   DeclarationNameInfo DirName;
9496   getDerived().getSema().StartOpenMPDSABlock(
9497       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9498       D->getBeginLoc());
9499   auto Res = getDerived().TransformOMPExecutableDirective(D);
9500   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9501   return Res;
9502 }
9503 
9504 template <typename Derived>
9505 StmtResult
9506 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9507     OMPTargetTeamsDistributeSimdDirective *D) {
9508   DeclarationNameInfo DirName;
9509   getDerived().getSema().StartOpenMPDSABlock(
9510       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9511   auto Res = getDerived().TransformOMPExecutableDirective(D);
9512   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9513   return Res;
9514 }
9515 
9516 template <typename Derived>
9517 StmtResult
9518 TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9519   DeclarationNameInfo DirName;
9520   getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9521                                              D->getBeginLoc());
9522   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9523   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9524   return Res;
9525 }
9526 
9527 template <typename Derived>
9528 StmtResult
9529 TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9530   DeclarationNameInfo DirName;
9531   getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9532                                              D->getBeginLoc());
9533   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9534   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9535   return Res;
9536 }
9537 
9538 template <typename Derived>
9539 StmtResult
9540 TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9541   DeclarationNameInfo DirName;
9542   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9543                                              D->getBeginLoc());
9544   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9545   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9546   return Res;
9547 }
9548 
9549 template <typename Derived>
9550 StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9551     OMPGenericLoopDirective *D) {
9552   DeclarationNameInfo DirName;
9553   getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9554                                              D->getBeginLoc());
9555   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9556   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9557   return Res;
9558 }
9559 
9560 template <typename Derived>
9561 StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9562     OMPTeamsGenericLoopDirective *D) {
9563   DeclarationNameInfo DirName;
9564   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9565                                              D->getBeginLoc());
9566   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9567   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9568   return Res;
9569 }
9570 
9571 template <typename Derived>
9572 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9573     OMPTargetTeamsGenericLoopDirective *D) {
9574   DeclarationNameInfo DirName;
9575   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9576                                              nullptr, D->getBeginLoc());
9577   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9578   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9579   return Res;
9580 }
9581 
9582 template <typename Derived>
9583 StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9584     OMPParallelGenericLoopDirective *D) {
9585   DeclarationNameInfo DirName;
9586   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9587                                              nullptr, D->getBeginLoc());
9588   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9589   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9590   return Res;
9591 }
9592 
9593 template <typename Derived>
9594 StmtResult
9595 TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9596     OMPTargetParallelGenericLoopDirective *D) {
9597   DeclarationNameInfo DirName;
9598   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9599                                              nullptr, D->getBeginLoc());
9600   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9601   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9602   return Res;
9603 }
9604 
9605 //===----------------------------------------------------------------------===//
9606 // OpenMP clause transformation
9607 //===----------------------------------------------------------------------===//
9608 template <typename Derived>
9609 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9610   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9611   if (Cond.isInvalid())
9612     return nullptr;
9613   return getDerived().RebuildOMPIfClause(
9614       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9615       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9616 }
9617 
9618 template <typename Derived>
9619 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9620   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9621   if (Cond.isInvalid())
9622     return nullptr;
9623   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9624                                             C->getLParenLoc(), C->getEndLoc());
9625 }
9626 
9627 template <typename Derived>
9628 OMPClause *
9629 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9630   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9631   if (NumThreads.isInvalid())
9632     return nullptr;
9633   return getDerived().RebuildOMPNumThreadsClause(
9634       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9635 }
9636 
9637 template <typename Derived>
9638 OMPClause *
9639 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9640   ExprResult E = getDerived().TransformExpr(C->getSafelen());
9641   if (E.isInvalid())
9642     return nullptr;
9643   return getDerived().RebuildOMPSafelenClause(
9644       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9645 }
9646 
9647 template <typename Derived>
9648 OMPClause *
9649 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9650   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9651   if (E.isInvalid())
9652     return nullptr;
9653   return getDerived().RebuildOMPAllocatorClause(
9654       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9655 }
9656 
9657 template <typename Derived>
9658 OMPClause *
9659 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9660   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9661   if (E.isInvalid())
9662     return nullptr;
9663   return getDerived().RebuildOMPSimdlenClause(
9664       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9665 }
9666 
9667 template <typename Derived>
9668 OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9669   SmallVector<Expr *, 4> TransformedSizes;
9670   TransformedSizes.reserve(C->getNumSizes());
9671   bool Changed = false;
9672   for (Expr *E : C->getSizesRefs()) {
9673     if (!E) {
9674       TransformedSizes.push_back(nullptr);
9675       continue;
9676     }
9677 
9678     ExprResult T = getDerived().TransformExpr(E);
9679     if (T.isInvalid())
9680       return nullptr;
9681     if (E != T.get())
9682       Changed = true;
9683     TransformedSizes.push_back(T.get());
9684   }
9685 
9686   if (!Changed && !getDerived().AlwaysRebuild())
9687     return C;
9688   return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9689                                C->getLParenLoc(), C->getEndLoc());
9690 }
9691 
9692 template <typename Derived>
9693 OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9694   if (!getDerived().AlwaysRebuild())
9695     return C;
9696   return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9697 }
9698 
9699 template <typename Derived>
9700 OMPClause *
9701 TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9702   ExprResult T = getDerived().TransformExpr(C->getFactor());
9703   if (T.isInvalid())
9704     return nullptr;
9705   Expr *Factor = T.get();
9706   bool Changed = Factor != C->getFactor();
9707 
9708   if (!Changed && !getDerived().AlwaysRebuild())
9709     return C;
9710   return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9711                                  C->getEndLoc());
9712 }
9713 
9714 template <typename Derived>
9715 OMPClause *
9716 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9717   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9718   if (E.isInvalid())
9719     return nullptr;
9720   return getDerived().RebuildOMPCollapseClause(
9721       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9722 }
9723 
9724 template <typename Derived>
9725 OMPClause *
9726 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9727   return getDerived().RebuildOMPDefaultClause(
9728       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9729       C->getLParenLoc(), C->getEndLoc());
9730 }
9731 
9732 template <typename Derived>
9733 OMPClause *
9734 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9735   return getDerived().RebuildOMPProcBindClause(
9736       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9737       C->getLParenLoc(), C->getEndLoc());
9738 }
9739 
9740 template <typename Derived>
9741 OMPClause *
9742 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9743   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9744   if (E.isInvalid())
9745     return nullptr;
9746   return getDerived().RebuildOMPScheduleClause(
9747       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9748       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9749       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9750       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9751 }
9752 
9753 template <typename Derived>
9754 OMPClause *
9755 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9756   ExprResult E;
9757   if (auto *Num = C->getNumForLoops()) {
9758     E = getDerived().TransformExpr(Num);
9759     if (E.isInvalid())
9760       return nullptr;
9761   }
9762   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9763                                               C->getLParenLoc(), E.get());
9764 }
9765 
9766 template <typename Derived>
9767 OMPClause *
9768 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9769   ExprResult E;
9770   if (Expr *Evt = C->getEventHandler()) {
9771     E = getDerived().TransformExpr(Evt);
9772     if (E.isInvalid())
9773       return nullptr;
9774   }
9775   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9776                                              C->getLParenLoc(), C->getEndLoc());
9777 }
9778 
9779 template <typename Derived>
9780 OMPClause *
9781 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9782   // No need to rebuild this clause, no template-dependent parameters.
9783   return C;
9784 }
9785 
9786 template <typename Derived>
9787 OMPClause *
9788 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9789   // No need to rebuild this clause, no template-dependent parameters.
9790   return C;
9791 }
9792 
9793 template <typename Derived>
9794 OMPClause *
9795 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9796   // No need to rebuild this clause, no template-dependent parameters.
9797   return C;
9798 }
9799 
9800 template <typename Derived>
9801 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9802   // No need to rebuild this clause, no template-dependent parameters.
9803   return C;
9804 }
9805 
9806 template <typename Derived>
9807 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9808   // No need to rebuild this clause, no template-dependent parameters.
9809   return C;
9810 }
9811 
9812 template <typename Derived>
9813 OMPClause *
9814 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9815   // No need to rebuild this clause, no template-dependent parameters.
9816   return C;
9817 }
9818 
9819 template <typename Derived>
9820 OMPClause *
9821 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9822   // No need to rebuild this clause, no template-dependent parameters.
9823   return C;
9824 }
9825 
9826 template <typename Derived>
9827 OMPClause *
9828 TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9829   // No need to rebuild this clause, no template-dependent parameters.
9830   return C;
9831 }
9832 
9833 template <typename Derived>
9834 OMPClause *
9835 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9836   // No need to rebuild this clause, no template-dependent parameters.
9837   return C;
9838 }
9839 
9840 template <typename Derived>
9841 OMPClause *
9842 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9843   // No need to rebuild this clause, no template-dependent parameters.
9844   return C;
9845 }
9846 
9847 template <typename Derived>
9848 OMPClause *
9849 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9850   // No need to rebuild this clause, no template-dependent parameters.
9851   return C;
9852 }
9853 
9854 template <typename Derived>
9855 OMPClause *
9856 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9857   // No need to rebuild this clause, no template-dependent parameters.
9858   return C;
9859 }
9860 
9861 template <typename Derived>
9862 OMPClause *
9863 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9864   // No need to rebuild this clause, no template-dependent parameters.
9865   return C;
9866 }
9867 
9868 template <typename Derived>
9869 OMPClause *
9870 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9871   // No need to rebuild this clause, no template-dependent parameters.
9872   return C;
9873 }
9874 
9875 template <typename Derived>
9876 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9877   // No need to rebuild this clause, no template-dependent parameters.
9878   return C;
9879 }
9880 
9881 template <typename Derived>
9882 OMPClause *
9883 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9884   // No need to rebuild this clause, no template-dependent parameters.
9885   return C;
9886 }
9887 
9888 template <typename Derived>
9889 OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9890   ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9891   if (IVR.isInvalid())
9892     return nullptr;
9893 
9894   OMPInteropInfo InteropInfo(C->getIsTarget(), C->getIsTargetSync());
9895   InteropInfo.PreferTypes.reserve(C->varlist_size() - 1);
9896   for (Expr *E : llvm::drop_begin(C->varlists())) {
9897     ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9898     if (ER.isInvalid())
9899       return nullptr;
9900     InteropInfo.PreferTypes.push_back(ER.get());
9901   }
9902   return getDerived().RebuildOMPInitClause(IVR.get(), InteropInfo,
9903                                            C->getBeginLoc(), C->getLParenLoc(),
9904                                            C->getVarLoc(), C->getEndLoc());
9905 }
9906 
9907 template <typename Derived>
9908 OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9909   ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9910   if (ER.isInvalid())
9911     return nullptr;
9912   return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9913                                           C->getLParenLoc(), C->getVarLoc(),
9914                                           C->getEndLoc());
9915 }
9916 
9917 template <typename Derived>
9918 OMPClause *
9919 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9920   ExprResult ER;
9921   if (Expr *IV = C->getInteropVar()) {
9922     ER = getDerived().TransformExpr(IV);
9923     if (ER.isInvalid())
9924       return nullptr;
9925   }
9926   return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9927                                               C->getLParenLoc(), C->getVarLoc(),
9928                                               C->getEndLoc());
9929 }
9930 
9931 template <typename Derived>
9932 OMPClause *
9933 TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9934   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9935   if (Cond.isInvalid())
9936     return nullptr;
9937   return getDerived().RebuildOMPNovariantsClause(
9938       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9939 }
9940 
9941 template <typename Derived>
9942 OMPClause *
9943 TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9944   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9945   if (Cond.isInvalid())
9946     return nullptr;
9947   return getDerived().RebuildOMPNocontextClause(
9948       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9949 }
9950 
9951 template <typename Derived>
9952 OMPClause *
9953 TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9954   ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9955   if (ThreadID.isInvalid())
9956     return nullptr;
9957   return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9958                                              C->getLParenLoc(), C->getEndLoc());
9959 }
9960 
9961 template <typename Derived>
9962 OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9963   ExprResult E = getDerived().TransformExpr(C->getAlignment());
9964   if (E.isInvalid())
9965     return nullptr;
9966   return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9967                                             C->getLParenLoc(), C->getEndLoc());
9968 }
9969 
9970 template <typename Derived>
9971 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9972     OMPUnifiedAddressClause *C) {
9973   llvm_unreachable("unified_address clause cannot appear in dependent context");
9974 }
9975 
9976 template <typename Derived>
9977 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9978     OMPUnifiedSharedMemoryClause *C) {
9979   llvm_unreachable(
9980       "unified_shared_memory clause cannot appear in dependent context");
9981 }
9982 
9983 template <typename Derived>
9984 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9985     OMPReverseOffloadClause *C) {
9986   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
9987 }
9988 
9989 template <typename Derived>
9990 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9991     OMPDynamicAllocatorsClause *C) {
9992   llvm_unreachable(
9993       "dynamic_allocators clause cannot appear in dependent context");
9994 }
9995 
9996 template <typename Derived>
9997 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9998     OMPAtomicDefaultMemOrderClause *C) {
9999   llvm_unreachable(
10000       "atomic_default_mem_order clause cannot appear in dependent context");
10001 }
10002 
10003 template <typename Derived>
10004 OMPClause *TreeTransform<Derived>::TransformOMPAtClause(OMPAtClause *C) {
10005   return getDerived().RebuildOMPAtClause(C->getAtKind(), C->getAtKindKwLoc(),
10006                                          C->getBeginLoc(), C->getLParenLoc(),
10007                                          C->getEndLoc());
10008 }
10009 
10010 template <typename Derived>
10011 OMPClause *
10012 TreeTransform<Derived>::TransformOMPSeverityClause(OMPSeverityClause *C) {
10013   return getDerived().RebuildOMPSeverityClause(
10014       C->getSeverityKind(), C->getSeverityKindKwLoc(), C->getBeginLoc(),
10015       C->getLParenLoc(), C->getEndLoc());
10016 }
10017 
10018 template <typename Derived>
10019 OMPClause *
10020 TreeTransform<Derived>::TransformOMPMessageClause(OMPMessageClause *C) {
10021   ExprResult E = getDerived().TransformExpr(C->getMessageString());
10022   if (E.isInvalid())
10023     return nullptr;
10024   return getDerived().RebuildOMPMessageClause(
10025       C->getMessageString(), C->getBeginLoc(), C->getLParenLoc(),
10026       C->getEndLoc());
10027 }
10028 
10029 template <typename Derived>
10030 OMPClause *
10031 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
10032   llvm::SmallVector<Expr *, 16> Vars;
10033   Vars.reserve(C->varlist_size());
10034   for (auto *VE : C->varlists()) {
10035     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10036     if (EVar.isInvalid())
10037       return nullptr;
10038     Vars.push_back(EVar.get());
10039   }
10040   return getDerived().RebuildOMPPrivateClause(
10041       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10042 }
10043 
10044 template <typename Derived>
10045 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
10046     OMPFirstprivateClause *C) {
10047   llvm::SmallVector<Expr *, 16> Vars;
10048   Vars.reserve(C->varlist_size());
10049   for (auto *VE : C->varlists()) {
10050     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10051     if (EVar.isInvalid())
10052       return nullptr;
10053     Vars.push_back(EVar.get());
10054   }
10055   return getDerived().RebuildOMPFirstprivateClause(
10056       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10057 }
10058 
10059 template <typename Derived>
10060 OMPClause *
10061 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
10062   llvm::SmallVector<Expr *, 16> Vars;
10063   Vars.reserve(C->varlist_size());
10064   for (auto *VE : C->varlists()) {
10065     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10066     if (EVar.isInvalid())
10067       return nullptr;
10068     Vars.push_back(EVar.get());
10069   }
10070   return getDerived().RebuildOMPLastprivateClause(
10071       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
10072       C->getLParenLoc(), C->getEndLoc());
10073 }
10074 
10075 template <typename Derived>
10076 OMPClause *
10077 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
10078   llvm::SmallVector<Expr *, 16> Vars;
10079   Vars.reserve(C->varlist_size());
10080   for (auto *VE : C->varlists()) {
10081     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10082     if (EVar.isInvalid())
10083       return nullptr;
10084     Vars.push_back(EVar.get());
10085   }
10086   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
10087                                              C->getLParenLoc(), C->getEndLoc());
10088 }
10089 
10090 template <typename Derived>
10091 OMPClause *
10092 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
10093   llvm::SmallVector<Expr *, 16> Vars;
10094   Vars.reserve(C->varlist_size());
10095   for (auto *VE : C->varlists()) {
10096     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10097     if (EVar.isInvalid())
10098       return nullptr;
10099     Vars.push_back(EVar.get());
10100   }
10101   CXXScopeSpec ReductionIdScopeSpec;
10102   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10103 
10104   DeclarationNameInfo NameInfo = C->getNameInfo();
10105   if (NameInfo.getName()) {
10106     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10107     if (!NameInfo.getName())
10108       return nullptr;
10109   }
10110   // Build a list of all UDR decls with the same names ranged by the Scopes.
10111   // The Scope boundary is a duplication of the previous decl.
10112   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10113   for (auto *E : C->reduction_ops()) {
10114     // Transform all the decls.
10115     if (E) {
10116       auto *ULE = cast<UnresolvedLookupExpr>(E);
10117       UnresolvedSet<8> Decls;
10118       for (auto *D : ULE->decls()) {
10119         NamedDecl *InstD =
10120             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10121         Decls.addDecl(InstD, InstD->getAccess());
10122       }
10123       UnresolvedReductions.push_back(
10124        UnresolvedLookupExpr::Create(
10125           SemaRef.Context, /*NamingClass=*/nullptr,
10126           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
10127           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
10128           Decls.begin(), Decls.end()));
10129     } else
10130       UnresolvedReductions.push_back(nullptr);
10131   }
10132   return getDerived().RebuildOMPReductionClause(
10133       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
10134       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
10135       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10136 }
10137 
10138 template <typename Derived>
10139 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
10140     OMPTaskReductionClause *C) {
10141   llvm::SmallVector<Expr *, 16> Vars;
10142   Vars.reserve(C->varlist_size());
10143   for (auto *VE : C->varlists()) {
10144     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10145     if (EVar.isInvalid())
10146       return nullptr;
10147     Vars.push_back(EVar.get());
10148   }
10149   CXXScopeSpec ReductionIdScopeSpec;
10150   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10151 
10152   DeclarationNameInfo NameInfo = C->getNameInfo();
10153   if (NameInfo.getName()) {
10154     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10155     if (!NameInfo.getName())
10156       return nullptr;
10157   }
10158   // Build a list of all UDR decls with the same names ranged by the Scopes.
10159   // The Scope boundary is a duplication of the previous decl.
10160   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10161   for (auto *E : C->reduction_ops()) {
10162     // Transform all the decls.
10163     if (E) {
10164       auto *ULE = cast<UnresolvedLookupExpr>(E);
10165       UnresolvedSet<8> Decls;
10166       for (auto *D : ULE->decls()) {
10167         NamedDecl *InstD =
10168             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10169         Decls.addDecl(InstD, InstD->getAccess());
10170       }
10171       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10172           SemaRef.Context, /*NamingClass=*/nullptr,
10173           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10174           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10175     } else
10176       UnresolvedReductions.push_back(nullptr);
10177   }
10178   return getDerived().RebuildOMPTaskReductionClause(
10179       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10180       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10181 }
10182 
10183 template <typename Derived>
10184 OMPClause *
10185 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
10186   llvm::SmallVector<Expr *, 16> Vars;
10187   Vars.reserve(C->varlist_size());
10188   for (auto *VE : C->varlists()) {
10189     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10190     if (EVar.isInvalid())
10191       return nullptr;
10192     Vars.push_back(EVar.get());
10193   }
10194   CXXScopeSpec ReductionIdScopeSpec;
10195   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10196 
10197   DeclarationNameInfo NameInfo = C->getNameInfo();
10198   if (NameInfo.getName()) {
10199     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10200     if (!NameInfo.getName())
10201       return nullptr;
10202   }
10203   // Build a list of all UDR decls with the same names ranged by the Scopes.
10204   // The Scope boundary is a duplication of the previous decl.
10205   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10206   for (auto *E : C->reduction_ops()) {
10207     // Transform all the decls.
10208     if (E) {
10209       auto *ULE = cast<UnresolvedLookupExpr>(E);
10210       UnresolvedSet<8> Decls;
10211       for (auto *D : ULE->decls()) {
10212         NamedDecl *InstD =
10213             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10214         Decls.addDecl(InstD, InstD->getAccess());
10215       }
10216       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10217           SemaRef.Context, /*NamingClass=*/nullptr,
10218           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10219           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10220     } else
10221       UnresolvedReductions.push_back(nullptr);
10222   }
10223   return getDerived().RebuildOMPInReductionClause(
10224       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10225       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10226 }
10227 
10228 template <typename Derived>
10229 OMPClause *
10230 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
10231   llvm::SmallVector<Expr *, 16> Vars;
10232   Vars.reserve(C->varlist_size());
10233   for (auto *VE : C->varlists()) {
10234     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10235     if (EVar.isInvalid())
10236       return nullptr;
10237     Vars.push_back(EVar.get());
10238   }
10239   ExprResult Step = getDerived().TransformExpr(C->getStep());
10240   if (Step.isInvalid())
10241     return nullptr;
10242   return getDerived().RebuildOMPLinearClause(
10243       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10244       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
10245 }
10246 
10247 template <typename Derived>
10248 OMPClause *
10249 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10250   llvm::SmallVector<Expr *, 16> Vars;
10251   Vars.reserve(C->varlist_size());
10252   for (auto *VE : C->varlists()) {
10253     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10254     if (EVar.isInvalid())
10255       return nullptr;
10256     Vars.push_back(EVar.get());
10257   }
10258   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10259   if (Alignment.isInvalid())
10260     return nullptr;
10261   return getDerived().RebuildOMPAlignedClause(
10262       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10263       C->getColonLoc(), C->getEndLoc());
10264 }
10265 
10266 template <typename Derived>
10267 OMPClause *
10268 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10269   llvm::SmallVector<Expr *, 16> Vars;
10270   Vars.reserve(C->varlist_size());
10271   for (auto *VE : C->varlists()) {
10272     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10273     if (EVar.isInvalid())
10274       return nullptr;
10275     Vars.push_back(EVar.get());
10276   }
10277   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10278                                              C->getLParenLoc(), C->getEndLoc());
10279 }
10280 
10281 template <typename Derived>
10282 OMPClause *
10283 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10284   llvm::SmallVector<Expr *, 16> Vars;
10285   Vars.reserve(C->varlist_size());
10286   for (auto *VE : C->varlists()) {
10287     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10288     if (EVar.isInvalid())
10289       return nullptr;
10290     Vars.push_back(EVar.get());
10291   }
10292   return getDerived().RebuildOMPCopyprivateClause(
10293       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10294 }
10295 
10296 template <typename Derived>
10297 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10298   llvm::SmallVector<Expr *, 16> Vars;
10299   Vars.reserve(C->varlist_size());
10300   for (auto *VE : C->varlists()) {
10301     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10302     if (EVar.isInvalid())
10303       return nullptr;
10304     Vars.push_back(EVar.get());
10305   }
10306   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10307                                             C->getLParenLoc(), C->getEndLoc());
10308 }
10309 
10310 template <typename Derived>
10311 OMPClause *
10312 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10313   ExprResult E = getDerived().TransformExpr(C->getDepobj());
10314   if (E.isInvalid())
10315     return nullptr;
10316   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10317                                              C->getLParenLoc(), C->getEndLoc());
10318 }
10319 
10320 template <typename Derived>
10321 OMPClause *
10322 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10323   llvm::SmallVector<Expr *, 16> Vars;
10324   Expr *DepModifier = C->getModifier();
10325   if (DepModifier) {
10326     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10327     if (DepModRes.isInvalid())
10328       return nullptr;
10329     DepModifier = DepModRes.get();
10330   }
10331   Vars.reserve(C->varlist_size());
10332   for (auto *VE : C->varlists()) {
10333     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10334     if (EVar.isInvalid())
10335       return nullptr;
10336     Vars.push_back(EVar.get());
10337   }
10338   return getDerived().RebuildOMPDependClause(
10339       {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10340        C->getOmpAllMemoryLoc()},
10341       DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10342 }
10343 
10344 template <typename Derived>
10345 OMPClause *
10346 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10347   ExprResult E = getDerived().TransformExpr(C->getDevice());
10348   if (E.isInvalid())
10349     return nullptr;
10350   return getDerived().RebuildOMPDeviceClause(
10351       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10352       C->getModifierLoc(), C->getEndLoc());
10353 }
10354 
10355 template <typename Derived, class T>
10356 bool transformOMPMappableExprListClause(
10357     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10358     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10359     DeclarationNameInfo &MapperIdInfo,
10360     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10361   // Transform expressions in the list.
10362   Vars.reserve(C->varlist_size());
10363   for (auto *VE : C->varlists()) {
10364     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10365     if (EVar.isInvalid())
10366       return true;
10367     Vars.push_back(EVar.get());
10368   }
10369   // Transform mapper scope specifier and identifier.
10370   NestedNameSpecifierLoc QualifierLoc;
10371   if (C->getMapperQualifierLoc()) {
10372     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10373         C->getMapperQualifierLoc());
10374     if (!QualifierLoc)
10375       return true;
10376   }
10377   MapperIdScopeSpec.Adopt(QualifierLoc);
10378   MapperIdInfo = C->getMapperIdInfo();
10379   if (MapperIdInfo.getName()) {
10380     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10381     if (!MapperIdInfo.getName())
10382       return true;
10383   }
10384   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10385   // the previous user-defined mapper lookup in dependent environment.
10386   for (auto *E : C->mapperlists()) {
10387     // Transform all the decls.
10388     if (E) {
10389       auto *ULE = cast<UnresolvedLookupExpr>(E);
10390       UnresolvedSet<8> Decls;
10391       for (auto *D : ULE->decls()) {
10392         NamedDecl *InstD =
10393             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10394         Decls.addDecl(InstD, InstD->getAccess());
10395       }
10396       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10397           TT.getSema().Context, /*NamingClass=*/nullptr,
10398           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10399           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10400           Decls.end()));
10401     } else {
10402       UnresolvedMappers.push_back(nullptr);
10403     }
10404   }
10405   return false;
10406 }
10407 
10408 template <typename Derived>
10409 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10410   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10411   llvm::SmallVector<Expr *, 16> Vars;
10412   Expr *IteratorModifier = C->getIteratorModifier();
10413   if (IteratorModifier) {
10414     ExprResult MapModRes = getDerived().TransformExpr(IteratorModifier);
10415     if (MapModRes.isInvalid())
10416       return nullptr;
10417     IteratorModifier = MapModRes.get();
10418   }
10419   CXXScopeSpec MapperIdScopeSpec;
10420   DeclarationNameInfo MapperIdInfo;
10421   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10422   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10423           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10424     return nullptr;
10425   return getDerived().RebuildOMPMapClause(
10426       IteratorModifier, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
10427       MapperIdScopeSpec, MapperIdInfo, C->getMapType(), C->isImplicitMapType(),
10428       C->getMapLoc(), C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10429 }
10430 
10431 template <typename Derived>
10432 OMPClause *
10433 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10434   Expr *Allocator = C->getAllocator();
10435   if (Allocator) {
10436     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10437     if (AllocatorRes.isInvalid())
10438       return nullptr;
10439     Allocator = AllocatorRes.get();
10440   }
10441   llvm::SmallVector<Expr *, 16> Vars;
10442   Vars.reserve(C->varlist_size());
10443   for (auto *VE : C->varlists()) {
10444     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10445     if (EVar.isInvalid())
10446       return nullptr;
10447     Vars.push_back(EVar.get());
10448   }
10449   return getDerived().RebuildOMPAllocateClause(
10450       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10451       C->getEndLoc());
10452 }
10453 
10454 template <typename Derived>
10455 OMPClause *
10456 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10457   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10458   if (E.isInvalid())
10459     return nullptr;
10460   return getDerived().RebuildOMPNumTeamsClause(
10461       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10462 }
10463 
10464 template <typename Derived>
10465 OMPClause *
10466 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10467   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10468   if (E.isInvalid())
10469     return nullptr;
10470   return getDerived().RebuildOMPThreadLimitClause(
10471       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10472 }
10473 
10474 template <typename Derived>
10475 OMPClause *
10476 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10477   ExprResult E = getDerived().TransformExpr(C->getPriority());
10478   if (E.isInvalid())
10479     return nullptr;
10480   return getDerived().RebuildOMPPriorityClause(
10481       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10482 }
10483 
10484 template <typename Derived>
10485 OMPClause *
10486 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10487   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10488   if (E.isInvalid())
10489     return nullptr;
10490   return getDerived().RebuildOMPGrainsizeClause(
10491       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10492       C->getModifierLoc(), C->getEndLoc());
10493 }
10494 
10495 template <typename Derived>
10496 OMPClause *
10497 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10498   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10499   if (E.isInvalid())
10500     return nullptr;
10501   return getDerived().RebuildOMPNumTasksClause(
10502       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10503       C->getModifierLoc(), C->getEndLoc());
10504 }
10505 
10506 template <typename Derived>
10507 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10508   ExprResult E = getDerived().TransformExpr(C->getHint());
10509   if (E.isInvalid())
10510     return nullptr;
10511   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10512                                            C->getLParenLoc(), C->getEndLoc());
10513 }
10514 
10515 template <typename Derived>
10516 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10517     OMPDistScheduleClause *C) {
10518   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10519   if (E.isInvalid())
10520     return nullptr;
10521   return getDerived().RebuildOMPDistScheduleClause(
10522       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10523       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10524 }
10525 
10526 template <typename Derived>
10527 OMPClause *
10528 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10529   // Rebuild Defaultmap Clause since we need to invoke the checking of
10530   // defaultmap(none:variable-category) after template initialization.
10531   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10532                                                  C->getDefaultmapKind(),
10533                                                  C->getBeginLoc(),
10534                                                  C->getLParenLoc(),
10535                                                  C->getDefaultmapModifierLoc(),
10536                                                  C->getDefaultmapKindLoc(),
10537                                                  C->getEndLoc());
10538 }
10539 
10540 template <typename Derived>
10541 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10542   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10543   llvm::SmallVector<Expr *, 16> Vars;
10544   CXXScopeSpec MapperIdScopeSpec;
10545   DeclarationNameInfo MapperIdInfo;
10546   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10547   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10548           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10549     return nullptr;
10550   return getDerived().RebuildOMPToClause(
10551       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10552       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10553 }
10554 
10555 template <typename Derived>
10556 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10557   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10558   llvm::SmallVector<Expr *, 16> Vars;
10559   CXXScopeSpec MapperIdScopeSpec;
10560   DeclarationNameInfo MapperIdInfo;
10561   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10562   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10563           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10564     return nullptr;
10565   return getDerived().RebuildOMPFromClause(
10566       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10567       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10568 }
10569 
10570 template <typename Derived>
10571 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10572     OMPUseDevicePtrClause *C) {
10573   llvm::SmallVector<Expr *, 16> Vars;
10574   Vars.reserve(C->varlist_size());
10575   for (auto *VE : C->varlists()) {
10576     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10577     if (EVar.isInvalid())
10578       return nullptr;
10579     Vars.push_back(EVar.get());
10580   }
10581   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10582   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10583 }
10584 
10585 template <typename Derived>
10586 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10587     OMPUseDeviceAddrClause *C) {
10588   llvm::SmallVector<Expr *, 16> Vars;
10589   Vars.reserve(C->varlist_size());
10590   for (auto *VE : C->varlists()) {
10591     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10592     if (EVar.isInvalid())
10593       return nullptr;
10594     Vars.push_back(EVar.get());
10595   }
10596   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10597   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10598 }
10599 
10600 template <typename Derived>
10601 OMPClause *
10602 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10603   llvm::SmallVector<Expr *, 16> Vars;
10604   Vars.reserve(C->varlist_size());
10605   for (auto *VE : C->varlists()) {
10606     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10607     if (EVar.isInvalid())
10608       return nullptr;
10609     Vars.push_back(EVar.get());
10610   }
10611   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10612   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10613 }
10614 
10615 template <typename Derived>
10616 OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10617     OMPHasDeviceAddrClause *C) {
10618   llvm::SmallVector<Expr *, 16> Vars;
10619   Vars.reserve(C->varlist_size());
10620   for (auto *VE : C->varlists()) {
10621     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10622     if (EVar.isInvalid())
10623       return nullptr;
10624     Vars.push_back(EVar.get());
10625   }
10626   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10627   return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10628 }
10629 
10630 template <typename Derived>
10631 OMPClause *
10632 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10633   llvm::SmallVector<Expr *, 16> Vars;
10634   Vars.reserve(C->varlist_size());
10635   for (auto *VE : C->varlists()) {
10636     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10637     if (EVar.isInvalid())
10638       return nullptr;
10639     Vars.push_back(EVar.get());
10640   }
10641   return getDerived().RebuildOMPNontemporalClause(
10642       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10643 }
10644 
10645 template <typename Derived>
10646 OMPClause *
10647 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10648   llvm::SmallVector<Expr *, 16> Vars;
10649   Vars.reserve(C->varlist_size());
10650   for (auto *VE : C->varlists()) {
10651     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10652     if (EVar.isInvalid())
10653       return nullptr;
10654     Vars.push_back(EVar.get());
10655   }
10656   return getDerived().RebuildOMPInclusiveClause(
10657       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10658 }
10659 
10660 template <typename Derived>
10661 OMPClause *
10662 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10663   llvm::SmallVector<Expr *, 16> Vars;
10664   Vars.reserve(C->varlist_size());
10665   for (auto *VE : C->varlists()) {
10666     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10667     if (EVar.isInvalid())
10668       return nullptr;
10669     Vars.push_back(EVar.get());
10670   }
10671   return getDerived().RebuildOMPExclusiveClause(
10672       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10673 }
10674 
10675 template <typename Derived>
10676 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10677     OMPUsesAllocatorsClause *C) {
10678   SmallVector<Sema::UsesAllocatorsData, 16> Data;
10679   Data.reserve(C->getNumberOfAllocators());
10680   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10681     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10682     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10683     if (Allocator.isInvalid())
10684       continue;
10685     ExprResult AllocatorTraits;
10686     if (Expr *AT = D.AllocatorTraits) {
10687       AllocatorTraits = getDerived().TransformExpr(AT);
10688       if (AllocatorTraits.isInvalid())
10689         continue;
10690     }
10691     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10692     NewD.Allocator = Allocator.get();
10693     NewD.AllocatorTraits = AllocatorTraits.get();
10694     NewD.LParenLoc = D.LParenLoc;
10695     NewD.RParenLoc = D.RParenLoc;
10696   }
10697   return getDerived().RebuildOMPUsesAllocatorsClause(
10698       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10699 }
10700 
10701 template <typename Derived>
10702 OMPClause *
10703 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10704   SmallVector<Expr *, 4> Locators;
10705   Locators.reserve(C->varlist_size());
10706   ExprResult ModifierRes;
10707   if (Expr *Modifier = C->getModifier()) {
10708     ModifierRes = getDerived().TransformExpr(Modifier);
10709     if (ModifierRes.isInvalid())
10710       return nullptr;
10711   }
10712   for (Expr *E : C->varlists()) {
10713     ExprResult Locator = getDerived().TransformExpr(E);
10714     if (Locator.isInvalid())
10715       continue;
10716     Locators.push_back(Locator.get());
10717   }
10718   return getDerived().RebuildOMPAffinityClause(
10719       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10720       ModifierRes.get(), Locators);
10721 }
10722 
10723 template <typename Derived>
10724 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10725   return getDerived().RebuildOMPOrderClause(
10726       C->getKind(), C->getKindKwLoc(), C->getBeginLoc(), C->getLParenLoc(),
10727       C->getEndLoc(), C->getModifier(), C->getModifierKwLoc());
10728 }
10729 
10730 template <typename Derived>
10731 OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10732   return getDerived().RebuildOMPBindClause(
10733       C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10734       C->getLParenLoc(), C->getEndLoc());
10735 }
10736 
10737 template <typename Derived>
10738 OMPClause *TreeTransform<Derived>::TransformOMPXDynCGroupMemClause(
10739     OMPXDynCGroupMemClause *C) {
10740   ExprResult Size = getDerived().TransformExpr(C->getSize());
10741   if (Size.isInvalid())
10742     return nullptr;
10743   return getDerived().RebuildOMPXDynCGroupMemClause(
10744       Size.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10745 }
10746 
10747 template <typename Derived>
10748 OMPClause *
10749 TreeTransform<Derived>::TransformOMPDoacrossClause(OMPDoacrossClause *C) {
10750   llvm::SmallVector<Expr *, 16> Vars;
10751   Vars.reserve(C->varlist_size());
10752   for (auto *VE : C->varlists()) {
10753     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10754     if (EVar.isInvalid())
10755       return nullptr;
10756     Vars.push_back(EVar.get());
10757   }
10758   return getDerived().RebuildOMPDoacrossClause(
10759       C->getDependenceType(), C->getDependenceLoc(), C->getColonLoc(), Vars,
10760       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10761 }
10762 
10763 //===----------------------------------------------------------------------===//
10764 // Expression transformation
10765 //===----------------------------------------------------------------------===//
10766 template<typename Derived>
10767 ExprResult
10768 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10769   return TransformExpr(E->getSubExpr());
10770 }
10771 
10772 template <typename Derived>
10773 ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10774     SYCLUniqueStableNameExpr *E) {
10775   if (!E->isTypeDependent())
10776     return E;
10777 
10778   TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10779 
10780   if (!NewT)
10781     return ExprError();
10782 
10783   if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10784     return E;
10785 
10786   return getDerived().RebuildSYCLUniqueStableNameExpr(
10787       E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10788 }
10789 
10790 template<typename Derived>
10791 ExprResult
10792 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10793   if (!E->isTypeDependent())
10794     return E;
10795 
10796   return getDerived().RebuildPredefinedExpr(E->getLocation(),
10797                                             E->getIdentKind());
10798 }
10799 
10800 template<typename Derived>
10801 ExprResult
10802 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10803   NestedNameSpecifierLoc QualifierLoc;
10804   if (E->getQualifierLoc()) {
10805     QualifierLoc
10806       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10807     if (!QualifierLoc)
10808       return ExprError();
10809   }
10810 
10811   ValueDecl *ND
10812     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10813                                                          E->getDecl()));
10814   if (!ND)
10815     return ExprError();
10816 
10817   NamedDecl *Found = ND;
10818   if (E->getFoundDecl() != E->getDecl()) {
10819     Found = cast_or_null<NamedDecl>(
10820         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10821     if (!Found)
10822       return ExprError();
10823   }
10824 
10825   DeclarationNameInfo NameInfo = E->getNameInfo();
10826   if (NameInfo.getName()) {
10827     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10828     if (!NameInfo.getName())
10829       return ExprError();
10830   }
10831 
10832   if (!getDerived().AlwaysRebuild() &&
10833       QualifierLoc == E->getQualifierLoc() &&
10834       ND == E->getDecl() &&
10835       Found == E->getFoundDecl() &&
10836       NameInfo.getName() == E->getDecl()->getDeclName() &&
10837       !E->hasExplicitTemplateArgs()) {
10838 
10839     // Mark it referenced in the new context regardless.
10840     // FIXME: this is a bit instantiation-specific.
10841     SemaRef.MarkDeclRefReferenced(E);
10842 
10843     return E;
10844   }
10845 
10846   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10847   if (E->hasExplicitTemplateArgs()) {
10848     TemplateArgs = &TransArgs;
10849     TransArgs.setLAngleLoc(E->getLAngleLoc());
10850     TransArgs.setRAngleLoc(E->getRAngleLoc());
10851     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10852                                                 E->getNumTemplateArgs(),
10853                                                 TransArgs))
10854       return ExprError();
10855   }
10856 
10857   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10858                                          Found, TemplateArgs);
10859 }
10860 
10861 template<typename Derived>
10862 ExprResult
10863 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10864   return E;
10865 }
10866 
10867 template <typename Derived>
10868 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10869     FixedPointLiteral *E) {
10870   return E;
10871 }
10872 
10873 template<typename Derived>
10874 ExprResult
10875 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10876   return E;
10877 }
10878 
10879 template<typename Derived>
10880 ExprResult
10881 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10882   return E;
10883 }
10884 
10885 template<typename Derived>
10886 ExprResult
10887 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10888   return E;
10889 }
10890 
10891 template<typename Derived>
10892 ExprResult
10893 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10894   return E;
10895 }
10896 
10897 template<typename Derived>
10898 ExprResult
10899 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10900   return getDerived().TransformCallExpr(E);
10901 }
10902 
10903 template<typename Derived>
10904 ExprResult
10905 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10906   ExprResult ControllingExpr;
10907   TypeSourceInfo *ControllingType = nullptr;
10908   if (E->isExprPredicate())
10909     ControllingExpr = getDerived().TransformExpr(E->getControllingExpr());
10910   else
10911     ControllingType = getDerived().TransformType(E->getControllingType());
10912 
10913   if (ControllingExpr.isInvalid() && !ControllingType)
10914     return ExprError();
10915 
10916   SmallVector<Expr *, 4> AssocExprs;
10917   SmallVector<TypeSourceInfo *, 4> AssocTypes;
10918   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10919     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10920     if (TSI) {
10921       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10922       if (!AssocType)
10923         return ExprError();
10924       AssocTypes.push_back(AssocType);
10925     } else {
10926       AssocTypes.push_back(nullptr);
10927     }
10928 
10929     ExprResult AssocExpr =
10930         getDerived().TransformExpr(Assoc.getAssociationExpr());
10931     if (AssocExpr.isInvalid())
10932       return ExprError();
10933     AssocExprs.push_back(AssocExpr.get());
10934   }
10935 
10936   if (!ControllingType)
10937   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10938                                                   E->getDefaultLoc(),
10939                                                   E->getRParenLoc(),
10940                                                   ControllingExpr.get(),
10941                                                   AssocTypes,
10942                                                   AssocExprs);
10943   return getDerived().RebuildGenericSelectionExpr(
10944       E->getGenericLoc(), E->getDefaultLoc(), E->getRParenLoc(),
10945       ControllingType, AssocTypes, AssocExprs);
10946 }
10947 
10948 template<typename Derived>
10949 ExprResult
10950 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10951   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10952   if (SubExpr.isInvalid())
10953     return ExprError();
10954 
10955   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10956     return E;
10957 
10958   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10959                                        E->getRParen());
10960 }
10961 
10962 /// The operand of a unary address-of operator has special rules: it's
10963 /// allowed to refer to a non-static member of a class even if there's no 'this'
10964 /// object available.
10965 template<typename Derived>
10966 ExprResult
10967 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10968   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10969     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10970   else
10971     return getDerived().TransformExpr(E);
10972 }
10973 
10974 template<typename Derived>
10975 ExprResult
10976 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10977   ExprResult SubExpr;
10978   if (E->getOpcode() == UO_AddrOf)
10979     SubExpr = TransformAddressOfOperand(E->getSubExpr());
10980   else
10981     SubExpr = TransformExpr(E->getSubExpr());
10982   if (SubExpr.isInvalid())
10983     return ExprError();
10984 
10985   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10986     return E;
10987 
10988   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10989                                            E->getOpcode(),
10990                                            SubExpr.get());
10991 }
10992 
10993 template<typename Derived>
10994 ExprResult
10995 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10996   // Transform the type.
10997   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10998   if (!Type)
10999     return ExprError();
11000 
11001   // Transform all of the components into components similar to what the
11002   // parser uses.
11003   // FIXME: It would be slightly more efficient in the non-dependent case to
11004   // just map FieldDecls, rather than requiring the rebuilder to look for
11005   // the fields again. However, __builtin_offsetof is rare enough in
11006   // template code that we don't care.
11007   bool ExprChanged = false;
11008   typedef Sema::OffsetOfComponent Component;
11009   SmallVector<Component, 4> Components;
11010   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
11011     const OffsetOfNode &ON = E->getComponent(I);
11012     Component Comp;
11013     Comp.isBrackets = true;
11014     Comp.LocStart = ON.getSourceRange().getBegin();
11015     Comp.LocEnd = ON.getSourceRange().getEnd();
11016     switch (ON.getKind()) {
11017     case OffsetOfNode::Array: {
11018       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
11019       ExprResult Index = getDerived().TransformExpr(FromIndex);
11020       if (Index.isInvalid())
11021         return ExprError();
11022 
11023       ExprChanged = ExprChanged || Index.get() != FromIndex;
11024       Comp.isBrackets = true;
11025       Comp.U.E = Index.get();
11026       break;
11027     }
11028 
11029     case OffsetOfNode::Field:
11030     case OffsetOfNode::Identifier:
11031       Comp.isBrackets = false;
11032       Comp.U.IdentInfo = ON.getFieldName();
11033       if (!Comp.U.IdentInfo)
11034         continue;
11035 
11036       break;
11037 
11038     case OffsetOfNode::Base:
11039       // Will be recomputed during the rebuild.
11040       continue;
11041     }
11042 
11043     Components.push_back(Comp);
11044   }
11045 
11046   // If nothing changed, retain the existing expression.
11047   if (!getDerived().AlwaysRebuild() &&
11048       Type == E->getTypeSourceInfo() &&
11049       !ExprChanged)
11050     return E;
11051 
11052   // Build a new offsetof expression.
11053   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
11054                                           Components, E->getRParenLoc());
11055 }
11056 
11057 template<typename Derived>
11058 ExprResult
11059 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
11060   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
11061          "opaque value expression requires transformation");
11062   return E;
11063 }
11064 
11065 template<typename Derived>
11066 ExprResult
11067 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
11068   return E;
11069 }
11070 
11071 template <typename Derived>
11072 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
11073   llvm::SmallVector<Expr *, 8> Children;
11074   bool Changed = false;
11075   for (Expr *C : E->subExpressions()) {
11076     ExprResult NewC = getDerived().TransformExpr(C);
11077     if (NewC.isInvalid())
11078       return ExprError();
11079     Children.push_back(NewC.get());
11080 
11081     Changed |= NewC.get() != C;
11082   }
11083   if (!getDerived().AlwaysRebuild() && !Changed)
11084     return E;
11085   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
11086                                           Children, E->getType());
11087 }
11088 
11089 template<typename Derived>
11090 ExprResult
11091 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
11092   // Rebuild the syntactic form.  The original syntactic form has
11093   // opaque-value expressions in it, so strip those away and rebuild
11094   // the result.  This is a really awful way of doing this, but the
11095   // better solution (rebuilding the semantic expressions and
11096   // rebinding OVEs as necessary) doesn't work; we'd need
11097   // TreeTransform to not strip away implicit conversions.
11098   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
11099   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
11100   if (result.isInvalid()) return ExprError();
11101 
11102   // If that gives us a pseudo-object result back, the pseudo-object
11103   // expression must have been an lvalue-to-rvalue conversion which we
11104   // should reapply.
11105   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
11106     result = SemaRef.checkPseudoObjectRValue(result.get());
11107 
11108   return result;
11109 }
11110 
11111 template<typename Derived>
11112 ExprResult
11113 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
11114                                                 UnaryExprOrTypeTraitExpr *E) {
11115   if (E->isArgumentType()) {
11116     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
11117 
11118     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11119     if (!NewT)
11120       return ExprError();
11121 
11122     if (!getDerived().AlwaysRebuild() && OldT == NewT)
11123       return E;
11124 
11125     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
11126                                                     E->getKind(),
11127                                                     E->getSourceRange());
11128   }
11129 
11130   // C++0x [expr.sizeof]p1:
11131   //   The operand is either an expression, which is an unevaluated operand
11132   //   [...]
11133   EnterExpressionEvaluationContext Unevaluated(
11134       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11135       Sema::ReuseLambdaContextDecl);
11136 
11137   // Try to recover if we have something like sizeof(T::X) where X is a type.
11138   // Notably, there must be *exactly* one set of parens if X is a type.
11139   TypeSourceInfo *RecoveryTSI = nullptr;
11140   ExprResult SubExpr;
11141   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
11142   if (auto *DRE =
11143           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
11144     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
11145         PE, DRE, false, &RecoveryTSI);
11146   else
11147     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
11148 
11149   if (RecoveryTSI) {
11150     return getDerived().RebuildUnaryExprOrTypeTrait(
11151         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
11152   } else if (SubExpr.isInvalid())
11153     return ExprError();
11154 
11155   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
11156     return E;
11157 
11158   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
11159                                                   E->getOperatorLoc(),
11160                                                   E->getKind(),
11161                                                   E->getSourceRange());
11162 }
11163 
11164 template<typename Derived>
11165 ExprResult
11166 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
11167   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11168   if (LHS.isInvalid())
11169     return ExprError();
11170 
11171   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11172   if (RHS.isInvalid())
11173     return ExprError();
11174 
11175 
11176   if (!getDerived().AlwaysRebuild() &&
11177       LHS.get() == E->getLHS() &&
11178       RHS.get() == E->getRHS())
11179     return E;
11180 
11181   return getDerived().RebuildArraySubscriptExpr(
11182       LHS.get(),
11183       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
11184 }
11185 
11186 template <typename Derived>
11187 ExprResult
11188 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
11189   ExprResult Base = getDerived().TransformExpr(E->getBase());
11190   if (Base.isInvalid())
11191     return ExprError();
11192 
11193   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
11194   if (RowIdx.isInvalid())
11195     return ExprError();
11196 
11197   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
11198   if (ColumnIdx.isInvalid())
11199     return ExprError();
11200 
11201   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11202       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
11203     return E;
11204 
11205   return getDerived().RebuildMatrixSubscriptExpr(
11206       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
11207 }
11208 
11209 template <typename Derived>
11210 ExprResult
11211 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
11212   ExprResult Base = getDerived().TransformExpr(E->getBase());
11213   if (Base.isInvalid())
11214     return ExprError();
11215 
11216   ExprResult LowerBound;
11217   if (E->getLowerBound()) {
11218     LowerBound = getDerived().TransformExpr(E->getLowerBound());
11219     if (LowerBound.isInvalid())
11220       return ExprError();
11221   }
11222 
11223   ExprResult Length;
11224   if (E->getLength()) {
11225     Length = getDerived().TransformExpr(E->getLength());
11226     if (Length.isInvalid())
11227       return ExprError();
11228   }
11229 
11230   ExprResult Stride;
11231   if (Expr *Str = E->getStride()) {
11232     Stride = getDerived().TransformExpr(Str);
11233     if (Stride.isInvalid())
11234       return ExprError();
11235   }
11236 
11237   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11238       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
11239     return E;
11240 
11241   return getDerived().RebuildOMPArraySectionExpr(
11242       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
11243       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
11244       E->getRBracketLoc());
11245 }
11246 
11247 template <typename Derived>
11248 ExprResult
11249 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
11250   ExprResult Base = getDerived().TransformExpr(E->getBase());
11251   if (Base.isInvalid())
11252     return ExprError();
11253 
11254   SmallVector<Expr *, 4> Dims;
11255   bool ErrorFound = false;
11256   for (Expr *Dim : E->getDimensions()) {
11257     ExprResult DimRes = getDerived().TransformExpr(Dim);
11258     if (DimRes.isInvalid()) {
11259       ErrorFound = true;
11260       continue;
11261     }
11262     Dims.push_back(DimRes.get());
11263   }
11264 
11265   if (ErrorFound)
11266     return ExprError();
11267   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
11268                                                  E->getRParenLoc(), Dims,
11269                                                  E->getBracketsRanges());
11270 }
11271 
11272 template <typename Derived>
11273 ExprResult
11274 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
11275   unsigned NumIterators = E->numOfIterators();
11276   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
11277 
11278   bool ErrorFound = false;
11279   bool NeedToRebuild = getDerived().AlwaysRebuild();
11280   for (unsigned I = 0; I < NumIterators; ++I) {
11281     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
11282     Data[I].DeclIdent = D->getIdentifier();
11283     Data[I].DeclIdentLoc = D->getLocation();
11284     if (D->getLocation() == D->getBeginLoc()) {
11285       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
11286              "Implicit type must be int.");
11287     } else {
11288       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11289       QualType DeclTy = getDerived().TransformType(D->getType());
11290       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11291     }
11292     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11293     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11294     ExprResult End = getDerived().TransformExpr(Range.End);
11295     ExprResult Step = getDerived().TransformExpr(Range.Step);
11296     ErrorFound = ErrorFound ||
11297                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11298                                                !Data[I].Type.get().isNull())) ||
11299                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11300     if (ErrorFound)
11301       continue;
11302     Data[I].Range.Begin = Begin.get();
11303     Data[I].Range.End = End.get();
11304     Data[I].Range.Step = Step.get();
11305     Data[I].AssignLoc = E->getAssignLoc(I);
11306     Data[I].ColonLoc = E->getColonLoc(I);
11307     Data[I].SecColonLoc = E->getSecondColonLoc(I);
11308     NeedToRebuild =
11309         NeedToRebuild ||
11310         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11311                                        D->getType().getTypePtrOrNull()) ||
11312         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11313         Range.Step != Data[I].Range.Step;
11314   }
11315   if (ErrorFound)
11316     return ExprError();
11317   if (!NeedToRebuild)
11318     return E;
11319 
11320   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11321       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11322   if (!Res.isUsable())
11323     return Res;
11324   auto *IE = cast<OMPIteratorExpr>(Res.get());
11325   for (unsigned I = 0; I < NumIterators; ++I)
11326     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11327                                       IE->getIteratorDecl(I));
11328   return Res;
11329 }
11330 
11331 template<typename Derived>
11332 ExprResult
11333 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11334   // Transform the callee.
11335   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11336   if (Callee.isInvalid())
11337     return ExprError();
11338 
11339   // Transform arguments.
11340   bool ArgChanged = false;
11341   SmallVector<Expr*, 8> Args;
11342   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11343                                   &ArgChanged))
11344     return ExprError();
11345 
11346   if (!getDerived().AlwaysRebuild() &&
11347       Callee.get() == E->getCallee() &&
11348       !ArgChanged)
11349     return SemaRef.MaybeBindToTemporary(E);
11350 
11351   // FIXME: Wrong source location information for the '('.
11352   SourceLocation FakeLParenLoc
11353     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11354 
11355   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11356   if (E->hasStoredFPFeatures()) {
11357     FPOptionsOverride NewOverrides = E->getFPFeatures();
11358     getSema().CurFPFeatures =
11359         NewOverrides.applyOverrides(getSema().getLangOpts());
11360     getSema().FpPragmaStack.CurrentValue = NewOverrides;
11361   }
11362 
11363   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11364                                       Args,
11365                                       E->getRParenLoc());
11366 }
11367 
11368 template<typename Derived>
11369 ExprResult
11370 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11371   ExprResult Base = getDerived().TransformExpr(E->getBase());
11372   if (Base.isInvalid())
11373     return ExprError();
11374 
11375   NestedNameSpecifierLoc QualifierLoc;
11376   if (E->hasQualifier()) {
11377     QualifierLoc
11378       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11379 
11380     if (!QualifierLoc)
11381       return ExprError();
11382   }
11383   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11384 
11385   ValueDecl *Member
11386     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11387                                                          E->getMemberDecl()));
11388   if (!Member)
11389     return ExprError();
11390 
11391   NamedDecl *FoundDecl = E->getFoundDecl();
11392   if (FoundDecl == E->getMemberDecl()) {
11393     FoundDecl = Member;
11394   } else {
11395     FoundDecl = cast_or_null<NamedDecl>(
11396                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11397     if (!FoundDecl)
11398       return ExprError();
11399   }
11400 
11401   if (!getDerived().AlwaysRebuild() &&
11402       Base.get() == E->getBase() &&
11403       QualifierLoc == E->getQualifierLoc() &&
11404       Member == E->getMemberDecl() &&
11405       FoundDecl == E->getFoundDecl() &&
11406       !E->hasExplicitTemplateArgs()) {
11407 
11408     // Skip for member expression of (this->f), rebuilt thisi->f is needed
11409     // for Openmp where the field need to be privatizized in the case.
11410     if (!(isa<CXXThisExpr>(E->getBase()) &&
11411           getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11412       // Mark it referenced in the new context regardless.
11413       // FIXME: this is a bit instantiation-specific.
11414       SemaRef.MarkMemberReferenced(E);
11415       return E;
11416     }
11417   }
11418 
11419   TemplateArgumentListInfo TransArgs;
11420   if (E->hasExplicitTemplateArgs()) {
11421     TransArgs.setLAngleLoc(E->getLAngleLoc());
11422     TransArgs.setRAngleLoc(E->getRAngleLoc());
11423     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11424                                                 E->getNumTemplateArgs(),
11425                                                 TransArgs))
11426       return ExprError();
11427   }
11428 
11429   // FIXME: Bogus source location for the operator
11430   SourceLocation FakeOperatorLoc =
11431       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11432 
11433   // FIXME: to do this check properly, we will need to preserve the
11434   // first-qualifier-in-scope here, just in case we had a dependent
11435   // base (and therefore couldn't do the check) and a
11436   // nested-name-qualifier (and therefore could do the lookup).
11437   NamedDecl *FirstQualifierInScope = nullptr;
11438   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11439   if (MemberNameInfo.getName()) {
11440     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11441     if (!MemberNameInfo.getName())
11442       return ExprError();
11443   }
11444 
11445   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11446                                         E->isArrow(),
11447                                         QualifierLoc,
11448                                         TemplateKWLoc,
11449                                         MemberNameInfo,
11450                                         Member,
11451                                         FoundDecl,
11452                                         (E->hasExplicitTemplateArgs()
11453                                            ? &TransArgs : nullptr),
11454                                         FirstQualifierInScope);
11455 }
11456 
11457 template<typename Derived>
11458 ExprResult
11459 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11460   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11461   if (LHS.isInvalid())
11462     return ExprError();
11463 
11464   ExprResult RHS =
11465       getDerived().TransformInitializer(E->getRHS(), /*NotCopyInit=*/false);
11466   if (RHS.isInvalid())
11467     return ExprError();
11468 
11469   if (!getDerived().AlwaysRebuild() &&
11470       LHS.get() == E->getLHS() &&
11471       RHS.get() == E->getRHS())
11472     return E;
11473 
11474   if (E->isCompoundAssignmentOp())
11475     // FPFeatures has already been established from trailing storage
11476     return getDerived().RebuildBinaryOperator(
11477         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11478   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11479   FPOptionsOverride NewOverrides(E->getFPFeatures());
11480   getSema().CurFPFeatures =
11481       NewOverrides.applyOverrides(getSema().getLangOpts());
11482   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11483   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11484                                             LHS.get(), RHS.get());
11485 }
11486 
11487 template <typename Derived>
11488 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11489     CXXRewrittenBinaryOperator *E) {
11490   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11491 
11492   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11493   if (LHS.isInvalid())
11494     return ExprError();
11495 
11496   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11497   if (RHS.isInvalid())
11498     return ExprError();
11499 
11500   // Extract the already-resolved callee declarations so that we can restrict
11501   // ourselves to using them as the unqualified lookup results when rebuilding.
11502   UnresolvedSet<2> UnqualLookups;
11503   bool ChangedAnyLookups = false;
11504   Expr *PossibleBinOps[] = {E->getSemanticForm(),
11505                             const_cast<Expr *>(Decomp.InnerBinOp)};
11506   for (Expr *PossibleBinOp : PossibleBinOps) {
11507     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11508     if (!Op)
11509       continue;
11510     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11511     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11512       continue;
11513 
11514     // Transform the callee in case we built a call to a local extern
11515     // declaration.
11516     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11517         E->getOperatorLoc(), Callee->getFoundDecl()));
11518     if (!Found)
11519       return ExprError();
11520     if (Found != Callee->getFoundDecl())
11521       ChangedAnyLookups = true;
11522     UnqualLookups.addDecl(Found);
11523   }
11524 
11525   if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11526       LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11527     // Mark all functions used in the rewrite as referenced. Note that when
11528     // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11529     // function calls, and/or there might be a user-defined conversion sequence
11530     // applied to the operands of the <.
11531     // FIXME: this is a bit instantiation-specific.
11532     const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11533     SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11534     return E;
11535   }
11536 
11537   return getDerived().RebuildCXXRewrittenBinaryOperator(
11538       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11539 }
11540 
11541 template<typename Derived>
11542 ExprResult
11543 TreeTransform<Derived>::TransformCompoundAssignOperator(
11544                                                       CompoundAssignOperator *E) {
11545   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11546   FPOptionsOverride NewOverrides(E->getFPFeatures());
11547   getSema().CurFPFeatures =
11548       NewOverrides.applyOverrides(getSema().getLangOpts());
11549   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11550   return getDerived().TransformBinaryOperator(E);
11551 }
11552 
11553 template<typename Derived>
11554 ExprResult TreeTransform<Derived>::
11555 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11556   // Just rebuild the common and RHS expressions and see whether we
11557   // get any changes.
11558 
11559   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11560   if (commonExpr.isInvalid())
11561     return ExprError();
11562 
11563   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11564   if (rhs.isInvalid())
11565     return ExprError();
11566 
11567   if (!getDerived().AlwaysRebuild() &&
11568       commonExpr.get() == e->getCommon() &&
11569       rhs.get() == e->getFalseExpr())
11570     return e;
11571 
11572   return getDerived().RebuildConditionalOperator(commonExpr.get(),
11573                                                  e->getQuestionLoc(),
11574                                                  nullptr,
11575                                                  e->getColonLoc(),
11576                                                  rhs.get());
11577 }
11578 
11579 template<typename Derived>
11580 ExprResult
11581 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11582   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11583   if (Cond.isInvalid())
11584     return ExprError();
11585 
11586   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11587   if (LHS.isInvalid())
11588     return ExprError();
11589 
11590   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11591   if (RHS.isInvalid())
11592     return ExprError();
11593 
11594   if (!getDerived().AlwaysRebuild() &&
11595       Cond.get() == E->getCond() &&
11596       LHS.get() == E->getLHS() &&
11597       RHS.get() == E->getRHS())
11598     return E;
11599 
11600   return getDerived().RebuildConditionalOperator(Cond.get(),
11601                                                  E->getQuestionLoc(),
11602                                                  LHS.get(),
11603                                                  E->getColonLoc(),
11604                                                  RHS.get());
11605 }
11606 
11607 template<typename Derived>
11608 ExprResult
11609 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11610   // Implicit casts are eliminated during transformation, since they
11611   // will be recomputed by semantic analysis after transformation.
11612   return getDerived().TransformExpr(E->getSubExprAsWritten());
11613 }
11614 
11615 template<typename Derived>
11616 ExprResult
11617 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11618   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11619   if (!Type)
11620     return ExprError();
11621 
11622   ExprResult SubExpr
11623     = getDerived().TransformExpr(E->getSubExprAsWritten());
11624   if (SubExpr.isInvalid())
11625     return ExprError();
11626 
11627   if (!getDerived().AlwaysRebuild() &&
11628       Type == E->getTypeInfoAsWritten() &&
11629       SubExpr.get() == E->getSubExpr())
11630     return E;
11631 
11632   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11633                                             Type,
11634                                             E->getRParenLoc(),
11635                                             SubExpr.get());
11636 }
11637 
11638 template<typename Derived>
11639 ExprResult
11640 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11641   TypeSourceInfo *OldT = E->getTypeSourceInfo();
11642   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11643   if (!NewT)
11644     return ExprError();
11645 
11646   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11647   if (Init.isInvalid())
11648     return ExprError();
11649 
11650   if (!getDerived().AlwaysRebuild() &&
11651       OldT == NewT &&
11652       Init.get() == E->getInitializer())
11653     return SemaRef.MaybeBindToTemporary(E);
11654 
11655   // Note: the expression type doesn't necessarily match the
11656   // type-as-written, but that's okay, because it should always be
11657   // derivable from the initializer.
11658 
11659   return getDerived().RebuildCompoundLiteralExpr(
11660       E->getLParenLoc(), NewT,
11661       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11662 }
11663 
11664 template<typename Derived>
11665 ExprResult
11666 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11667   ExprResult Base = getDerived().TransformExpr(E->getBase());
11668   if (Base.isInvalid())
11669     return ExprError();
11670 
11671   if (!getDerived().AlwaysRebuild() &&
11672       Base.get() == E->getBase())
11673     return E;
11674 
11675   // FIXME: Bad source location
11676   SourceLocation FakeOperatorLoc =
11677       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11678   return getDerived().RebuildExtVectorElementExpr(
11679       Base.get(), FakeOperatorLoc, E->isArrow(), E->getAccessorLoc(),
11680       E->getAccessor());
11681 }
11682 
11683 template<typename Derived>
11684 ExprResult
11685 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11686   if (InitListExpr *Syntactic = E->getSyntacticForm())
11687     E = Syntactic;
11688 
11689   bool InitChanged = false;
11690 
11691   EnterExpressionEvaluationContext Context(
11692       getSema(), EnterExpressionEvaluationContext::InitList);
11693 
11694   SmallVector<Expr*, 4> Inits;
11695   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11696                                   Inits, &InitChanged))
11697     return ExprError();
11698 
11699   if (!getDerived().AlwaysRebuild() && !InitChanged) {
11700     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11701     // in some cases. We can't reuse it in general, because the syntactic and
11702     // semantic forms are linked, and we can't know that semantic form will
11703     // match even if the syntactic form does.
11704   }
11705 
11706   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11707                                       E->getRBraceLoc());
11708 }
11709 
11710 template<typename Derived>
11711 ExprResult
11712 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11713   Designation Desig;
11714 
11715   // transform the initializer value
11716   ExprResult Init = getDerived().TransformExpr(E->getInit());
11717   if (Init.isInvalid())
11718     return ExprError();
11719 
11720   // transform the designators.
11721   SmallVector<Expr*, 4> ArrayExprs;
11722   bool ExprChanged = false;
11723   for (const DesignatedInitExpr::Designator &D : E->designators()) {
11724     if (D.isFieldDesignator()) {
11725       Desig.AddDesignator(Designator::CreateFieldDesignator(
11726           D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
11727       if (D.getFieldDecl()) {
11728         FieldDecl *Field = cast_or_null<FieldDecl>(
11729             getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
11730         if (Field != D.getFieldDecl())
11731           // Rebuild the expression when the transformed FieldDecl is
11732           // different to the already assigned FieldDecl.
11733           ExprChanged = true;
11734       } else {
11735         // Ensure that the designator expression is rebuilt when there isn't
11736         // a resolved FieldDecl in the designator as we don't want to assign
11737         // a FieldDecl to a pattern designator that will be instantiated again.
11738         ExprChanged = true;
11739       }
11740       continue;
11741     }
11742 
11743     if (D.isArrayDesignator()) {
11744       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11745       if (Index.isInvalid())
11746         return ExprError();
11747 
11748       Desig.AddDesignator(
11749           Designator::CreateArrayDesignator(Index.get(), D.getLBracketLoc()));
11750 
11751       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11752       ArrayExprs.push_back(Index.get());
11753       continue;
11754     }
11755 
11756     assert(D.isArrayRangeDesignator() && "New kind of designator?");
11757     ExprResult Start
11758       = getDerived().TransformExpr(E->getArrayRangeStart(D));
11759     if (Start.isInvalid())
11760       return ExprError();
11761 
11762     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11763     if (End.isInvalid())
11764       return ExprError();
11765 
11766     Desig.AddDesignator(Designator::CreateArrayRangeDesignator(
11767         Start.get(), End.get(), D.getLBracketLoc(), D.getEllipsisLoc()));
11768 
11769     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11770                   End.get() != E->getArrayRangeEnd(D);
11771 
11772     ArrayExprs.push_back(Start.get());
11773     ArrayExprs.push_back(End.get());
11774   }
11775 
11776   if (!getDerived().AlwaysRebuild() &&
11777       Init.get() == E->getInit() &&
11778       !ExprChanged)
11779     return E;
11780 
11781   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11782                                                 E->getEqualOrColonLoc(),
11783                                                 E->usesGNUSyntax(), Init.get());
11784 }
11785 
11786 // Seems that if TransformInitListExpr() only works on the syntactic form of an
11787 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11788 template<typename Derived>
11789 ExprResult
11790 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11791     DesignatedInitUpdateExpr *E) {
11792   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
11793                    "initializer");
11794   return ExprError();
11795 }
11796 
11797 template<typename Derived>
11798 ExprResult
11799 TreeTransform<Derived>::TransformNoInitExpr(
11800     NoInitExpr *E) {
11801   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
11802   return ExprError();
11803 }
11804 
11805 template<typename Derived>
11806 ExprResult
11807 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11808   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
11809   return ExprError();
11810 }
11811 
11812 template<typename Derived>
11813 ExprResult
11814 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11815   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
11816   return ExprError();
11817 }
11818 
11819 template<typename Derived>
11820 ExprResult
11821 TreeTransform<Derived>::TransformImplicitValueInitExpr(
11822                                                      ImplicitValueInitExpr *E) {
11823   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11824 
11825   // FIXME: Will we ever have proper type location here? Will we actually
11826   // need to transform the type?
11827   QualType T = getDerived().TransformType(E->getType());
11828   if (T.isNull())
11829     return ExprError();
11830 
11831   if (!getDerived().AlwaysRebuild() &&
11832       T == E->getType())
11833     return E;
11834 
11835   return getDerived().RebuildImplicitValueInitExpr(T);
11836 }
11837 
11838 template<typename Derived>
11839 ExprResult
11840 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11841   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11842   if (!TInfo)
11843     return ExprError();
11844 
11845   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11846   if (SubExpr.isInvalid())
11847     return ExprError();
11848 
11849   if (!getDerived().AlwaysRebuild() &&
11850       TInfo == E->getWrittenTypeInfo() &&
11851       SubExpr.get() == E->getSubExpr())
11852     return E;
11853 
11854   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11855                                        TInfo, E->getRParenLoc());
11856 }
11857 
11858 template<typename Derived>
11859 ExprResult
11860 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11861   bool ArgumentChanged = false;
11862   SmallVector<Expr*, 4> Inits;
11863   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11864                      &ArgumentChanged))
11865     return ExprError();
11866 
11867   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11868                                            Inits,
11869                                            E->getRParenLoc());
11870 }
11871 
11872 /// Transform an address-of-label expression.
11873 ///
11874 /// By default, the transformation of an address-of-label expression always
11875 /// rebuilds the expression, so that the label identifier can be resolved to
11876 /// the corresponding label statement by semantic analysis.
11877 template<typename Derived>
11878 ExprResult
11879 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11880   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11881                                         E->getLabel());
11882   if (!LD)
11883     return ExprError();
11884 
11885   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11886                                            cast<LabelDecl>(LD));
11887 }
11888 
11889 template<typename Derived>
11890 ExprResult
11891 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11892   SemaRef.ActOnStartStmtExpr();
11893   StmtResult SubStmt
11894     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11895   if (SubStmt.isInvalid()) {
11896     SemaRef.ActOnStmtExprError();
11897     return ExprError();
11898   }
11899 
11900   unsigned OldDepth = E->getTemplateDepth();
11901   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11902 
11903   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11904       SubStmt.get() == E->getSubStmt()) {
11905     // Calling this an 'error' is unintuitive, but it does the right thing.
11906     SemaRef.ActOnStmtExprError();
11907     return SemaRef.MaybeBindToTemporary(E);
11908   }
11909 
11910   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11911                                       E->getRParenLoc(), NewDepth);
11912 }
11913 
11914 template<typename Derived>
11915 ExprResult
11916 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11917   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11918   if (Cond.isInvalid())
11919     return ExprError();
11920 
11921   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11922   if (LHS.isInvalid())
11923     return ExprError();
11924 
11925   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11926   if (RHS.isInvalid())
11927     return ExprError();
11928 
11929   if (!getDerived().AlwaysRebuild() &&
11930       Cond.get() == E->getCond() &&
11931       LHS.get() == E->getLHS() &&
11932       RHS.get() == E->getRHS())
11933     return E;
11934 
11935   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11936                                         Cond.get(), LHS.get(), RHS.get(),
11937                                         E->getRParenLoc());
11938 }
11939 
11940 template<typename Derived>
11941 ExprResult
11942 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11943   return E;
11944 }
11945 
11946 template<typename Derived>
11947 ExprResult
11948 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11949   switch (E->getOperator()) {
11950   case OO_New:
11951   case OO_Delete:
11952   case OO_Array_New:
11953   case OO_Array_Delete:
11954     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
11955 
11956   case OO_Subscript:
11957   case OO_Call: {
11958     // This is a call to an object's operator().
11959     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
11960 
11961     // Transform the object itself.
11962     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11963     if (Object.isInvalid())
11964       return ExprError();
11965 
11966     // FIXME: Poor location information
11967     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11968         static_cast<Expr *>(Object.get())->getEndLoc());
11969 
11970     // Transform the call arguments.
11971     SmallVector<Expr*, 8> Args;
11972     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11973                                     Args))
11974       return ExprError();
11975 
11976     if (E->getOperator() == OO_Subscript)
11977       return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
11978                                                   Args, E->getEndLoc());
11979 
11980     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11981                                         E->getEndLoc());
11982   }
11983 
11984 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
11985   case OO_##Name:                                                              \
11986     break;
11987 
11988 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11989 #include "clang/Basic/OperatorKinds.def"
11990 
11991   case OO_Conditional:
11992     llvm_unreachable("conditional operator is not actually overloadable");
11993 
11994   case OO_None:
11995   case NUM_OVERLOADED_OPERATORS:
11996     llvm_unreachable("not an overloaded operator?");
11997   }
11998 
11999   ExprResult First;
12000   if (E->getOperator() == OO_Amp)
12001     First = getDerived().TransformAddressOfOperand(E->getArg(0));
12002   else
12003     First = getDerived().TransformExpr(E->getArg(0));
12004   if (First.isInvalid())
12005     return ExprError();
12006 
12007   ExprResult Second;
12008   if (E->getNumArgs() == 2) {
12009     Second =
12010         getDerived().TransformInitializer(E->getArg(1), /*NotCopyInit=*/false);
12011     if (Second.isInvalid())
12012       return ExprError();
12013   }
12014 
12015   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
12016   FPOptionsOverride NewOverrides(E->getFPFeatures());
12017   getSema().CurFPFeatures =
12018       NewOverrides.applyOverrides(getSema().getLangOpts());
12019   getSema().FpPragmaStack.CurrentValue = NewOverrides;
12020 
12021   Expr *Callee = E->getCallee();
12022   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
12023     LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12024                    Sema::LookupOrdinaryName);
12025     if (getDerived().TransformOverloadExprDecls(ULE, ULE->requiresADL(), R))
12026       return ExprError();
12027 
12028     return getDerived().RebuildCXXOperatorCallExpr(
12029         E->getOperator(), E->getOperatorLoc(), Callee->getBeginLoc(),
12030         ULE->requiresADL(), R.asUnresolvedSet(), First.get(), Second.get());
12031   }
12032 
12033   UnresolvedSet<1> Functions;
12034   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
12035     Callee = ICE->getSubExprAsWritten();
12036   NamedDecl *DR = cast<DeclRefExpr>(Callee)->getDecl();
12037   ValueDecl *VD = cast_or_null<ValueDecl>(
12038       getDerived().TransformDecl(DR->getLocation(), DR));
12039   if (!VD)
12040     return ExprError();
12041 
12042   if (!isa<CXXMethodDecl>(VD))
12043     Functions.addDecl(VD);
12044 
12045   return getDerived().RebuildCXXOperatorCallExpr(
12046       E->getOperator(), E->getOperatorLoc(), Callee->getBeginLoc(),
12047       /*RequiresADL=*/false, Functions, First.get(), Second.get());
12048 }
12049 
12050 template<typename Derived>
12051 ExprResult
12052 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
12053   return getDerived().TransformCallExpr(E);
12054 }
12055 
12056 template <typename Derived>
12057 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
12058   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
12059                          getSema().CurContext != E->getParentContext();
12060 
12061   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
12062     return E;
12063 
12064   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
12065                                            E->getBeginLoc(), E->getEndLoc(),
12066                                            getSema().CurContext);
12067 }
12068 
12069 template<typename Derived>
12070 ExprResult
12071 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
12072   // Transform the callee.
12073   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
12074   if (Callee.isInvalid())
12075     return ExprError();
12076 
12077   // Transform exec config.
12078   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
12079   if (EC.isInvalid())
12080     return ExprError();
12081 
12082   // Transform arguments.
12083   bool ArgChanged = false;
12084   SmallVector<Expr*, 8> Args;
12085   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12086                                   &ArgChanged))
12087     return ExprError();
12088 
12089   if (!getDerived().AlwaysRebuild() &&
12090       Callee.get() == E->getCallee() &&
12091       !ArgChanged)
12092     return SemaRef.MaybeBindToTemporary(E);
12093 
12094   // FIXME: Wrong source location information for the '('.
12095   SourceLocation FakeLParenLoc
12096     = ((Expr *)Callee.get())->getSourceRange().getBegin();
12097   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
12098                                       Args,
12099                                       E->getRParenLoc(), EC.get());
12100 }
12101 
12102 template<typename Derived>
12103 ExprResult
12104 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
12105   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
12106   if (!Type)
12107     return ExprError();
12108 
12109   ExprResult SubExpr
12110     = getDerived().TransformExpr(E->getSubExprAsWritten());
12111   if (SubExpr.isInvalid())
12112     return ExprError();
12113 
12114   if (!getDerived().AlwaysRebuild() &&
12115       Type == E->getTypeInfoAsWritten() &&
12116       SubExpr.get() == E->getSubExpr())
12117     return E;
12118   return getDerived().RebuildCXXNamedCastExpr(
12119       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
12120       Type, E->getAngleBrackets().getEnd(),
12121       // FIXME. this should be '(' location
12122       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
12123 }
12124 
12125 template<typename Derived>
12126 ExprResult
12127 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
12128   TypeSourceInfo *TSI =
12129       getDerived().TransformType(BCE->getTypeInfoAsWritten());
12130   if (!TSI)
12131     return ExprError();
12132 
12133   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
12134   if (Sub.isInvalid())
12135     return ExprError();
12136 
12137   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
12138                                                 Sub.get(), BCE->getEndLoc());
12139 }
12140 
12141 template<typename Derived>
12142 ExprResult
12143 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
12144   return getDerived().TransformCXXNamedCastExpr(E);
12145 }
12146 
12147 template<typename Derived>
12148 ExprResult
12149 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
12150   return getDerived().TransformCXXNamedCastExpr(E);
12151 }
12152 
12153 template<typename Derived>
12154 ExprResult
12155 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
12156                                                       CXXReinterpretCastExpr *E) {
12157   return getDerived().TransformCXXNamedCastExpr(E);
12158 }
12159 
12160 template<typename Derived>
12161 ExprResult
12162 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
12163   return getDerived().TransformCXXNamedCastExpr(E);
12164 }
12165 
12166 template<typename Derived>
12167 ExprResult
12168 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
12169   return getDerived().TransformCXXNamedCastExpr(E);
12170 }
12171 
12172 template<typename Derived>
12173 ExprResult
12174 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
12175                                                      CXXFunctionalCastExpr *E) {
12176   TypeSourceInfo *Type =
12177       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
12178   if (!Type)
12179     return ExprError();
12180 
12181   ExprResult SubExpr
12182     = getDerived().TransformExpr(E->getSubExprAsWritten());
12183   if (SubExpr.isInvalid())
12184     return ExprError();
12185 
12186   if (!getDerived().AlwaysRebuild() &&
12187       Type == E->getTypeInfoAsWritten() &&
12188       SubExpr.get() == E->getSubExpr())
12189     return E;
12190 
12191   return getDerived().RebuildCXXFunctionalCastExpr(Type,
12192                                                    E->getLParenLoc(),
12193                                                    SubExpr.get(),
12194                                                    E->getRParenLoc(),
12195                                                    E->isListInitialization());
12196 }
12197 
12198 template<typename Derived>
12199 ExprResult
12200 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
12201   if (E->isTypeOperand()) {
12202     TypeSourceInfo *TInfo
12203       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12204     if (!TInfo)
12205       return ExprError();
12206 
12207     if (!getDerived().AlwaysRebuild() &&
12208         TInfo == E->getTypeOperandSourceInfo())
12209       return E;
12210 
12211     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12212                                              TInfo, E->getEndLoc());
12213   }
12214 
12215   // Typeid's operand is an unevaluated context, unless it's a polymorphic
12216   // type.  We must not unilaterally enter unevaluated context here, as then
12217   // semantic processing can re-transform an already transformed operand.
12218   Expr *Op = E->getExprOperand();
12219   auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
12220   if (E->isGLValue())
12221     if (auto *RecordT = Op->getType()->getAs<RecordType>())
12222       if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
12223         EvalCtx = SemaRef.ExprEvalContexts.back().Context;
12224 
12225   EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
12226                                                Sema::ReuseLambdaContextDecl);
12227 
12228   ExprResult SubExpr = getDerived().TransformExpr(Op);
12229   if (SubExpr.isInvalid())
12230     return ExprError();
12231 
12232   if (!getDerived().AlwaysRebuild() &&
12233       SubExpr.get() == E->getExprOperand())
12234     return E;
12235 
12236   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12237                                            SubExpr.get(), E->getEndLoc());
12238 }
12239 
12240 template<typename Derived>
12241 ExprResult
12242 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
12243   if (E->isTypeOperand()) {
12244     TypeSourceInfo *TInfo
12245       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12246     if (!TInfo)
12247       return ExprError();
12248 
12249     if (!getDerived().AlwaysRebuild() &&
12250         TInfo == E->getTypeOperandSourceInfo())
12251       return E;
12252 
12253     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12254                                              TInfo, E->getEndLoc());
12255   }
12256 
12257   EnterExpressionEvaluationContext Unevaluated(
12258       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12259 
12260   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
12261   if (SubExpr.isInvalid())
12262     return ExprError();
12263 
12264   if (!getDerived().AlwaysRebuild() &&
12265       SubExpr.get() == E->getExprOperand())
12266     return E;
12267 
12268   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12269                                            SubExpr.get(), E->getEndLoc());
12270 }
12271 
12272 template<typename Derived>
12273 ExprResult
12274 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
12275   return E;
12276 }
12277 
12278 template<typename Derived>
12279 ExprResult
12280 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
12281                                                      CXXNullPtrLiteralExpr *E) {
12282   return E;
12283 }
12284 
12285 template<typename Derived>
12286 ExprResult
12287 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
12288 
12289   // In lambdas, the qualifiers of the type depends of where in
12290   // the call operator `this` appear, and we do not have a good way to
12291   // rebuild this information, so we transform the type.
12292   //
12293   // In other contexts, the type of `this` may be overrided
12294   // for type deduction, so we need to recompute it.
12295   QualType T = getSema().getCurLambda() ?
12296                    getDerived().TransformType(E->getType())
12297                  : getSema().getCurrentThisType();
12298 
12299   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
12300     // Mark it referenced in the new context regardless.
12301     // FIXME: this is a bit instantiation-specific.
12302     getSema().MarkThisReferenced(E);
12303     return E;
12304   }
12305 
12306   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12307 }
12308 
12309 template<typename Derived>
12310 ExprResult
12311 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12312   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12313   if (SubExpr.isInvalid())
12314     return ExprError();
12315 
12316   if (!getDerived().AlwaysRebuild() &&
12317       SubExpr.get() == E->getSubExpr())
12318     return E;
12319 
12320   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12321                                           E->isThrownVariableInScope());
12322 }
12323 
12324 template<typename Derived>
12325 ExprResult
12326 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12327   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12328       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12329   if (!Param)
12330     return ExprError();
12331 
12332   ExprResult InitRes;
12333   if (E->hasRewrittenInit()) {
12334     InitRes = getDerived().TransformExpr(E->getRewrittenExpr());
12335     if (InitRes.isInvalid())
12336       return ExprError();
12337   }
12338 
12339   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12340       E->getUsedContext() == SemaRef.CurContext &&
12341       InitRes.get() == E->getRewrittenExpr())
12342     return E;
12343 
12344   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param,
12345                                                InitRes.get());
12346 }
12347 
12348 template<typename Derived>
12349 ExprResult
12350 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12351   FieldDecl *Field = cast_or_null<FieldDecl>(
12352       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12353   if (!Field)
12354     return ExprError();
12355 
12356   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12357       E->getUsedContext() == SemaRef.CurContext)
12358     return E;
12359 
12360   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12361 }
12362 
12363 template<typename Derived>
12364 ExprResult
12365 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12366                                                     CXXScalarValueInitExpr *E) {
12367   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12368   if (!T)
12369     return ExprError();
12370 
12371   if (!getDerived().AlwaysRebuild() &&
12372       T == E->getTypeSourceInfo())
12373     return E;
12374 
12375   return getDerived().RebuildCXXScalarValueInitExpr(T,
12376                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
12377                                                     E->getRParenLoc());
12378 }
12379 
12380 template<typename Derived>
12381 ExprResult
12382 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12383   // Transform the type that we're allocating
12384   TypeSourceInfo *AllocTypeInfo =
12385       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12386   if (!AllocTypeInfo)
12387     return ExprError();
12388 
12389   // Transform the size of the array we're allocating (if any).
12390   std::optional<Expr *> ArraySize;
12391   if (E->isArray()) {
12392     ExprResult NewArraySize;
12393     if (std::optional<Expr *> OldArraySize = E->getArraySize()) {
12394       NewArraySize = getDerived().TransformExpr(*OldArraySize);
12395       if (NewArraySize.isInvalid())
12396         return ExprError();
12397     }
12398     ArraySize = NewArraySize.get();
12399   }
12400 
12401   // Transform the placement arguments (if any).
12402   bool ArgumentChanged = false;
12403   SmallVector<Expr*, 8> PlacementArgs;
12404   if (getDerived().TransformExprs(E->getPlacementArgs(),
12405                                   E->getNumPlacementArgs(), true,
12406                                   PlacementArgs, &ArgumentChanged))
12407     return ExprError();
12408 
12409   // Transform the initializer (if any).
12410   Expr *OldInit = E->getInitializer();
12411   ExprResult NewInit;
12412   if (OldInit)
12413     NewInit = getDerived().TransformInitializer(OldInit, true);
12414   if (NewInit.isInvalid())
12415     return ExprError();
12416 
12417   // Transform new operator and delete operator.
12418   FunctionDecl *OperatorNew = nullptr;
12419   if (E->getOperatorNew()) {
12420     OperatorNew = cast_or_null<FunctionDecl>(
12421         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12422     if (!OperatorNew)
12423       return ExprError();
12424   }
12425 
12426   FunctionDecl *OperatorDelete = nullptr;
12427   if (E->getOperatorDelete()) {
12428     OperatorDelete = cast_or_null<FunctionDecl>(
12429         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12430     if (!OperatorDelete)
12431       return ExprError();
12432   }
12433 
12434   if (!getDerived().AlwaysRebuild() &&
12435       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12436       ArraySize == E->getArraySize() &&
12437       NewInit.get() == OldInit &&
12438       OperatorNew == E->getOperatorNew() &&
12439       OperatorDelete == E->getOperatorDelete() &&
12440       !ArgumentChanged) {
12441     // Mark any declarations we need as referenced.
12442     // FIXME: instantiation-specific.
12443     if (OperatorNew)
12444       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12445     if (OperatorDelete)
12446       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12447 
12448     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12449       QualType ElementType
12450         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12451       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12452         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12453         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12454           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12455         }
12456       }
12457     }
12458 
12459     return E;
12460   }
12461 
12462   QualType AllocType = AllocTypeInfo->getType();
12463   if (!ArraySize) {
12464     // If no array size was specified, but the new expression was
12465     // instantiated with an array type (e.g., "new T" where T is
12466     // instantiated with "int[4]"), extract the outer bound from the
12467     // array type as our array size. We do this with constant and
12468     // dependently-sized array types.
12469     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12470     if (!ArrayT) {
12471       // Do nothing
12472     } else if (const ConstantArrayType *ConsArrayT
12473                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
12474       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12475                                          SemaRef.Context.getSizeType(),
12476                                          /*FIXME:*/ E->getBeginLoc());
12477       AllocType = ConsArrayT->getElementType();
12478     } else if (const DependentSizedArrayType *DepArrayT
12479                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12480       if (DepArrayT->getSizeExpr()) {
12481         ArraySize = DepArrayT->getSizeExpr();
12482         AllocType = DepArrayT->getElementType();
12483       }
12484     }
12485   }
12486 
12487   return getDerived().RebuildCXXNewExpr(
12488       E->getBeginLoc(), E->isGlobalNew(),
12489       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12490       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12491       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12492 }
12493 
12494 template<typename Derived>
12495 ExprResult
12496 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12497   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12498   if (Operand.isInvalid())
12499     return ExprError();
12500 
12501   // Transform the delete operator, if known.
12502   FunctionDecl *OperatorDelete = nullptr;
12503   if (E->getOperatorDelete()) {
12504     OperatorDelete = cast_or_null<FunctionDecl>(
12505         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12506     if (!OperatorDelete)
12507       return ExprError();
12508   }
12509 
12510   if (!getDerived().AlwaysRebuild() &&
12511       Operand.get() == E->getArgument() &&
12512       OperatorDelete == E->getOperatorDelete()) {
12513     // Mark any declarations we need as referenced.
12514     // FIXME: instantiation-specific.
12515     if (OperatorDelete)
12516       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12517 
12518     if (!E->getArgument()->isTypeDependent()) {
12519       QualType Destroyed = SemaRef.Context.getBaseElementType(
12520                                                          E->getDestroyedType());
12521       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12522         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12523         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12524                                        SemaRef.LookupDestructor(Record));
12525       }
12526     }
12527 
12528     return E;
12529   }
12530 
12531   return getDerived().RebuildCXXDeleteExpr(
12532       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12533 }
12534 
12535 template<typename Derived>
12536 ExprResult
12537 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12538                                                      CXXPseudoDestructorExpr *E) {
12539   ExprResult Base = getDerived().TransformExpr(E->getBase());
12540   if (Base.isInvalid())
12541     return ExprError();
12542 
12543   ParsedType ObjectTypePtr;
12544   bool MayBePseudoDestructor = false;
12545   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12546                                               E->getOperatorLoc(),
12547                                         E->isArrow()? tok::arrow : tok::period,
12548                                               ObjectTypePtr,
12549                                               MayBePseudoDestructor);
12550   if (Base.isInvalid())
12551     return ExprError();
12552 
12553   QualType ObjectType = ObjectTypePtr.get();
12554   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12555   if (QualifierLoc) {
12556     QualifierLoc
12557       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12558     if (!QualifierLoc)
12559       return ExprError();
12560   }
12561   CXXScopeSpec SS;
12562   SS.Adopt(QualifierLoc);
12563 
12564   PseudoDestructorTypeStorage Destroyed;
12565   if (E->getDestroyedTypeInfo()) {
12566     TypeSourceInfo *DestroyedTypeInfo
12567       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12568                                                 ObjectType, nullptr, SS);
12569     if (!DestroyedTypeInfo)
12570       return ExprError();
12571     Destroyed = DestroyedTypeInfo;
12572   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12573     // We aren't likely to be able to resolve the identifier down to a type
12574     // now anyway, so just retain the identifier.
12575     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12576                                             E->getDestroyedTypeLoc());
12577   } else {
12578     // Look for a destructor known with the given name.
12579     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12580                                               *E->getDestroyedTypeIdentifier(),
12581                                                 E->getDestroyedTypeLoc(),
12582                                                 /*Scope=*/nullptr,
12583                                                 SS, ObjectTypePtr,
12584                                                 false);
12585     if (!T)
12586       return ExprError();
12587 
12588     Destroyed
12589       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12590                                                  E->getDestroyedTypeLoc());
12591   }
12592 
12593   TypeSourceInfo *ScopeTypeInfo = nullptr;
12594   if (E->getScopeTypeInfo()) {
12595     CXXScopeSpec EmptySS;
12596     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12597                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12598     if (!ScopeTypeInfo)
12599       return ExprError();
12600   }
12601 
12602   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12603                                                      E->getOperatorLoc(),
12604                                                      E->isArrow(),
12605                                                      SS,
12606                                                      ScopeTypeInfo,
12607                                                      E->getColonColonLoc(),
12608                                                      E->getTildeLoc(),
12609                                                      Destroyed);
12610 }
12611 
12612 template <typename Derived>
12613 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12614                                                         bool RequiresADL,
12615                                                         LookupResult &R) {
12616   // Transform all the decls.
12617   bool AllEmptyPacks = true;
12618   for (auto *OldD : Old->decls()) {
12619     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12620     if (!InstD) {
12621       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12622       // This can happen because of dependent hiding.
12623       if (isa<UsingShadowDecl>(OldD))
12624         continue;
12625       else {
12626         R.clear();
12627         return true;
12628       }
12629     }
12630 
12631     // Expand using pack declarations.
12632     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12633     ArrayRef<NamedDecl*> Decls = SingleDecl;
12634     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12635       Decls = UPD->expansions();
12636 
12637     // Expand using declarations.
12638     for (auto *D : Decls) {
12639       if (auto *UD = dyn_cast<UsingDecl>(D)) {
12640         for (auto *SD : UD->shadows())
12641           R.addDecl(SD);
12642       } else {
12643         R.addDecl(D);
12644       }
12645     }
12646 
12647     AllEmptyPacks &= Decls.empty();
12648   };
12649 
12650   // C++ [temp.res]/8.4.2:
12651   //   The program is ill-formed, no diagnostic required, if [...] lookup for
12652   //   a name in the template definition found a using-declaration, but the
12653   //   lookup in the corresponding scope in the instantiation odoes not find
12654   //   any declarations because the using-declaration was a pack expansion and
12655   //   the corresponding pack is empty
12656   if (AllEmptyPacks && !RequiresADL) {
12657     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12658         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12659     return true;
12660   }
12661 
12662   // Resolve a kind, but don't do any further analysis.  If it's
12663   // ambiguous, the callee needs to deal with it.
12664   R.resolveKind();
12665   return false;
12666 }
12667 
12668 template<typename Derived>
12669 ExprResult
12670 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12671                                                   UnresolvedLookupExpr *Old) {
12672   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12673                  Sema::LookupOrdinaryName);
12674 
12675   // Transform the declaration set.
12676   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12677     return ExprError();
12678 
12679   // Rebuild the nested-name qualifier, if present.
12680   CXXScopeSpec SS;
12681   if (Old->getQualifierLoc()) {
12682     NestedNameSpecifierLoc QualifierLoc
12683       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12684     if (!QualifierLoc)
12685       return ExprError();
12686 
12687     SS.Adopt(QualifierLoc);
12688   }
12689 
12690   if (Old->getNamingClass()) {
12691     CXXRecordDecl *NamingClass
12692       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12693                                                             Old->getNameLoc(),
12694                                                         Old->getNamingClass()));
12695     if (!NamingClass) {
12696       R.clear();
12697       return ExprError();
12698     }
12699 
12700     R.setNamingClass(NamingClass);
12701   }
12702 
12703   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12704 
12705   // If we have neither explicit template arguments, nor the template keyword,
12706   // it's a normal declaration name or member reference.
12707   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12708     NamedDecl *D = R.getAsSingle<NamedDecl>();
12709     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12710     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12711     // give a good diagnostic.
12712     if (D && D->isCXXInstanceMember()) {
12713       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12714                                                      /*TemplateArgs=*/nullptr,
12715                                                      /*Scope=*/nullptr);
12716     }
12717 
12718     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12719   }
12720 
12721   // If we have template arguments, rebuild them, then rebuild the
12722   // templateid expression.
12723   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12724   if (Old->hasExplicitTemplateArgs() &&
12725       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12726                                               Old->getNumTemplateArgs(),
12727                                               TransArgs)) {
12728     R.clear();
12729     return ExprError();
12730   }
12731 
12732   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12733                                             Old->requiresADL(), &TransArgs);
12734 }
12735 
12736 template<typename Derived>
12737 ExprResult
12738 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12739   bool ArgChanged = false;
12740   SmallVector<TypeSourceInfo *, 4> Args;
12741   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12742     TypeSourceInfo *From = E->getArg(I);
12743     TypeLoc FromTL = From->getTypeLoc();
12744     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12745       TypeLocBuilder TLB;
12746       TLB.reserve(FromTL.getFullDataSize());
12747       QualType To = getDerived().TransformType(TLB, FromTL);
12748       if (To.isNull())
12749         return ExprError();
12750 
12751       if (To == From->getType())
12752         Args.push_back(From);
12753       else {
12754         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12755         ArgChanged = true;
12756       }
12757       continue;
12758     }
12759 
12760     ArgChanged = true;
12761 
12762     // We have a pack expansion. Instantiate it.
12763     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12764     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12765     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12766     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12767 
12768     // Determine whether the set of unexpanded parameter packs can and should
12769     // be expanded.
12770     bool Expand = true;
12771     bool RetainExpansion = false;
12772     std::optional<unsigned> OrigNumExpansions =
12773         ExpansionTL.getTypePtr()->getNumExpansions();
12774     std::optional<unsigned> NumExpansions = OrigNumExpansions;
12775     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12776                                              PatternTL.getSourceRange(),
12777                                              Unexpanded,
12778                                              Expand, RetainExpansion,
12779                                              NumExpansions))
12780       return ExprError();
12781 
12782     if (!Expand) {
12783       // The transform has determined that we should perform a simple
12784       // transformation on the pack expansion, producing another pack
12785       // expansion.
12786       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12787 
12788       TypeLocBuilder TLB;
12789       TLB.reserve(From->getTypeLoc().getFullDataSize());
12790 
12791       QualType To = getDerived().TransformType(TLB, PatternTL);
12792       if (To.isNull())
12793         return ExprError();
12794 
12795       To = getDerived().RebuildPackExpansionType(To,
12796                                                  PatternTL.getSourceRange(),
12797                                                  ExpansionTL.getEllipsisLoc(),
12798                                                  NumExpansions);
12799       if (To.isNull())
12800         return ExprError();
12801 
12802       PackExpansionTypeLoc ToExpansionTL
12803         = TLB.push<PackExpansionTypeLoc>(To);
12804       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12805       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12806       continue;
12807     }
12808 
12809     // Expand the pack expansion by substituting for each argument in the
12810     // pack(s).
12811     for (unsigned I = 0; I != *NumExpansions; ++I) {
12812       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12813       TypeLocBuilder TLB;
12814       TLB.reserve(PatternTL.getFullDataSize());
12815       QualType To = getDerived().TransformType(TLB, PatternTL);
12816       if (To.isNull())
12817         return ExprError();
12818 
12819       if (To->containsUnexpandedParameterPack()) {
12820         To = getDerived().RebuildPackExpansionType(To,
12821                                                    PatternTL.getSourceRange(),
12822                                                    ExpansionTL.getEllipsisLoc(),
12823                                                    NumExpansions);
12824         if (To.isNull())
12825           return ExprError();
12826 
12827         PackExpansionTypeLoc ToExpansionTL
12828           = TLB.push<PackExpansionTypeLoc>(To);
12829         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12830       }
12831 
12832       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12833     }
12834 
12835     if (!RetainExpansion)
12836       continue;
12837 
12838     // If we're supposed to retain a pack expansion, do so by temporarily
12839     // forgetting the partially-substituted parameter pack.
12840     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12841 
12842     TypeLocBuilder TLB;
12843     TLB.reserve(From->getTypeLoc().getFullDataSize());
12844 
12845     QualType To = getDerived().TransformType(TLB, PatternTL);
12846     if (To.isNull())
12847       return ExprError();
12848 
12849     To = getDerived().RebuildPackExpansionType(To,
12850                                                PatternTL.getSourceRange(),
12851                                                ExpansionTL.getEllipsisLoc(),
12852                                                NumExpansions);
12853     if (To.isNull())
12854       return ExprError();
12855 
12856     PackExpansionTypeLoc ToExpansionTL
12857       = TLB.push<PackExpansionTypeLoc>(To);
12858     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12859     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12860   }
12861 
12862   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12863     return E;
12864 
12865   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12866                                        E->getEndLoc());
12867 }
12868 
12869 template<typename Derived>
12870 ExprResult
12871 TreeTransform<Derived>::TransformConceptSpecializationExpr(
12872                                                  ConceptSpecializationExpr *E) {
12873   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12874   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12875   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12876                                               Old->NumTemplateArgs, TransArgs))
12877     return ExprError();
12878 
12879   return getDerived().RebuildConceptSpecializationExpr(
12880       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12881       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12882       &TransArgs);
12883 }
12884 
12885 template<typename Derived>
12886 ExprResult
12887 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12888   SmallVector<ParmVarDecl*, 4> TransParams;
12889   SmallVector<QualType, 4> TransParamTypes;
12890   Sema::ExtParameterInfoBuilder ExtParamInfos;
12891 
12892   // C++2a [expr.prim.req]p2
12893   // Expressions appearing within a requirement-body are unevaluated operands.
12894   EnterExpressionEvaluationContext Ctx(
12895       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
12896       Sema::ReuseLambdaContextDecl);
12897 
12898   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12899       getSema().Context, getSema().CurContext,
12900       E->getBody()->getBeginLoc());
12901 
12902   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12903 
12904   ExprResult TypeParamResult = getDerived().TransformRequiresTypeParams(
12905       E->getRequiresKWLoc(), E->getRBraceLoc(), E, Body,
12906       E->getLocalParameters(), TransParamTypes, TransParams, ExtParamInfos);
12907 
12908   for (ParmVarDecl *Param : TransParams)
12909     if (Param)
12910       Param->setDeclContext(Body);
12911 
12912   // On failure to transform, TransformRequiresTypeParams returns an expression
12913   // in the event that the transformation of the type params failed in some way.
12914   // It is expected that this will result in a 'not satisfied' Requires clause
12915   // when instantiating.
12916   if (!TypeParamResult.isUnset())
12917     return TypeParamResult;
12918 
12919   SmallVector<concepts::Requirement *, 4> TransReqs;
12920   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12921                                                      TransReqs))
12922     return ExprError();
12923 
12924   for (concepts::Requirement *Req : TransReqs) {
12925     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12926       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12927         ER->getReturnTypeRequirement()
12928                 .getTypeConstraintTemplateParameterList()->getParam(0)
12929                 ->setDeclContext(Body);
12930       }
12931     }
12932   }
12933 
12934   return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12935                                           TransParams, TransReqs,
12936                                           E->getRBraceLoc());
12937 }
12938 
12939 template<typename Derived>
12940 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12941     ArrayRef<concepts::Requirement *> Reqs,
12942     SmallVectorImpl<concepts::Requirement *> &Transformed) {
12943   for (concepts::Requirement *Req : Reqs) {
12944     concepts::Requirement *TransReq = nullptr;
12945     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12946       TransReq = getDerived().TransformTypeRequirement(TypeReq);
12947     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12948       TransReq = getDerived().TransformExprRequirement(ExprReq);
12949     else
12950       TransReq = getDerived().TransformNestedRequirement(
12951                      cast<concepts::NestedRequirement>(Req));
12952     if (!TransReq)
12953       return true;
12954     Transformed.push_back(TransReq);
12955   }
12956   return false;
12957 }
12958 
12959 template<typename Derived>
12960 concepts::TypeRequirement *
12961 TreeTransform<Derived>::TransformTypeRequirement(
12962     concepts::TypeRequirement *Req) {
12963   if (Req->isSubstitutionFailure()) {
12964     if (getDerived().AlwaysRebuild())
12965       return getDerived().RebuildTypeRequirement(
12966               Req->getSubstitutionDiagnostic());
12967     return Req;
12968   }
12969   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12970   if (!TransType)
12971     return nullptr;
12972   return getDerived().RebuildTypeRequirement(TransType);
12973 }
12974 
12975 template<typename Derived>
12976 concepts::ExprRequirement *
12977 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12978   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12979   if (Req->isExprSubstitutionFailure())
12980     TransExpr = Req->getExprSubstitutionDiagnostic();
12981   else {
12982     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12983     if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12984       TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12985     if (TransExprRes.isInvalid())
12986       return nullptr;
12987     TransExpr = TransExprRes.get();
12988   }
12989 
12990   std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12991   const auto &RetReq = Req->getReturnTypeRequirement();
12992   if (RetReq.isEmpty())
12993     TransRetReq.emplace();
12994   else if (RetReq.isSubstitutionFailure())
12995     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12996   else if (RetReq.isTypeConstraint()) {
12997     TemplateParameterList *OrigTPL =
12998         RetReq.getTypeConstraintTemplateParameterList();
12999     TemplateParameterList *TPL =
13000         getDerived().TransformTemplateParameterList(OrigTPL);
13001     if (!TPL)
13002       return nullptr;
13003     TransRetReq.emplace(TPL);
13004   }
13005   assert(TransRetReq && "All code paths leading here must set TransRetReq");
13006   if (Expr *E = TransExpr.dyn_cast<Expr *>())
13007     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
13008                                                Req->getNoexceptLoc(),
13009                                                std::move(*TransRetReq));
13010   return getDerived().RebuildExprRequirement(
13011       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
13012       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
13013 }
13014 
13015 template<typename Derived>
13016 concepts::NestedRequirement *
13017 TreeTransform<Derived>::TransformNestedRequirement(
13018     concepts::NestedRequirement *Req) {
13019   if (Req->hasInvalidConstraint()) {
13020     if (getDerived().AlwaysRebuild())
13021       return getDerived().RebuildNestedRequirement(
13022           Req->getInvalidConstraintEntity(), Req->getConstraintSatisfaction());
13023     return Req;
13024   }
13025   ExprResult TransConstraint =
13026       getDerived().TransformExpr(Req->getConstraintExpr());
13027   if (TransConstraint.isInvalid())
13028     return nullptr;
13029   return getDerived().RebuildNestedRequirement(TransConstraint.get());
13030 }
13031 
13032 template<typename Derived>
13033 ExprResult
13034 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
13035   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
13036   if (!T)
13037     return ExprError();
13038 
13039   if (!getDerived().AlwaysRebuild() &&
13040       T == E->getQueriedTypeSourceInfo())
13041     return E;
13042 
13043   ExprResult SubExpr;
13044   {
13045     EnterExpressionEvaluationContext Unevaluated(
13046         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13047     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
13048     if (SubExpr.isInvalid())
13049       return ExprError();
13050 
13051     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
13052       return E;
13053   }
13054 
13055   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
13056                                             SubExpr.get(), E->getEndLoc());
13057 }
13058 
13059 template<typename Derived>
13060 ExprResult
13061 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
13062   ExprResult SubExpr;
13063   {
13064     EnterExpressionEvaluationContext Unevaluated(
13065         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13066     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
13067     if (SubExpr.isInvalid())
13068       return ExprError();
13069 
13070     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
13071       return E;
13072   }
13073 
13074   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
13075                                              SubExpr.get(), E->getEndLoc());
13076 }
13077 
13078 template <typename Derived>
13079 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
13080     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
13081     TypeSourceInfo **RecoveryTSI) {
13082   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
13083       DRE, AddrTaken, RecoveryTSI);
13084 
13085   // Propagate both errors and recovered types, which return ExprEmpty.
13086   if (!NewDRE.isUsable())
13087     return NewDRE;
13088 
13089   // We got an expr, wrap it up in parens.
13090   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
13091     return PE;
13092   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
13093                                        PE->getRParen());
13094 }
13095 
13096 template <typename Derived>
13097 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13098     DependentScopeDeclRefExpr *E) {
13099   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
13100                                             nullptr);
13101 }
13102 
13103 template <typename Derived>
13104 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13105     DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
13106     TypeSourceInfo **RecoveryTSI) {
13107   assert(E->getQualifierLoc());
13108   NestedNameSpecifierLoc QualifierLoc =
13109       getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
13110   if (!QualifierLoc)
13111     return ExprError();
13112   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13113 
13114   // TODO: If this is a conversion-function-id, verify that the
13115   // destination type name (if present) resolves the same way after
13116   // instantiation as it did in the local scope.
13117 
13118   DeclarationNameInfo NameInfo =
13119       getDerived().TransformDeclarationNameInfo(E->getNameInfo());
13120   if (!NameInfo.getName())
13121     return ExprError();
13122 
13123   if (!E->hasExplicitTemplateArgs()) {
13124     if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
13125         // Note: it is sufficient to compare the Name component of NameInfo:
13126         // if name has not changed, DNLoc has not changed either.
13127         NameInfo.getName() == E->getDeclName())
13128       return E;
13129 
13130     return getDerived().RebuildDependentScopeDeclRefExpr(
13131         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
13132         IsAddressOfOperand, RecoveryTSI);
13133   }
13134 
13135   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13136   if (getDerived().TransformTemplateArguments(
13137           E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
13138     return ExprError();
13139 
13140   return getDerived().RebuildDependentScopeDeclRefExpr(
13141       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
13142       RecoveryTSI);
13143 }
13144 
13145 template<typename Derived>
13146 ExprResult
13147 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
13148   // CXXConstructExprs other than for list-initialization and
13149   // CXXTemporaryObjectExpr are always implicit, so when we have
13150   // a 1-argument construction we just transform that argument.
13151   if (getDerived().AllowSkippingCXXConstructExpr() &&
13152       ((E->getNumArgs() == 1 ||
13153         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
13154        (!getDerived().DropCallArgument(E->getArg(0))) &&
13155        !E->isListInitialization()))
13156     return getDerived().TransformInitializer(E->getArg(0),
13157                                              /*DirectInit*/ false);
13158 
13159   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
13160 
13161   QualType T = getDerived().TransformType(E->getType());
13162   if (T.isNull())
13163     return ExprError();
13164 
13165   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13166       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13167   if (!Constructor)
13168     return ExprError();
13169 
13170   bool ArgumentChanged = false;
13171   SmallVector<Expr*, 8> Args;
13172   {
13173     EnterExpressionEvaluationContext Context(
13174         getSema(), EnterExpressionEvaluationContext::InitList,
13175         E->isListInitialization());
13176     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13177                                     &ArgumentChanged))
13178       return ExprError();
13179   }
13180 
13181   if (!getDerived().AlwaysRebuild() &&
13182       T == E->getType() &&
13183       Constructor == E->getConstructor() &&
13184       !ArgumentChanged) {
13185     // Mark the constructor as referenced.
13186     // FIXME: Instantiation-specific
13187     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13188     return E;
13189   }
13190 
13191   return getDerived().RebuildCXXConstructExpr(
13192       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
13193       E->hadMultipleCandidates(), E->isListInitialization(),
13194       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
13195       E->getConstructionKind(), E->getParenOrBraceRange());
13196 }
13197 
13198 template<typename Derived>
13199 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
13200     CXXInheritedCtorInitExpr *E) {
13201   QualType T = getDerived().TransformType(E->getType());
13202   if (T.isNull())
13203     return ExprError();
13204 
13205   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13206       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13207   if (!Constructor)
13208     return ExprError();
13209 
13210   if (!getDerived().AlwaysRebuild() &&
13211       T == E->getType() &&
13212       Constructor == E->getConstructor()) {
13213     // Mark the constructor as referenced.
13214     // FIXME: Instantiation-specific
13215     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13216     return E;
13217   }
13218 
13219   return getDerived().RebuildCXXInheritedCtorInitExpr(
13220       T, E->getLocation(), Constructor,
13221       E->constructsVBase(), E->inheritedFromVBase());
13222 }
13223 
13224 /// Transform a C++ temporary-binding expression.
13225 ///
13226 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
13227 /// transform the subexpression and return that.
13228 template<typename Derived>
13229 ExprResult
13230 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13231   if (auto *Dtor = E->getTemporary()->getDestructor())
13232     SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
13233                                    const_cast<CXXDestructorDecl *>(Dtor));
13234   return getDerived().TransformExpr(E->getSubExpr());
13235 }
13236 
13237 /// Transform a C++ expression that contains cleanups that should
13238 /// be run after the expression is evaluated.
13239 ///
13240 /// Since ExprWithCleanups nodes are implicitly generated, we
13241 /// just transform the subexpression and return that.
13242 template<typename Derived>
13243 ExprResult
13244 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
13245   return getDerived().TransformExpr(E->getSubExpr());
13246 }
13247 
13248 template<typename Derived>
13249 ExprResult
13250 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
13251                                                     CXXTemporaryObjectExpr *E) {
13252   TypeSourceInfo *T =
13253       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13254   if (!T)
13255     return ExprError();
13256 
13257   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13258       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13259   if (!Constructor)
13260     return ExprError();
13261 
13262   bool ArgumentChanged = false;
13263   SmallVector<Expr*, 8> Args;
13264   Args.reserve(E->getNumArgs());
13265   {
13266     EnterExpressionEvaluationContext Context(
13267         getSema(), EnterExpressionEvaluationContext::InitList,
13268         E->isListInitialization());
13269     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13270                        &ArgumentChanged))
13271       return ExprError();
13272   }
13273 
13274   if (!getDerived().AlwaysRebuild() &&
13275       T == E->getTypeSourceInfo() &&
13276       Constructor == E->getConstructor() &&
13277       !ArgumentChanged) {
13278     // FIXME: Instantiation-specific
13279     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13280     return SemaRef.MaybeBindToTemporary(E);
13281   }
13282 
13283   // FIXME: We should just pass E->isListInitialization(), but we're not
13284   // prepared to handle list-initialization without a child InitListExpr.
13285   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
13286   return getDerived().RebuildCXXTemporaryObjectExpr(
13287       T, LParenLoc, Args, E->getEndLoc(),
13288       /*ListInitialization=*/LParenLoc.isInvalid());
13289 }
13290 
13291 template<typename Derived>
13292 ExprResult
13293 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
13294   // Transform any init-capture expressions before entering the scope of the
13295   // lambda body, because they are not semantically within that scope.
13296   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
13297   struct TransformedInitCapture {
13298     // The location of the ... if the result is retaining a pack expansion.
13299     SourceLocation EllipsisLoc;
13300     // Zero or more expansions of the init-capture.
13301     SmallVector<InitCaptureInfoTy, 4> Expansions;
13302   };
13303   SmallVector<TransformedInitCapture, 4> InitCaptures;
13304   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
13305   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13306                                     CEnd = E->capture_end();
13307        C != CEnd; ++C) {
13308     if (!E->isInitCapture(C))
13309       continue;
13310 
13311     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
13312     auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13313 
13314     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
13315                                 std::optional<unsigned> NumExpansions) {
13316       ExprResult NewExprInitResult = getDerived().TransformInitializer(
13317           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
13318 
13319       if (NewExprInitResult.isInvalid()) {
13320         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13321         return;
13322       }
13323       Expr *NewExprInit = NewExprInitResult.get();
13324 
13325       QualType NewInitCaptureType =
13326           getSema().buildLambdaInitCaptureInitialization(
13327               C->getLocation(), C->getCaptureKind() == LCK_ByRef,
13328               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13329               cast<VarDecl>(C->getCapturedVar())->getInitStyle() !=
13330                   VarDecl::CInit,
13331               NewExprInit);
13332       Result.Expansions.push_back(
13333           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13334     };
13335 
13336     // If this is an init-capture pack, consider expanding the pack now.
13337     if (OldVD->isParameterPack()) {
13338       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13339                                              ->getTypeLoc()
13340                                              .castAs<PackExpansionTypeLoc>();
13341       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13342       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13343 
13344       // Determine whether the set of unexpanded parameter packs can and should
13345       // be expanded.
13346       bool Expand = true;
13347       bool RetainExpansion = false;
13348       std::optional<unsigned> OrigNumExpansions =
13349           ExpansionTL.getTypePtr()->getNumExpansions();
13350       std::optional<unsigned> NumExpansions = OrigNumExpansions;
13351       if (getDerived().TryExpandParameterPacks(
13352               ExpansionTL.getEllipsisLoc(),
13353               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13354               RetainExpansion, NumExpansions))
13355         return ExprError();
13356       if (Expand) {
13357         for (unsigned I = 0; I != *NumExpansions; ++I) {
13358           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13359           SubstInitCapture(SourceLocation(), std::nullopt);
13360         }
13361       }
13362       if (!Expand || RetainExpansion) {
13363         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13364         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13365         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13366       }
13367     } else {
13368       SubstInitCapture(SourceLocation(), std::nullopt);
13369     }
13370   }
13371 
13372   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13373   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13374 
13375   // Create the local class that will describe the lambda.
13376 
13377   // FIXME: DependencyKind below is wrong when substituting inside a templated
13378   // context that isn't a DeclContext (such as a variable template), or when
13379   // substituting an unevaluated lambda inside of a function's parameter's type
13380   // - as parameter types are not instantiated from within a function's DC. We
13381   // use evaluation contexts to distinguish the function parameter case.
13382   CXXRecordDecl::LambdaDependencyKind DependencyKind =
13383       CXXRecordDecl::LDK_Unknown;
13384   if ((getSema().isUnevaluatedContext() ||
13385        getSema().isConstantEvaluatedContext()) &&
13386       (getSema().CurContext->isFileContext() ||
13387        !getSema().CurContext->getParent()->isDependentContext()))
13388     DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13389 
13390   CXXRecordDecl *OldClass = E->getLambdaClass();
13391   CXXRecordDecl *Class = getSema().createLambdaClosureType(
13392       E->getIntroducerRange(), /*Info=*/nullptr, DependencyKind,
13393       E->getCaptureDefault());
13394   getDerived().transformedLocalDecl(OldClass, {Class});
13395 
13396   CXXMethodDecl *NewCallOperator =
13397       getSema().CreateLambdaCallOperator(E->getIntroducerRange(), Class);
13398   NewCallOperator->setLexicalDeclContext(getSema().CurContext);
13399 
13400   // Enter the scope of the lambda.
13401   getSema().buildLambdaScope(LSI, NewCallOperator, E->getIntroducerRange(),
13402                              E->getCaptureDefault(), E->getCaptureDefaultLoc(),
13403                              E->hasExplicitParameters(), E->isMutable());
13404 
13405   // Introduce the context of the call operator.
13406   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13407                                  /*NewThisContext*/false);
13408 
13409   bool Invalid = false;
13410 
13411   // Transform captures.
13412   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13413                                  CEnd = E->capture_end();
13414        C != CEnd; ++C) {
13415     // When we hit the first implicit capture, tell Sema that we've finished
13416     // the list of explicit captures.
13417     if (C->isImplicit())
13418       break;
13419 
13420     // Capturing 'this' is trivial.
13421     if (C->capturesThis()) {
13422       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13423                                     /*BuildAndDiagnose*/ true, nullptr,
13424                                     C->getCaptureKind() == LCK_StarThis);
13425       continue;
13426     }
13427     // Captured expression will be recaptured during captured variables
13428     // rebuilding.
13429     if (C->capturesVLAType())
13430       continue;
13431 
13432     // Rebuild init-captures, including the implied field declaration.
13433     if (E->isInitCapture(C)) {
13434       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13435 
13436       auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13437       llvm::SmallVector<Decl*, 4> NewVDs;
13438 
13439       for (InitCaptureInfoTy &Info : NewC.Expansions) {
13440         ExprResult Init = Info.first;
13441         QualType InitQualType = Info.second;
13442         if (Init.isInvalid() || InitQualType.isNull()) {
13443           Invalid = true;
13444           break;
13445         }
13446         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13447             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13448             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get(),
13449             getSema().CurContext);
13450         if (!NewVD) {
13451           Invalid = true;
13452           break;
13453         }
13454         NewVDs.push_back(NewVD);
13455         getSema().addInitCapture(LSI, NewVD, C->getCaptureKind() == LCK_ByRef);
13456       }
13457 
13458       if (Invalid)
13459         break;
13460 
13461       getDerived().transformedLocalDecl(OldVD, NewVDs);
13462       continue;
13463     }
13464 
13465     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13466 
13467     // Determine the capture kind for Sema.
13468     Sema::TryCaptureKind Kind
13469       = C->isImplicit()? Sema::TryCapture_Implicit
13470                        : C->getCaptureKind() == LCK_ByCopy
13471                            ? Sema::TryCapture_ExplicitByVal
13472                            : Sema::TryCapture_ExplicitByRef;
13473     SourceLocation EllipsisLoc;
13474     if (C->isPackExpansion()) {
13475       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13476       bool ShouldExpand = false;
13477       bool RetainExpansion = false;
13478       std::optional<unsigned> NumExpansions;
13479       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13480                                                C->getLocation(),
13481                                                Unexpanded,
13482                                                ShouldExpand, RetainExpansion,
13483                                                NumExpansions)) {
13484         Invalid = true;
13485         continue;
13486       }
13487 
13488       if (ShouldExpand) {
13489         // The transform has determined that we should perform an expansion;
13490         // transform and capture each of the arguments.
13491         // expansion of the pattern. Do so.
13492         auto *Pack = cast<VarDecl>(C->getCapturedVar());
13493         for (unsigned I = 0; I != *NumExpansions; ++I) {
13494           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13495           VarDecl *CapturedVar
13496             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13497                                                                Pack));
13498           if (!CapturedVar) {
13499             Invalid = true;
13500             continue;
13501           }
13502 
13503           // Capture the transformed variable.
13504           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13505         }
13506 
13507         // FIXME: Retain a pack expansion if RetainExpansion is true.
13508 
13509         continue;
13510       }
13511 
13512       EllipsisLoc = C->getEllipsisLoc();
13513     }
13514 
13515     // Transform the captured variable.
13516     auto *CapturedVar = cast_or_null<ValueDecl>(
13517         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13518     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13519       Invalid = true;
13520       continue;
13521     }
13522 
13523     // Capture the transformed variable.
13524     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13525                                  EllipsisLoc);
13526   }
13527   getSema().finishLambdaExplicitCaptures(LSI);
13528 
13529   // Transform the template parameters, and add them to the current
13530   // instantiation scope. The null case is handled correctly.
13531   auto TPL = getDerived().TransformTemplateParameterList(
13532       E->getTemplateParameterList());
13533   LSI->GLTemplateParameterList = TPL;
13534 
13535   // Transform the type of the original lambda's call operator.
13536   // The transformation MUST be done in the CurrentInstantiationScope since
13537   // it introduces a mapping of the original to the newly created
13538   // transformed parameters.
13539   TypeSourceInfo *NewCallOpTSI = nullptr;
13540   {
13541     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
13542     auto OldCallOpFPTL =
13543         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
13544 
13545     TypeLocBuilder NewCallOpTLBuilder;
13546     SmallVector<QualType, 4> ExceptionStorage;
13547     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
13548     QualType NewCallOpType = TransformFunctionProtoType(
13549         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
13550         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13551           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
13552                                               ExceptionStorage, Changed);
13553         });
13554     if (NewCallOpType.isNull())
13555       return ExprError();
13556     NewCallOpTSI =
13557         NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context, NewCallOpType);
13558   }
13559 
13560   getSema().CompleteLambdaCallOperator(
13561       NewCallOperator, E->getCallOperator()->getLocation(),
13562       E->getCallOperator()->getInnerLocStart(),
13563       E->getCallOperator()->getTrailingRequiresClause(), NewCallOpTSI,
13564       E->getCallOperator()->getConstexprKind(),
13565       E->getCallOperator()->getStorageClass(),
13566       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
13567       E->hasExplicitResultType());
13568 
13569   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13570   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13571 
13572   {
13573     // Number the lambda for linkage purposes if necessary.
13574     Sema::ContextRAII ManglingContext(getSema(), Class->getDeclContext());
13575 
13576     std::optional<CXXRecordDecl::LambdaNumbering> Numbering;
13577     if (getDerived().ReplacingOriginal()) {
13578       Numbering = OldClass->getLambdaNumbering();
13579     }
13580 
13581     getSema().handleLambdaNumbering(Class, NewCallOperator, Numbering);
13582   }
13583 
13584   // FIXME: Sema's lambda-building mechanism expects us to push an expression
13585   // evaluation context even if we're not transforming the function body.
13586   getSema().PushExpressionEvaluationContext(
13587       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13588 
13589   // Instantiate the body of the lambda expression.
13590   StmtResult Body =
13591       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13592 
13593   // ActOnLambda* will pop the function scope for us.
13594   FuncScopeCleanup.disable();
13595 
13596   if (Body.isInvalid()) {
13597     SavedContext.pop();
13598     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13599                                /*IsInstantiation=*/true);
13600     return ExprError();
13601   }
13602 
13603   // Copy the LSI before ActOnFinishFunctionBody removes it.
13604   // FIXME: This is dumb. Store the lambda information somewhere that outlives
13605   // the call operator.
13606   auto LSICopy = *LSI;
13607   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13608                                     /*IsInstantiation*/ true);
13609   SavedContext.pop();
13610 
13611   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13612                                    &LSICopy);
13613 }
13614 
13615 template<typename Derived>
13616 StmtResult
13617 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13618   return TransformStmt(S);
13619 }
13620 
13621 template<typename Derived>
13622 StmtResult
13623 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13624   // Transform captures.
13625   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13626                                  CEnd = E->capture_end();
13627        C != CEnd; ++C) {
13628     // When we hit the first implicit capture, tell Sema that we've finished
13629     // the list of explicit captures.
13630     if (!C->isImplicit())
13631       continue;
13632 
13633     // Capturing 'this' is trivial.
13634     if (C->capturesThis()) {
13635       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13636                                     /*BuildAndDiagnose*/ true, nullptr,
13637                                     C->getCaptureKind() == LCK_StarThis);
13638       continue;
13639     }
13640     // Captured expression will be recaptured during captured variables
13641     // rebuilding.
13642     if (C->capturesVLAType())
13643       continue;
13644 
13645     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13646     assert(!E->isInitCapture(C) && "implicit init-capture?");
13647 
13648     // Transform the captured variable.
13649     VarDecl *CapturedVar = cast_or_null<VarDecl>(
13650         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13651     if (!CapturedVar || CapturedVar->isInvalidDecl())
13652       return StmtError();
13653 
13654     // Capture the transformed variable.
13655     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13656   }
13657 
13658   return S;
13659 }
13660 
13661 template<typename Derived>
13662 ExprResult
13663 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13664                                                   CXXUnresolvedConstructExpr *E) {
13665   TypeSourceInfo *T =
13666       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13667   if (!T)
13668     return ExprError();
13669 
13670   bool ArgumentChanged = false;
13671   SmallVector<Expr*, 8> Args;
13672   Args.reserve(E->getNumArgs());
13673   {
13674     EnterExpressionEvaluationContext Context(
13675         getSema(), EnterExpressionEvaluationContext::InitList,
13676         E->isListInitialization());
13677     if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13678                                     &ArgumentChanged))
13679       return ExprError();
13680   }
13681 
13682   if (!getDerived().AlwaysRebuild() &&
13683       T == E->getTypeSourceInfo() &&
13684       !ArgumentChanged)
13685     return E;
13686 
13687   // FIXME: we're faking the locations of the commas
13688   return getDerived().RebuildCXXUnresolvedConstructExpr(
13689       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13690 }
13691 
13692 template<typename Derived>
13693 ExprResult
13694 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13695                                              CXXDependentScopeMemberExpr *E) {
13696   // Transform the base of the expression.
13697   ExprResult Base((Expr*) nullptr);
13698   Expr *OldBase;
13699   QualType BaseType;
13700   QualType ObjectType;
13701   if (!E->isImplicitAccess()) {
13702     OldBase = E->getBase();
13703     Base = getDerived().TransformExpr(OldBase);
13704     if (Base.isInvalid())
13705       return ExprError();
13706 
13707     // Start the member reference and compute the object's type.
13708     ParsedType ObjectTy;
13709     bool MayBePseudoDestructor = false;
13710     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13711                                                 E->getOperatorLoc(),
13712                                       E->isArrow()? tok::arrow : tok::period,
13713                                                 ObjectTy,
13714                                                 MayBePseudoDestructor);
13715     if (Base.isInvalid())
13716       return ExprError();
13717 
13718     ObjectType = ObjectTy.get();
13719     BaseType = ((Expr*) Base.get())->getType();
13720   } else {
13721     OldBase = nullptr;
13722     BaseType = getDerived().TransformType(E->getBaseType());
13723     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13724   }
13725 
13726   // Transform the first part of the nested-name-specifier that qualifies
13727   // the member name.
13728   NamedDecl *FirstQualifierInScope
13729     = getDerived().TransformFirstQualifierInScope(
13730                                             E->getFirstQualifierFoundInScope(),
13731                                             E->getQualifierLoc().getBeginLoc());
13732 
13733   NestedNameSpecifierLoc QualifierLoc;
13734   if (E->getQualifier()) {
13735     QualifierLoc
13736       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13737                                                      ObjectType,
13738                                                      FirstQualifierInScope);
13739     if (!QualifierLoc)
13740       return ExprError();
13741   }
13742 
13743   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13744 
13745   // TODO: If this is a conversion-function-id, verify that the
13746   // destination type name (if present) resolves the same way after
13747   // instantiation as it did in the local scope.
13748 
13749   DeclarationNameInfo NameInfo
13750     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13751   if (!NameInfo.getName())
13752     return ExprError();
13753 
13754   if (!E->hasExplicitTemplateArgs()) {
13755     // This is a reference to a member without an explicitly-specified
13756     // template argument list. Optimize for this common case.
13757     if (!getDerived().AlwaysRebuild() &&
13758         Base.get() == OldBase &&
13759         BaseType == E->getBaseType() &&
13760         QualifierLoc == E->getQualifierLoc() &&
13761         NameInfo.getName() == E->getMember() &&
13762         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13763       return E;
13764 
13765     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13766                                                        BaseType,
13767                                                        E->isArrow(),
13768                                                        E->getOperatorLoc(),
13769                                                        QualifierLoc,
13770                                                        TemplateKWLoc,
13771                                                        FirstQualifierInScope,
13772                                                        NameInfo,
13773                                                        /*TemplateArgs*/nullptr);
13774   }
13775 
13776   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13777   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13778                                               E->getNumTemplateArgs(),
13779                                               TransArgs))
13780     return ExprError();
13781 
13782   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13783                                                      BaseType,
13784                                                      E->isArrow(),
13785                                                      E->getOperatorLoc(),
13786                                                      QualifierLoc,
13787                                                      TemplateKWLoc,
13788                                                      FirstQualifierInScope,
13789                                                      NameInfo,
13790                                                      &TransArgs);
13791 }
13792 
13793 template <typename Derived>
13794 ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13795     UnresolvedMemberExpr *Old) {
13796   // Transform the base of the expression.
13797   ExprResult Base((Expr *)nullptr);
13798   QualType BaseType;
13799   if (!Old->isImplicitAccess()) {
13800     Base = getDerived().TransformExpr(Old->getBase());
13801     if (Base.isInvalid())
13802       return ExprError();
13803     Base =
13804         getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13805     if (Base.isInvalid())
13806       return ExprError();
13807     BaseType = Base.get()->getType();
13808   } else {
13809     BaseType = getDerived().TransformType(Old->getBaseType());
13810   }
13811 
13812   NestedNameSpecifierLoc QualifierLoc;
13813   if (Old->getQualifierLoc()) {
13814     QualifierLoc =
13815         getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13816     if (!QualifierLoc)
13817       return ExprError();
13818   }
13819 
13820   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13821 
13822   LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13823 
13824   // Transform the declaration set.
13825   if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13826     return ExprError();
13827 
13828   // Determine the naming class.
13829   if (Old->getNamingClass()) {
13830     CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13831         getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13832     if (!NamingClass)
13833       return ExprError();
13834 
13835     R.setNamingClass(NamingClass);
13836   }
13837 
13838   TemplateArgumentListInfo TransArgs;
13839   if (Old->hasExplicitTemplateArgs()) {
13840     TransArgs.setLAngleLoc(Old->getLAngleLoc());
13841     TransArgs.setRAngleLoc(Old->getRAngleLoc());
13842     if (getDerived().TransformTemplateArguments(
13843             Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13844       return ExprError();
13845   }
13846 
13847   // FIXME: to do this check properly, we will need to preserve the
13848   // first-qualifier-in-scope here, just in case we had a dependent
13849   // base (and therefore couldn't do the check) and a
13850   // nested-name-qualifier (and therefore could do the lookup).
13851   NamedDecl *FirstQualifierInScope = nullptr;
13852 
13853   return getDerived().RebuildUnresolvedMemberExpr(
13854       Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13855       TemplateKWLoc, FirstQualifierInScope, R,
13856       (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13857 }
13858 
13859 template<typename Derived>
13860 ExprResult
13861 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13862   EnterExpressionEvaluationContext Unevaluated(
13863       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13864   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13865   if (SubExpr.isInvalid())
13866     return ExprError();
13867 
13868   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13869     return E;
13870 
13871   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13872 }
13873 
13874 template<typename Derived>
13875 ExprResult
13876 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13877   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13878   if (Pattern.isInvalid())
13879     return ExprError();
13880 
13881   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13882     return E;
13883 
13884   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13885                                            E->getNumExpansions());
13886 }
13887 
13888 template<typename Derived>
13889 ExprResult
13890 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13891   // If E is not value-dependent, then nothing will change when we transform it.
13892   // Note: This is an instantiation-centric view.
13893   if (!E->isValueDependent())
13894     return E;
13895 
13896   EnterExpressionEvaluationContext Unevaluated(
13897       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13898 
13899   ArrayRef<TemplateArgument> PackArgs;
13900   TemplateArgument ArgStorage;
13901 
13902   // Find the argument list to transform.
13903   if (E->isPartiallySubstituted()) {
13904     PackArgs = E->getPartialArguments();
13905   } else if (E->isValueDependent()) {
13906     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13907     bool ShouldExpand = false;
13908     bool RetainExpansion = false;
13909     std::optional<unsigned> NumExpansions;
13910     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13911                                              Unexpanded,
13912                                              ShouldExpand, RetainExpansion,
13913                                              NumExpansions))
13914       return ExprError();
13915 
13916     // If we need to expand the pack, build a template argument from it and
13917     // expand that.
13918     if (ShouldExpand) {
13919       auto *Pack = E->getPack();
13920       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13921         ArgStorage = getSema().Context.getPackExpansionType(
13922             getSema().Context.getTypeDeclType(TTPD), std::nullopt);
13923       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13924         ArgStorage = TemplateArgument(TemplateName(TTPD), std::nullopt);
13925       } else {
13926         auto *VD = cast<ValueDecl>(Pack);
13927         ExprResult DRE = getSema().BuildDeclRefExpr(
13928             VD, VD->getType().getNonLValueExprType(getSema().Context),
13929             VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13930             E->getPackLoc());
13931         if (DRE.isInvalid())
13932           return ExprError();
13933         ArgStorage = new (getSema().Context)
13934             PackExpansionExpr(getSema().Context.DependentTy, DRE.get(),
13935                               E->getPackLoc(), std::nullopt);
13936       }
13937       PackArgs = ArgStorage;
13938     }
13939   }
13940 
13941   // If we're not expanding the pack, just transform the decl.
13942   if (!PackArgs.size()) {
13943     auto *Pack = cast_or_null<NamedDecl>(
13944         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13945     if (!Pack)
13946       return ExprError();
13947     return getDerived().RebuildSizeOfPackExpr(
13948         E->getOperatorLoc(), Pack, E->getPackLoc(), E->getRParenLoc(),
13949         std::nullopt, std::nullopt);
13950   }
13951 
13952   // Try to compute the result without performing a partial substitution.
13953   std::optional<unsigned> Result = 0;
13954   for (const TemplateArgument &Arg : PackArgs) {
13955     if (!Arg.isPackExpansion()) {
13956       Result = *Result + 1;
13957       continue;
13958     }
13959 
13960     TemplateArgumentLoc ArgLoc;
13961     InventTemplateArgumentLoc(Arg, ArgLoc);
13962 
13963     // Find the pattern of the pack expansion.
13964     SourceLocation Ellipsis;
13965     std::optional<unsigned> OrigNumExpansions;
13966     TemplateArgumentLoc Pattern =
13967         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13968                                                           OrigNumExpansions);
13969 
13970     // Substitute under the pack expansion. Do not expand the pack (yet).
13971     TemplateArgumentLoc OutPattern;
13972     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13973     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13974                                                /*Uneval*/ true))
13975       return true;
13976 
13977     // See if we can determine the number of arguments from the result.
13978     std::optional<unsigned> NumExpansions =
13979         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13980     if (!NumExpansions) {
13981       // No: we must be in an alias template expansion, and we're going to need
13982       // to actually expand the packs.
13983       Result = std::nullopt;
13984       break;
13985     }
13986 
13987     Result = *Result + *NumExpansions;
13988   }
13989 
13990   // Common case: we could determine the number of expansions without
13991   // substituting.
13992   if (Result)
13993     return getDerived().RebuildSizeOfPackExpr(
13994         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13995         *Result, std::nullopt);
13996 
13997   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13998                                                E->getPackLoc());
13999   {
14000     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
14001     typedef TemplateArgumentLocInventIterator<
14002         Derived, const TemplateArgument*> PackLocIterator;
14003     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
14004                                    PackLocIterator(*this, PackArgs.end()),
14005                                    TransformedPackArgs, /*Uneval*/true))
14006       return ExprError();
14007   }
14008 
14009   // Check whether we managed to fully-expand the pack.
14010   // FIXME: Is it possible for us to do so and not hit the early exit path?
14011   SmallVector<TemplateArgument, 8> Args;
14012   bool PartialSubstitution = false;
14013   for (auto &Loc : TransformedPackArgs.arguments()) {
14014     Args.push_back(Loc.getArgument());
14015     if (Loc.getArgument().isPackExpansion())
14016       PartialSubstitution = true;
14017   }
14018 
14019   if (PartialSubstitution)
14020     return getDerived().RebuildSizeOfPackExpr(
14021         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
14022         std::nullopt, Args);
14023 
14024   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
14025                                             E->getPackLoc(), E->getRParenLoc(),
14026                                             Args.size(), std::nullopt);
14027 }
14028 
14029 template<typename Derived>
14030 ExprResult
14031 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
14032                                           SubstNonTypeTemplateParmPackExpr *E) {
14033   // Default behavior is to do nothing with this transformation.
14034   return E;
14035 }
14036 
14037 template<typename Derived>
14038 ExprResult
14039 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
14040                                           SubstNonTypeTemplateParmExpr *E) {
14041   // Default behavior is to do nothing with this transformation.
14042   return E;
14043 }
14044 
14045 template<typename Derived>
14046 ExprResult
14047 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
14048   // Default behavior is to do nothing with this transformation.
14049   return E;
14050 }
14051 
14052 template<typename Derived>
14053 ExprResult
14054 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
14055                                                   MaterializeTemporaryExpr *E) {
14056   return getDerived().TransformExpr(E->getSubExpr());
14057 }
14058 
14059 template<typename Derived>
14060 ExprResult
14061 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
14062   UnresolvedLookupExpr *Callee = nullptr;
14063   if (Expr *OldCallee = E->getCallee()) {
14064     ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
14065     if (CalleeResult.isInvalid())
14066       return ExprError();
14067     Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
14068   }
14069 
14070   Expr *Pattern = E->getPattern();
14071 
14072   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14073   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
14074   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
14075 
14076   // Determine whether the set of unexpanded parameter packs can and should
14077   // be expanded.
14078   bool Expand = true;
14079   bool RetainExpansion = false;
14080   std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
14081                           NumExpansions = OrigNumExpansions;
14082   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
14083                                            Pattern->getSourceRange(),
14084                                            Unexpanded,
14085                                            Expand, RetainExpansion,
14086                                            NumExpansions))
14087     return true;
14088 
14089   if (!Expand) {
14090     // Do not expand any packs here, just transform and rebuild a fold
14091     // expression.
14092     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14093 
14094     ExprResult LHS =
14095         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
14096     if (LHS.isInvalid())
14097       return true;
14098 
14099     ExprResult RHS =
14100         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
14101     if (RHS.isInvalid())
14102       return true;
14103 
14104     if (!getDerived().AlwaysRebuild() &&
14105         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
14106       return E;
14107 
14108     return getDerived().RebuildCXXFoldExpr(
14109         Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
14110         E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
14111   }
14112 
14113   // Formally a fold expression expands to nested parenthesized expressions.
14114   // Enforce this limit to avoid creating trees so deep we can't safely traverse
14115   // them.
14116   if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
14117     SemaRef.Diag(E->getEllipsisLoc(),
14118                  clang::diag::err_fold_expression_limit_exceeded)
14119         << *NumExpansions << SemaRef.getLangOpts().BracketDepth
14120         << E->getSourceRange();
14121     SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
14122     return ExprError();
14123   }
14124 
14125   // The transform has determined that we should perform an elementwise
14126   // expansion of the pattern. Do so.
14127   ExprResult Result = getDerived().TransformExpr(E->getInit());
14128   if (Result.isInvalid())
14129     return true;
14130   bool LeftFold = E->isLeftFold();
14131 
14132   // If we're retaining an expansion for a right fold, it is the innermost
14133   // component and takes the init (if any).
14134   if (!LeftFold && RetainExpansion) {
14135     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14136 
14137     ExprResult Out = getDerived().TransformExpr(Pattern);
14138     if (Out.isInvalid())
14139       return true;
14140 
14141     Result = getDerived().RebuildCXXFoldExpr(
14142         Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
14143         E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
14144     if (Result.isInvalid())
14145       return true;
14146   }
14147 
14148   for (unsigned I = 0; I != *NumExpansions; ++I) {
14149     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
14150         getSema(), LeftFold ? I : *NumExpansions - I - 1);
14151     ExprResult Out = getDerived().TransformExpr(Pattern);
14152     if (Out.isInvalid())
14153       return true;
14154 
14155     if (Out.get()->containsUnexpandedParameterPack()) {
14156       // We still have a pack; retain a pack expansion for this slice.
14157       Result = getDerived().RebuildCXXFoldExpr(
14158           Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
14159           E->getOperator(), E->getEllipsisLoc(),
14160           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
14161           OrigNumExpansions);
14162     } else if (Result.isUsable()) {
14163       // We've got down to a single element; build a binary operator.
14164       Expr *LHS = LeftFold ? Result.get() : Out.get();
14165       Expr *RHS = LeftFold ? Out.get() : Result.get();
14166       if (Callee) {
14167         UnresolvedSet<16> Functions;
14168         Functions.append(Callee->decls_begin(), Callee->decls_end());
14169         Result = getDerived().RebuildCXXOperatorCallExpr(
14170             BinaryOperator::getOverloadedOperator(E->getOperator()),
14171             E->getEllipsisLoc(), Callee->getBeginLoc(), Callee->requiresADL(),
14172             Functions, LHS, RHS);
14173       } else {
14174         Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
14175                                                     E->getOperator(), LHS, RHS);
14176       }
14177     } else
14178       Result = Out;
14179 
14180     if (Result.isInvalid())
14181       return true;
14182   }
14183 
14184   // If we're retaining an expansion for a left fold, it is the outermost
14185   // component and takes the complete expansion so far as its init (if any).
14186   if (LeftFold && RetainExpansion) {
14187     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14188 
14189     ExprResult Out = getDerived().TransformExpr(Pattern);
14190     if (Out.isInvalid())
14191       return true;
14192 
14193     Result = getDerived().RebuildCXXFoldExpr(
14194         Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
14195         E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
14196     if (Result.isInvalid())
14197       return true;
14198   }
14199 
14200   // If we had no init and an empty pack, and we're not retaining an expansion,
14201   // then produce a fallback value or error.
14202   if (Result.isUnset())
14203     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
14204                                                 E->getOperator());
14205 
14206   return Result;
14207 }
14208 
14209 template <typename Derived>
14210 ExprResult
14211 TreeTransform<Derived>::TransformCXXParenListInitExpr(CXXParenListInitExpr *E) {
14212   SmallVector<Expr *, 4> TransformedInits;
14213   ArrayRef<Expr *> InitExprs = E->getInitExprs();
14214   if (TransformExprs(InitExprs.data(), InitExprs.size(), true,
14215                      TransformedInits))
14216     return ExprError();
14217 
14218   return getDerived().RebuildParenListExpr(E->getBeginLoc(), TransformedInits,
14219                                            E->getEndLoc());
14220 }
14221 
14222 template<typename Derived>
14223 ExprResult
14224 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
14225     CXXStdInitializerListExpr *E) {
14226   return getDerived().TransformExpr(E->getSubExpr());
14227 }
14228 
14229 template<typename Derived>
14230 ExprResult
14231 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
14232   return SemaRef.MaybeBindToTemporary(E);
14233 }
14234 
14235 template<typename Derived>
14236 ExprResult
14237 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
14238   return E;
14239 }
14240 
14241 template<typename Derived>
14242 ExprResult
14243 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
14244   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
14245   if (SubExpr.isInvalid())
14246     return ExprError();
14247 
14248   if (!getDerived().AlwaysRebuild() &&
14249       SubExpr.get() == E->getSubExpr())
14250     return E;
14251 
14252   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
14253 }
14254 
14255 template<typename Derived>
14256 ExprResult
14257 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
14258   // Transform each of the elements.
14259   SmallVector<Expr *, 8> Elements;
14260   bool ArgChanged = false;
14261   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
14262                                   /*IsCall=*/false, Elements, &ArgChanged))
14263     return ExprError();
14264 
14265   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14266     return SemaRef.MaybeBindToTemporary(E);
14267 
14268   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
14269                                               Elements.data(),
14270                                               Elements.size());
14271 }
14272 
14273 template<typename Derived>
14274 ExprResult
14275 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
14276                                                     ObjCDictionaryLiteral *E) {
14277   // Transform each of the elements.
14278   SmallVector<ObjCDictionaryElement, 8> Elements;
14279   bool ArgChanged = false;
14280   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
14281     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
14282 
14283     if (OrigElement.isPackExpansion()) {
14284       // This key/value element is a pack expansion.
14285       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14286       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
14287       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
14288       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
14289 
14290       // Determine whether the set of unexpanded parameter packs can
14291       // and should be expanded.
14292       bool Expand = true;
14293       bool RetainExpansion = false;
14294       std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
14295       std::optional<unsigned> NumExpansions = OrigNumExpansions;
14296       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
14297                                OrigElement.Value->getEndLoc());
14298       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
14299                                                PatternRange, Unexpanded, Expand,
14300                                                RetainExpansion, NumExpansions))
14301         return ExprError();
14302 
14303       if (!Expand) {
14304         // The transform has determined that we should perform a simple
14305         // transformation on the pack expansion, producing another pack
14306         // expansion.
14307         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14308         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14309         if (Key.isInvalid())
14310           return ExprError();
14311 
14312         if (Key.get() != OrigElement.Key)
14313           ArgChanged = true;
14314 
14315         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14316         if (Value.isInvalid())
14317           return ExprError();
14318 
14319         if (Value.get() != OrigElement.Value)
14320           ArgChanged = true;
14321 
14322         ObjCDictionaryElement Expansion = {
14323           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
14324         };
14325         Elements.push_back(Expansion);
14326         continue;
14327       }
14328 
14329       // Record right away that the argument was changed.  This needs
14330       // to happen even if the array expands to nothing.
14331       ArgChanged = true;
14332 
14333       // The transform has determined that we should perform an elementwise
14334       // expansion of the pattern. Do so.
14335       for (unsigned I = 0; I != *NumExpansions; ++I) {
14336         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14337         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14338         if (Key.isInvalid())
14339           return ExprError();
14340 
14341         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14342         if (Value.isInvalid())
14343           return ExprError();
14344 
14345         ObjCDictionaryElement Element = {
14346           Key.get(), Value.get(), SourceLocation(), NumExpansions
14347         };
14348 
14349         // If any unexpanded parameter packs remain, we still have a
14350         // pack expansion.
14351         // FIXME: Can this really happen?
14352         if (Key.get()->containsUnexpandedParameterPack() ||
14353             Value.get()->containsUnexpandedParameterPack())
14354           Element.EllipsisLoc = OrigElement.EllipsisLoc;
14355 
14356         Elements.push_back(Element);
14357       }
14358 
14359       // FIXME: Retain a pack expansion if RetainExpansion is true.
14360 
14361       // We've finished with this pack expansion.
14362       continue;
14363     }
14364 
14365     // Transform and check key.
14366     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14367     if (Key.isInvalid())
14368       return ExprError();
14369 
14370     if (Key.get() != OrigElement.Key)
14371       ArgChanged = true;
14372 
14373     // Transform and check value.
14374     ExprResult Value
14375       = getDerived().TransformExpr(OrigElement.Value);
14376     if (Value.isInvalid())
14377       return ExprError();
14378 
14379     if (Value.get() != OrigElement.Value)
14380       ArgChanged = true;
14381 
14382     ObjCDictionaryElement Element = {Key.get(), Value.get(), SourceLocation(),
14383                                      std::nullopt};
14384     Elements.push_back(Element);
14385   }
14386 
14387   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14388     return SemaRef.MaybeBindToTemporary(E);
14389 
14390   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14391                                                    Elements);
14392 }
14393 
14394 template<typename Derived>
14395 ExprResult
14396 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14397   TypeSourceInfo *EncodedTypeInfo
14398     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14399   if (!EncodedTypeInfo)
14400     return ExprError();
14401 
14402   if (!getDerived().AlwaysRebuild() &&
14403       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14404     return E;
14405 
14406   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14407                                             EncodedTypeInfo,
14408                                             E->getRParenLoc());
14409 }
14410 
14411 template<typename Derived>
14412 ExprResult TreeTransform<Derived>::
14413 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14414   // This is a kind of implicit conversion, and it needs to get dropped
14415   // and recomputed for the same general reasons that ImplicitCastExprs
14416   // do, as well a more specific one: this expression is only valid when
14417   // it appears *immediately* as an argument expression.
14418   return getDerived().TransformExpr(E->getSubExpr());
14419 }
14420 
14421 template<typename Derived>
14422 ExprResult TreeTransform<Derived>::
14423 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14424   TypeSourceInfo *TSInfo
14425     = getDerived().TransformType(E->getTypeInfoAsWritten());
14426   if (!TSInfo)
14427     return ExprError();
14428 
14429   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14430   if (Result.isInvalid())
14431     return ExprError();
14432 
14433   if (!getDerived().AlwaysRebuild() &&
14434       TSInfo == E->getTypeInfoAsWritten() &&
14435       Result.get() == E->getSubExpr())
14436     return E;
14437 
14438   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14439                                       E->getBridgeKeywordLoc(), TSInfo,
14440                                       Result.get());
14441 }
14442 
14443 template <typename Derived>
14444 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14445     ObjCAvailabilityCheckExpr *E) {
14446   return E;
14447 }
14448 
14449 template<typename Derived>
14450 ExprResult
14451 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14452   // Transform arguments.
14453   bool ArgChanged = false;
14454   SmallVector<Expr*, 8> Args;
14455   Args.reserve(E->getNumArgs());
14456   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14457                                   &ArgChanged))
14458     return ExprError();
14459 
14460   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14461     // Class message: transform the receiver type.
14462     TypeSourceInfo *ReceiverTypeInfo
14463       = getDerived().TransformType(E->getClassReceiverTypeInfo());
14464     if (!ReceiverTypeInfo)
14465       return ExprError();
14466 
14467     // If nothing changed, just retain the existing message send.
14468     if (!getDerived().AlwaysRebuild() &&
14469         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14470       return SemaRef.MaybeBindToTemporary(E);
14471 
14472     // Build a new class message send.
14473     SmallVector<SourceLocation, 16> SelLocs;
14474     E->getSelectorLocs(SelLocs);
14475     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14476                                                E->getSelector(),
14477                                                SelLocs,
14478                                                E->getMethodDecl(),
14479                                                E->getLeftLoc(),
14480                                                Args,
14481                                                E->getRightLoc());
14482   }
14483   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14484            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14485     if (!E->getMethodDecl())
14486       return ExprError();
14487 
14488     // Build a new class message send to 'super'.
14489     SmallVector<SourceLocation, 16> SelLocs;
14490     E->getSelectorLocs(SelLocs);
14491     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14492                                                E->getSelector(),
14493                                                SelLocs,
14494                                                E->getReceiverType(),
14495                                                E->getMethodDecl(),
14496                                                E->getLeftLoc(),
14497                                                Args,
14498                                                E->getRightLoc());
14499   }
14500 
14501   // Instance message: transform the receiver
14502   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
14503          "Only class and instance messages may be instantiated");
14504   ExprResult Receiver
14505     = getDerived().TransformExpr(E->getInstanceReceiver());
14506   if (Receiver.isInvalid())
14507     return ExprError();
14508 
14509   // If nothing changed, just retain the existing message send.
14510   if (!getDerived().AlwaysRebuild() &&
14511       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14512     return SemaRef.MaybeBindToTemporary(E);
14513 
14514   // Build a new instance message send.
14515   SmallVector<SourceLocation, 16> SelLocs;
14516   E->getSelectorLocs(SelLocs);
14517   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14518                                              E->getSelector(),
14519                                              SelLocs,
14520                                              E->getMethodDecl(),
14521                                              E->getLeftLoc(),
14522                                              Args,
14523                                              E->getRightLoc());
14524 }
14525 
14526 template<typename Derived>
14527 ExprResult
14528 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14529   return E;
14530 }
14531 
14532 template<typename Derived>
14533 ExprResult
14534 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14535   return E;
14536 }
14537 
14538 template<typename Derived>
14539 ExprResult
14540 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14541   // Transform the base expression.
14542   ExprResult Base = getDerived().TransformExpr(E->getBase());
14543   if (Base.isInvalid())
14544     return ExprError();
14545 
14546   // We don't need to transform the ivar; it will never change.
14547 
14548   // If nothing changed, just retain the existing expression.
14549   if (!getDerived().AlwaysRebuild() &&
14550       Base.get() == E->getBase())
14551     return E;
14552 
14553   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14554                                              E->getLocation(),
14555                                              E->isArrow(), E->isFreeIvar());
14556 }
14557 
14558 template<typename Derived>
14559 ExprResult
14560 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14561   // 'super' and types never change. Property never changes. Just
14562   // retain the existing expression.
14563   if (!E->isObjectReceiver())
14564     return E;
14565 
14566   // Transform the base expression.
14567   ExprResult Base = getDerived().TransformExpr(E->getBase());
14568   if (Base.isInvalid())
14569     return ExprError();
14570 
14571   // We don't need to transform the property; it will never change.
14572 
14573   // If nothing changed, just retain the existing expression.
14574   if (!getDerived().AlwaysRebuild() &&
14575       Base.get() == E->getBase())
14576     return E;
14577 
14578   if (E->isExplicitProperty())
14579     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14580                                                    E->getExplicitProperty(),
14581                                                    E->getLocation());
14582 
14583   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14584                                                  SemaRef.Context.PseudoObjectTy,
14585                                                  E->getImplicitPropertyGetter(),
14586                                                  E->getImplicitPropertySetter(),
14587                                                  E->getLocation());
14588 }
14589 
14590 template<typename Derived>
14591 ExprResult
14592 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14593   // Transform the base expression.
14594   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14595   if (Base.isInvalid())
14596     return ExprError();
14597 
14598   // Transform the key expression.
14599   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14600   if (Key.isInvalid())
14601     return ExprError();
14602 
14603   // If nothing changed, just retain the existing expression.
14604   if (!getDerived().AlwaysRebuild() &&
14605       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14606     return E;
14607 
14608   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14609                                                   Base.get(), Key.get(),
14610                                                   E->getAtIndexMethodDecl(),
14611                                                   E->setAtIndexMethodDecl());
14612 }
14613 
14614 template<typename Derived>
14615 ExprResult
14616 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14617   // Transform the base expression.
14618   ExprResult Base = getDerived().TransformExpr(E->getBase());
14619   if (Base.isInvalid())
14620     return ExprError();
14621 
14622   // If nothing changed, just retain the existing expression.
14623   if (!getDerived().AlwaysRebuild() &&
14624       Base.get() == E->getBase())
14625     return E;
14626 
14627   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14628                                          E->getOpLoc(),
14629                                          E->isArrow());
14630 }
14631 
14632 template<typename Derived>
14633 ExprResult
14634 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14635   bool ArgumentChanged = false;
14636   SmallVector<Expr*, 8> SubExprs;
14637   SubExprs.reserve(E->getNumSubExprs());
14638   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14639                                   SubExprs, &ArgumentChanged))
14640     return ExprError();
14641 
14642   if (!getDerived().AlwaysRebuild() &&
14643       !ArgumentChanged)
14644     return E;
14645 
14646   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14647                                                SubExprs,
14648                                                E->getRParenLoc());
14649 }
14650 
14651 template<typename Derived>
14652 ExprResult
14653 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14654   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14655   if (SrcExpr.isInvalid())
14656     return ExprError();
14657 
14658   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14659   if (!Type)
14660     return ExprError();
14661 
14662   if (!getDerived().AlwaysRebuild() &&
14663       Type == E->getTypeSourceInfo() &&
14664       SrcExpr.get() == E->getSrcExpr())
14665     return E;
14666 
14667   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14668                                                SrcExpr.get(), Type,
14669                                                E->getRParenLoc());
14670 }
14671 
14672 template<typename Derived>
14673 ExprResult
14674 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14675   BlockDecl *oldBlock = E->getBlockDecl();
14676 
14677   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14678   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14679 
14680   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14681   blockScope->TheDecl->setBlockMissingReturnType(
14682                          oldBlock->blockMissingReturnType());
14683 
14684   SmallVector<ParmVarDecl*, 4> params;
14685   SmallVector<QualType, 4> paramTypes;
14686 
14687   const FunctionProtoType *exprFunctionType = E->getFunctionType();
14688 
14689   // Parameter substitution.
14690   Sema::ExtParameterInfoBuilder extParamInfos;
14691   if (getDerived().TransformFunctionTypeParams(
14692           E->getCaretLocation(), oldBlock->parameters(), nullptr,
14693           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14694           extParamInfos)) {
14695     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14696     return ExprError();
14697   }
14698 
14699   QualType exprResultType =
14700       getDerived().TransformType(exprFunctionType->getReturnType());
14701 
14702   auto epi = exprFunctionType->getExtProtoInfo();
14703   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14704 
14705   QualType functionType =
14706     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14707   blockScope->FunctionType = functionType;
14708 
14709   // Set the parameters on the block decl.
14710   if (!params.empty())
14711     blockScope->TheDecl->setParams(params);
14712 
14713   if (!oldBlock->blockMissingReturnType()) {
14714     blockScope->HasImplicitReturnType = false;
14715     blockScope->ReturnType = exprResultType;
14716   }
14717 
14718   // Transform the body
14719   StmtResult body = getDerived().TransformStmt(E->getBody());
14720   if (body.isInvalid()) {
14721     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14722     return ExprError();
14723   }
14724 
14725 #ifndef NDEBUG
14726   // In builds with assertions, make sure that we captured everything we
14727   // captured before.
14728   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14729     for (const auto &I : oldBlock->captures()) {
14730       VarDecl *oldCapture = I.getVariable();
14731 
14732       // Ignore parameter packs.
14733       if (oldCapture->isParameterPack())
14734         continue;
14735 
14736       VarDecl *newCapture =
14737         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14738                                                  oldCapture));
14739       assert(blockScope->CaptureMap.count(newCapture));
14740     }
14741 
14742     // The this pointer may not be captured by the instantiated block, even when
14743     // it's captured by the original block, if the expression causing the
14744     // capture is in the discarded branch of a constexpr if statement.
14745     assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&
14746            "this pointer isn't captured in the old block");
14747   }
14748 #endif
14749 
14750   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14751                                     /*Scope=*/nullptr);
14752 }
14753 
14754 template<typename Derived>
14755 ExprResult
14756 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14757   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14758   if (SrcExpr.isInvalid())
14759     return ExprError();
14760 
14761   QualType Type = getDerived().TransformType(E->getType());
14762 
14763   return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14764                                  E->getRParenLoc());
14765 }
14766 
14767 template<typename Derived>
14768 ExprResult
14769 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14770   bool ArgumentChanged = false;
14771   SmallVector<Expr*, 8> SubExprs;
14772   SubExprs.reserve(E->getNumSubExprs());
14773   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14774                                   SubExprs, &ArgumentChanged))
14775     return ExprError();
14776 
14777   if (!getDerived().AlwaysRebuild() &&
14778       !ArgumentChanged)
14779     return E;
14780 
14781   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14782                                         E->getOp(), E->getRParenLoc());
14783 }
14784 
14785 //===----------------------------------------------------------------------===//
14786 // Type reconstruction
14787 //===----------------------------------------------------------------------===//
14788 
14789 template<typename Derived>
14790 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14791                                                     SourceLocation Star) {
14792   return SemaRef.BuildPointerType(PointeeType, Star,
14793                                   getDerived().getBaseEntity());
14794 }
14795 
14796 template<typename Derived>
14797 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14798                                                          SourceLocation Star) {
14799   return SemaRef.BuildBlockPointerType(PointeeType, Star,
14800                                        getDerived().getBaseEntity());
14801 }
14802 
14803 template<typename Derived>
14804 QualType
14805 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14806                                              bool WrittenAsLValue,
14807                                              SourceLocation Sigil) {
14808   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14809                                     Sigil, getDerived().getBaseEntity());
14810 }
14811 
14812 template<typename Derived>
14813 QualType
14814 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14815                                                  QualType ClassType,
14816                                                  SourceLocation Sigil) {
14817   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14818                                         getDerived().getBaseEntity());
14819 }
14820 
14821 template<typename Derived>
14822 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14823            const ObjCTypeParamDecl *Decl,
14824            SourceLocation ProtocolLAngleLoc,
14825            ArrayRef<ObjCProtocolDecl *> Protocols,
14826            ArrayRef<SourceLocation> ProtocolLocs,
14827            SourceLocation ProtocolRAngleLoc) {
14828   return SemaRef.BuildObjCTypeParamType(Decl,
14829                                         ProtocolLAngleLoc, Protocols,
14830                                         ProtocolLocs, ProtocolRAngleLoc,
14831                                         /*FailOnError=*/true);
14832 }
14833 
14834 template<typename Derived>
14835 QualType TreeTransform<Derived>::RebuildObjCObjectType(
14836            QualType BaseType,
14837            SourceLocation Loc,
14838            SourceLocation TypeArgsLAngleLoc,
14839            ArrayRef<TypeSourceInfo *> TypeArgs,
14840            SourceLocation TypeArgsRAngleLoc,
14841            SourceLocation ProtocolLAngleLoc,
14842            ArrayRef<ObjCProtocolDecl *> Protocols,
14843            ArrayRef<SourceLocation> ProtocolLocs,
14844            SourceLocation ProtocolRAngleLoc) {
14845   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc, TypeArgs,
14846                                      TypeArgsRAngleLoc, ProtocolLAngleLoc,
14847                                      Protocols, ProtocolLocs, ProtocolRAngleLoc,
14848                                      /*FailOnError=*/true,
14849                                      /*Rebuilding=*/true);
14850 }
14851 
14852 template<typename Derived>
14853 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14854            QualType PointeeType,
14855            SourceLocation Star) {
14856   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14857 }
14858 
14859 template<typename Derived>
14860 QualType
14861 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14862                                          ArrayType::ArraySizeModifier SizeMod,
14863                                          const llvm::APInt *Size,
14864                                          Expr *SizeExpr,
14865                                          unsigned IndexTypeQuals,
14866                                          SourceRange BracketsRange) {
14867   if (SizeExpr || !Size)
14868     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14869                                   IndexTypeQuals, BracketsRange,
14870                                   getDerived().getBaseEntity());
14871 
14872   QualType Types[] = {
14873     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14874     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14875     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14876   };
14877   QualType SizeType;
14878   for (const auto &T : Types)
14879     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(T)) {
14880       SizeType = T;
14881       break;
14882     }
14883 
14884   // Note that we can return a VariableArrayType here in the case where
14885   // the element type was a dependent VariableArrayType.
14886   IntegerLiteral *ArraySize
14887       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14888                                /*FIXME*/BracketsRange.getBegin());
14889   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14890                                 IndexTypeQuals, BracketsRange,
14891                                 getDerived().getBaseEntity());
14892 }
14893 
14894 template<typename Derived>
14895 QualType
14896 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14897                                                  ArrayType::ArraySizeModifier SizeMod,
14898                                                  const llvm::APInt &Size,
14899                                                  Expr *SizeExpr,
14900                                                  unsigned IndexTypeQuals,
14901                                                  SourceRange BracketsRange) {
14902   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14903                                         IndexTypeQuals, BracketsRange);
14904 }
14905 
14906 template<typename Derived>
14907 QualType
14908 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14909                                           ArrayType::ArraySizeModifier SizeMod,
14910                                                  unsigned IndexTypeQuals,
14911                                                    SourceRange BracketsRange) {
14912   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14913                                        IndexTypeQuals, BracketsRange);
14914 }
14915 
14916 template<typename Derived>
14917 QualType
14918 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14919                                           ArrayType::ArraySizeModifier SizeMod,
14920                                                  Expr *SizeExpr,
14921                                                  unsigned IndexTypeQuals,
14922                                                  SourceRange BracketsRange) {
14923   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14924                                        SizeExpr,
14925                                        IndexTypeQuals, BracketsRange);
14926 }
14927 
14928 template<typename Derived>
14929 QualType
14930 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14931                                           ArrayType::ArraySizeModifier SizeMod,
14932                                                        Expr *SizeExpr,
14933                                                        unsigned IndexTypeQuals,
14934                                                    SourceRange BracketsRange) {
14935   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14936                                        SizeExpr,
14937                                        IndexTypeQuals, BracketsRange);
14938 }
14939 
14940 template <typename Derived>
14941 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14942     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14943   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14944                                           AttributeLoc);
14945 }
14946 
14947 template <typename Derived>
14948 QualType
14949 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14950                                           unsigned NumElements,
14951                                           VectorType::VectorKind VecKind) {
14952   // FIXME: semantic checking!
14953   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14954 }
14955 
14956 template <typename Derived>
14957 QualType TreeTransform<Derived>::RebuildDependentVectorType(
14958     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14959     VectorType::VectorKind VecKind) {
14960   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14961 }
14962 
14963 template<typename Derived>
14964 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14965                                                       unsigned NumElements,
14966                                                  SourceLocation AttributeLoc) {
14967   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14968                           NumElements, true);
14969   IntegerLiteral *VectorSize
14970     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14971                              AttributeLoc);
14972   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14973 }
14974 
14975 template<typename Derived>
14976 QualType
14977 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14978                                                            Expr *SizeExpr,
14979                                                   SourceLocation AttributeLoc) {
14980   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14981 }
14982 
14983 template <typename Derived>
14984 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14985     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14986   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14987                                                NumColumns);
14988 }
14989 
14990 template <typename Derived>
14991 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14992     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14993     SourceLocation AttributeLoc) {
14994   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14995                                  AttributeLoc);
14996 }
14997 
14998 template<typename Derived>
14999 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
15000     QualType T,
15001     MutableArrayRef<QualType> ParamTypes,
15002     const FunctionProtoType::ExtProtoInfo &EPI) {
15003   return SemaRef.BuildFunctionType(T, ParamTypes,
15004                                    getDerived().getBaseLocation(),
15005                                    getDerived().getBaseEntity(),
15006                                    EPI);
15007 }
15008 
15009 template<typename Derived>
15010 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
15011   return SemaRef.Context.getFunctionNoProtoType(T);
15012 }
15013 
15014 template<typename Derived>
15015 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
15016                                                             Decl *D) {
15017   assert(D && "no decl found");
15018   if (D->isInvalidDecl()) return QualType();
15019 
15020   // FIXME: Doesn't account for ObjCInterfaceDecl!
15021   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
15022     // A valid resolved using typename pack expansion decl can have multiple
15023     // UsingDecls, but they must each have exactly one type, and it must be
15024     // the same type in every case. But we must have at least one expansion!
15025     if (UPD->expansions().empty()) {
15026       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
15027           << UPD->isCXXClassMember() << UPD;
15028       return QualType();
15029     }
15030 
15031     // We might still have some unresolved types. Try to pick a resolved type
15032     // if we can. The final instantiation will check that the remaining
15033     // unresolved types instantiate to the type we pick.
15034     QualType FallbackT;
15035     QualType T;
15036     for (auto *E : UPD->expansions()) {
15037       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
15038       if (ThisT.isNull())
15039         continue;
15040       else if (ThisT->getAs<UnresolvedUsingType>())
15041         FallbackT = ThisT;
15042       else if (T.isNull())
15043         T = ThisT;
15044       else
15045         assert(getSema().Context.hasSameType(ThisT, T) &&
15046                "mismatched resolved types in using pack expansion");
15047     }
15048     return T.isNull() ? FallbackT : T;
15049   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
15050     assert(Using->hasTypename() &&
15051            "UnresolvedUsingTypenameDecl transformed to non-typename using");
15052 
15053     // A valid resolved using typename decl points to exactly one type decl.
15054     assert(++Using->shadow_begin() == Using->shadow_end());
15055 
15056     UsingShadowDecl *Shadow = *Using->shadow_begin();
15057     if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
15058       return QualType();
15059     return SemaRef.Context.getUsingType(
15060         Shadow, SemaRef.Context.getTypeDeclType(
15061                     cast<TypeDecl>(Shadow->getTargetDecl())));
15062   } else {
15063     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
15064            "UnresolvedUsingTypenameDecl transformed to non-using decl");
15065     return SemaRef.Context.getTypeDeclType(
15066         cast<UnresolvedUsingTypenameDecl>(D));
15067   }
15068 }
15069 
15070 template <typename Derived>
15071 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E, SourceLocation,
15072                                                        TypeOfKind Kind) {
15073   return SemaRef.BuildTypeofExprType(E, Kind);
15074 }
15075 
15076 template<typename Derived>
15077 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying,
15078                                                    TypeOfKind Kind) {
15079   return SemaRef.Context.getTypeOfType(Underlying, Kind);
15080 }
15081 
15082 template <typename Derived>
15083 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
15084   return SemaRef.BuildDecltypeType(E);
15085 }
15086 
15087 template<typename Derived>
15088 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
15089                                             UnaryTransformType::UTTKind UKind,
15090                                             SourceLocation Loc) {
15091   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
15092 }
15093 
15094 template<typename Derived>
15095 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
15096                                                       TemplateName Template,
15097                                              SourceLocation TemplateNameLoc,
15098                                      TemplateArgumentListInfo &TemplateArgs) {
15099   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
15100 }
15101 
15102 template<typename Derived>
15103 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
15104                                                    SourceLocation KWLoc) {
15105   return SemaRef.BuildAtomicType(ValueType, KWLoc);
15106 }
15107 
15108 template<typename Derived>
15109 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
15110                                                  SourceLocation KWLoc,
15111                                                  bool isReadPipe) {
15112   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
15113                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
15114 }
15115 
15116 template <typename Derived>
15117 QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
15118                                                    unsigned NumBits,
15119                                                    SourceLocation Loc) {
15120   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15121                         NumBits, true);
15122   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
15123                                                 SemaRef.Context.IntTy, Loc);
15124   return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
15125 }
15126 
15127 template <typename Derived>
15128 QualType TreeTransform<Derived>::RebuildDependentBitIntType(
15129     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
15130   return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
15131 }
15132 
15133 template<typename Derived>
15134 TemplateName
15135 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15136                                             bool TemplateKW,
15137                                             TemplateDecl *Template) {
15138   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
15139                                                   TemplateName(Template));
15140 }
15141 
15142 template<typename Derived>
15143 TemplateName
15144 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15145                                             SourceLocation TemplateKWLoc,
15146                                             const IdentifierInfo &Name,
15147                                             SourceLocation NameLoc,
15148                                             QualType ObjectType,
15149                                             NamedDecl *FirstQualifierInScope,
15150                                             bool AllowInjectedClassName) {
15151   UnqualifiedId TemplateName;
15152   TemplateName.setIdentifier(&Name, NameLoc);
15153   Sema::TemplateTy Template;
15154   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
15155                               TemplateName, ParsedType::make(ObjectType),
15156                               /*EnteringContext=*/false, Template,
15157                               AllowInjectedClassName);
15158   return Template.get();
15159 }
15160 
15161 template<typename Derived>
15162 TemplateName
15163 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15164                                             SourceLocation TemplateKWLoc,
15165                                             OverloadedOperatorKind Operator,
15166                                             SourceLocation NameLoc,
15167                                             QualType ObjectType,
15168                                             bool AllowInjectedClassName) {
15169   UnqualifiedId Name;
15170   // FIXME: Bogus location information.
15171   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
15172   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
15173   Sema::TemplateTy Template;
15174   getSema().ActOnTemplateName(
15175       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
15176       /*EnteringContext=*/false, Template, AllowInjectedClassName);
15177   return Template.get();
15178 }
15179 
15180 template <typename Derived>
15181 ExprResult TreeTransform<Derived>::RebuildCXXOperatorCallExpr(
15182     OverloadedOperatorKind Op, SourceLocation OpLoc, SourceLocation CalleeLoc,
15183     bool RequiresADL, const UnresolvedSetImpl &Functions, Expr *First,
15184     Expr *Second) {
15185   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
15186 
15187   if (First->getObjectKind() == OK_ObjCProperty) {
15188     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15189     if (BinaryOperator::isAssignmentOp(Opc))
15190       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
15191                                                  First, Second);
15192     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
15193     if (Result.isInvalid())
15194       return ExprError();
15195     First = Result.get();
15196   }
15197 
15198   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
15199     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
15200     if (Result.isInvalid())
15201       return ExprError();
15202     Second = Result.get();
15203   }
15204 
15205   // Determine whether this should be a builtin operation.
15206   if (Op == OO_Subscript) {
15207     if (!First->getType()->isOverloadableType() &&
15208         !Second->getType()->isOverloadableType())
15209       return getSema().CreateBuiltinArraySubscriptExpr(First, CalleeLoc, Second,
15210                                                        OpLoc);
15211   } else if (Op == OO_Arrow) {
15212     // It is possible that the type refers to a RecoveryExpr created earlier
15213     // in the tree transformation.
15214     if (First->getType()->isDependentType())
15215       return ExprError();
15216     // -> is never a builtin operation.
15217     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
15218   } else if (Second == nullptr || isPostIncDec) {
15219     if (!First->getType()->isOverloadableType() ||
15220         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
15221       // The argument is not of overloadable type, or this is an expression
15222       // of the form &Class::member, so try to create a built-in unary
15223       // operation.
15224       UnaryOperatorKind Opc
15225         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15226 
15227       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
15228     }
15229   } else {
15230     if (!First->getType()->isOverloadableType() &&
15231         !Second->getType()->isOverloadableType()) {
15232       // Neither of the arguments is an overloadable type, so try to
15233       // create a built-in binary operation.
15234       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15235       ExprResult Result
15236         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
15237       if (Result.isInvalid())
15238         return ExprError();
15239 
15240       return Result;
15241     }
15242   }
15243 
15244   // Add any functions found via argument-dependent lookup.
15245   Expr *Args[2] = { First, Second };
15246   unsigned NumArgs = 1 + (Second != nullptr);
15247 
15248   // Create the overloaded operator invocation for unary operators.
15249   if (NumArgs == 1 || isPostIncDec) {
15250     UnaryOperatorKind Opc
15251       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15252     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
15253                                            RequiresADL);
15254   }
15255 
15256   // Create the overloaded operator invocation for binary operators.
15257   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15258   ExprResult Result = SemaRef.CreateOverloadedBinOp(
15259       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
15260   if (Result.isInvalid())
15261     return ExprError();
15262 
15263   return Result;
15264 }
15265 
15266 template<typename Derived>
15267 ExprResult
15268 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
15269                                                      SourceLocation OperatorLoc,
15270                                                        bool isArrow,
15271                                                        CXXScopeSpec &SS,
15272                                                      TypeSourceInfo *ScopeType,
15273                                                        SourceLocation CCLoc,
15274                                                        SourceLocation TildeLoc,
15275                                         PseudoDestructorTypeStorage Destroyed) {
15276   QualType BaseType = Base->getType();
15277   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
15278       (!isArrow && !BaseType->getAs<RecordType>()) ||
15279       (isArrow && BaseType->getAs<PointerType>() &&
15280        !BaseType->castAs<PointerType>()->getPointeeType()
15281                                               ->template getAs<RecordType>())){
15282     // This pseudo-destructor expression is still a pseudo-destructor.
15283     return SemaRef.BuildPseudoDestructorExpr(
15284         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
15285         CCLoc, TildeLoc, Destroyed);
15286   }
15287 
15288   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
15289   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
15290                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
15291   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
15292   NameInfo.setNamedTypeInfo(DestroyedType);
15293 
15294   // The scope type is now known to be a valid nested name specifier
15295   // component. Tack it on to the end of the nested name specifier.
15296   if (ScopeType) {
15297     if (!ScopeType->getType()->getAs<TagType>()) {
15298       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15299                      diag::err_expected_class_or_namespace)
15300           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15301       return ExprError();
15302     }
15303     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15304               CCLoc);
15305   }
15306 
15307   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15308   return getSema().BuildMemberReferenceExpr(Base, BaseType,
15309                                             OperatorLoc, isArrow,
15310                                             SS, TemplateKWLoc,
15311                                             /*FIXME: FirstQualifier*/ nullptr,
15312                                             NameInfo,
15313                                             /*TemplateArgs*/ nullptr,
15314                                             /*S*/nullptr);
15315 }
15316 
15317 template<typename Derived>
15318 StmtResult
15319 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15320   SourceLocation Loc = S->getBeginLoc();
15321   CapturedDecl *CD = S->getCapturedDecl();
15322   unsigned NumParams = CD->getNumParams();
15323   unsigned ContextParamPos = CD->getContextParamPosition();
15324   SmallVector<Sema::CapturedParamNameType, 4> Params;
15325   for (unsigned I = 0; I < NumParams; ++I) {
15326     if (I != ContextParamPos) {
15327       Params.push_back(
15328              std::make_pair(
15329                   CD->getParam(I)->getName(),
15330                   getDerived().TransformType(CD->getParam(I)->getType())));
15331     } else {
15332       Params.push_back(std::make_pair(StringRef(), QualType()));
15333     }
15334   }
15335   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15336                                      S->getCapturedRegionKind(), Params);
15337   StmtResult Body;
15338   {
15339     Sema::CompoundScopeRAII CompoundScope(getSema());
15340     Body = getDerived().TransformStmt(S->getCapturedStmt());
15341   }
15342 
15343   if (Body.isInvalid()) {
15344     getSema().ActOnCapturedRegionError();
15345     return StmtError();
15346   }
15347 
15348   return getSema().ActOnCapturedRegionEnd(Body.get());
15349 }
15350 
15351 } // end namespace clang
15352 
15353 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15354