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/ExprObjC.h"
24 #include "clang/AST/ExprOpenMP.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/AST/StmtOpenMP.h"
29 #include "clang/Sema/Designator.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Ownership.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaDiagnostic.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include <algorithm>
39 
40 namespace clang {
41 using namespace sema;
42 
43 /// A semantic tree transformation that allows one to transform one
44 /// abstract syntax tree into another.
45 ///
46 /// A new tree transformation is defined by creating a new subclass \c X of
47 /// \c TreeTransform<X> and then overriding certain operations to provide
48 /// behavior specific to that transformation. For example, template
49 /// instantiation is implemented as a tree transformation where the
50 /// transformation of TemplateTypeParmType nodes involves substituting the
51 /// template arguments for their corresponding template parameters; a similar
52 /// transformation is performed for non-type template parameters and
53 /// template template parameters.
54 ///
55 /// This tree-transformation template uses static polymorphism to allow
56 /// subclasses to customize any of its operations. Thus, a subclass can
57 /// override any of the transformation or rebuild operators by providing an
58 /// operation with the same signature as the default implementation. The
59 /// overriding function should not be virtual.
60 ///
61 /// Semantic tree transformations are split into two stages, either of which
62 /// can be replaced by a subclass. The "transform" step transforms an AST node
63 /// or the parts of an AST node using the various transformation functions,
64 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
65 /// node of the appropriate kind from the pieces. The default transformation
66 /// routines recursively transform the operands to composite AST nodes (e.g.,
67 /// the pointee type of a PointerType node) and, if any of those operand nodes
68 /// were changed by the transformation, invokes the rebuild operation to create
69 /// a new AST node.
70 ///
71 /// Subclasses can customize the transformation at various levels. The
72 /// most coarse-grained transformations involve replacing TransformType(),
73 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
74 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
75 /// new implementations.
76 ///
77 /// For more fine-grained transformations, subclasses can replace any of the
78 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
79 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
80 /// replacing TransformTemplateTypeParmType() allows template instantiation
81 /// to substitute template arguments for their corresponding template
82 /// parameters. Additionally, subclasses can override the \c RebuildXXX
83 /// functions to control how AST nodes are rebuilt when their operands change.
84 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
85 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
86 /// be able to use more efficient rebuild steps.
87 ///
88 /// There are a handful of other functions that can be overridden, allowing one
89 /// to avoid traversing nodes that don't need any transformation
90 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
91 /// operands have not changed (\c AlwaysRebuild()), and customize the
92 /// default locations and entity names used for type-checking
93 /// (\c getBaseLocation(), \c getBaseEntity()).
94 template<typename Derived>
95 class TreeTransform {
96   /// Private RAII object that helps us forget and then re-remember
97   /// the template argument corresponding to a partially-substituted parameter
98   /// pack.
99   class ForgetPartiallySubstitutedPackRAII {
100     Derived &Self;
101     TemplateArgument Old;
102 
103   public:
104     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
105       Old = Self.ForgetPartiallySubstitutedPack();
106     }
107 
108     ~ForgetPartiallySubstitutedPackRAII() {
109       Self.RememberPartiallySubstitutedPack(Old);
110     }
111   };
112 
113 protected:
114   Sema &SemaRef;
115 
116   /// The set of local declarations that have been transformed, for
117   /// cases where we are forced to build new declarations within the transformer
118   /// rather than in the subclass (e.g., lambda closure types).
119   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
120 
121 public:
122   /// Initializes a new tree transformer.
123   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
124 
125   /// Retrieves a reference to the derived class.
126   Derived &getDerived() { return static_cast<Derived&>(*this); }
127 
128   /// Retrieves a reference to the derived class.
129   const Derived &getDerived() const {
130     return static_cast<const Derived&>(*this);
131   }
132 
133   static inline ExprResult Owned(Expr *E) { return E; }
134   static inline StmtResult Owned(Stmt *S) { return S; }
135 
136   /// Retrieves a reference to the semantic analysis object used for
137   /// this tree transform.
138   Sema &getSema() const { return SemaRef; }
139 
140   /// Whether the transformation should always rebuild AST nodes, even
141   /// if none of the children have changed.
142   ///
143   /// Subclasses may override this function to specify when the transformation
144   /// should rebuild all AST nodes.
145   ///
146   /// We must always rebuild all AST nodes when performing variadic template
147   /// pack expansion, in order to avoid violating the AST invariant that each
148   /// statement node appears at most once in its containing declaration.
149   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
150 
151   /// Whether the transformation is forming an expression or statement that
152   /// replaces the original. In this case, we'll reuse mangling numbers from
153   /// existing lambdas.
154   bool ReplacingOriginal() { return false; }
155 
156   /// Returns the location of the entity being transformed, if that
157   /// information was not available elsewhere in the AST.
158   ///
159   /// By default, returns no source-location information. Subclasses can
160   /// provide an alternative implementation that provides better location
161   /// information.
162   SourceLocation getBaseLocation() { return SourceLocation(); }
163 
164   /// Returns the name of the entity being transformed, if that
165   /// information was not available elsewhere in the AST.
166   ///
167   /// By default, returns an empty name. Subclasses can provide an alternative
168   /// implementation with a more precise name.
169   DeclarationName getBaseEntity() { return DeclarationName(); }
170 
171   /// Sets the "base" location and entity when that
172   /// information is known based on another transformation.
173   ///
174   /// By default, the source location and entity are ignored. Subclasses can
175   /// override this function to provide a customized implementation.
176   void setBase(SourceLocation Loc, DeclarationName Entity) { }
177 
178   /// RAII object that temporarily sets the base location and entity
179   /// used for reporting diagnostics in types.
180   class TemporaryBase {
181     TreeTransform &Self;
182     SourceLocation OldLocation;
183     DeclarationName OldEntity;
184 
185   public:
186     TemporaryBase(TreeTransform &Self, SourceLocation Location,
187                   DeclarationName Entity) : Self(Self) {
188       OldLocation = Self.getDerived().getBaseLocation();
189       OldEntity = Self.getDerived().getBaseEntity();
190 
191       if (Location.isValid())
192         Self.getDerived().setBase(Location, Entity);
193     }
194 
195     ~TemporaryBase() {
196       Self.getDerived().setBase(OldLocation, OldEntity);
197     }
198   };
199 
200   /// Determine whether the given type \p T has already been
201   /// transformed.
202   ///
203   /// Subclasses can provide an alternative implementation of this routine
204   /// to short-circuit evaluation when it is known that a given type will
205   /// not change. For example, template instantiation need not traverse
206   /// non-dependent types.
207   bool AlreadyTransformed(QualType T) {
208     return T.isNull();
209   }
210 
211   /// Determine whether the given call argument should be dropped, e.g.,
212   /// because it is a default argument.
213   ///
214   /// Subclasses can provide an alternative implementation of this routine to
215   /// determine which kinds of call arguments get dropped. By default,
216   /// CXXDefaultArgument nodes are dropped (prior to transformation).
217   bool DropCallArgument(Expr *E) {
218     return E->isDefaultArgument();
219   }
220 
221   /// Determine whether we should expand a pack expansion with the
222   /// given set of parameter packs into separate arguments by repeatedly
223   /// transforming the pattern.
224   ///
225   /// By default, the transformer never tries to expand pack expansions.
226   /// Subclasses can override this routine to provide different behavior.
227   ///
228   /// \param EllipsisLoc The location of the ellipsis that identifies the
229   /// pack expansion.
230   ///
231   /// \param PatternRange The source range that covers the entire pattern of
232   /// the pack expansion.
233   ///
234   /// \param Unexpanded The set of unexpanded parameter packs within the
235   /// pattern.
236   ///
237   /// \param ShouldExpand Will be set to \c true if the transformer should
238   /// expand the corresponding pack expansions into separate arguments. When
239   /// set, \c NumExpansions must also be set.
240   ///
241   /// \param RetainExpansion Whether the caller should add an unexpanded
242   /// pack expansion after all of the expanded arguments. This is used
243   /// when extending explicitly-specified template argument packs per
244   /// C++0x [temp.arg.explicit]p9.
245   ///
246   /// \param NumExpansions The number of separate arguments that will be in
247   /// the expanded form of the corresponding pack expansion. This is both an
248   /// input and an output parameter, which can be set by the caller if the
249   /// number of expansions is known a priori (e.g., due to a prior substitution)
250   /// and will be set by the callee when the number of expansions is known.
251   /// The callee must set this value when \c ShouldExpand is \c true; it may
252   /// set this value in other cases.
253   ///
254   /// \returns true if an error occurred (e.g., because the parameter packs
255   /// are to be instantiated with arguments of different lengths), false
256   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
257   /// must be set.
258   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
259                                SourceRange PatternRange,
260                                ArrayRef<UnexpandedParameterPack> Unexpanded,
261                                bool &ShouldExpand,
262                                bool &RetainExpansion,
263                                Optional<unsigned> &NumExpansions) {
264     ShouldExpand = false;
265     return false;
266   }
267 
268   /// "Forget" about the partially-substituted pack template argument,
269   /// when performing an instantiation that must preserve the parameter pack
270   /// use.
271   ///
272   /// This routine is meant to be overridden by the template instantiator.
273   TemplateArgument ForgetPartiallySubstitutedPack() {
274     return TemplateArgument();
275   }
276 
277   /// "Remember" the partially-substituted pack template argument
278   /// after performing an instantiation that must preserve the parameter pack
279   /// use.
280   ///
281   /// This routine is meant to be overridden by the template instantiator.
282   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
283 
284   /// Note to the derived class when a function parameter pack is
285   /// being expanded.
286   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
287 
288   /// Transforms the given type into another type.
289   ///
290   /// By default, this routine transforms a type by creating a
291   /// TypeSourceInfo for it and delegating to the appropriate
292   /// function.  This is expensive, but we don't mind, because
293   /// this method is deprecated anyway;  all users should be
294   /// switched to storing TypeSourceInfos.
295   ///
296   /// \returns the transformed type.
297   QualType TransformType(QualType T);
298 
299   /// Transforms the given type-with-location into a new
300   /// type-with-location.
301   ///
302   /// By default, this routine transforms a type by delegating to the
303   /// appropriate TransformXXXType to build a new type.  Subclasses
304   /// may override this function (to take over all type
305   /// transformations) or some set of the TransformXXXType functions
306   /// to alter the transformation.
307   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
308 
309   /// Transform the given type-with-location into a new
310   /// type, collecting location information in the given builder
311   /// as necessary.
312   ///
313   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
314 
315   /// Transform a type that is permitted to produce a
316   /// DeducedTemplateSpecializationType.
317   ///
318   /// This is used in the (relatively rare) contexts where it is acceptable
319   /// for transformation to produce a class template type with deduced
320   /// template arguments.
321   /// @{
322   QualType TransformTypeWithDeducedTST(QualType T);
323   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
324   /// @}
325 
326   /// The reason why the value of a statement is not discarded, if any.
327   enum StmtDiscardKind {
328     SDK_Discarded,
329     SDK_NotDiscarded,
330     SDK_StmtExprResult,
331   };
332 
333   /// Transform the given statement.
334   ///
335   /// By default, this routine transforms a statement by delegating to the
336   /// appropriate TransformXXXStmt function to transform a specific kind of
337   /// statement or the TransformExpr() function to transform an expression.
338   /// Subclasses may override this function to transform statements using some
339   /// other mechanism.
340   ///
341   /// \returns the transformed statement.
342   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
343 
344   /// Transform the given statement.
345   ///
346   /// By default, this routine transforms a statement by delegating to the
347   /// appropriate TransformOMPXXXClause function to transform a specific kind
348   /// of clause. Subclasses may override this function to transform statements
349   /// using some other mechanism.
350   ///
351   /// \returns the transformed OpenMP clause.
352   OMPClause *TransformOMPClause(OMPClause *S);
353 
354   /// Transform the given attribute.
355   ///
356   /// By default, this routine transforms a statement by delegating to the
357   /// appropriate TransformXXXAttr function to transform a specific kind
358   /// of attribute. Subclasses may override this function to transform
359   /// attributed statements using some other mechanism.
360   ///
361   /// \returns the transformed attribute
362   const Attr *TransformAttr(const Attr *S);
363 
364 /// Transform the specified attribute.
365 ///
366 /// Subclasses should override the transformation of attributes with a pragma
367 /// spelling to transform expressions stored within the attribute.
368 ///
369 /// \returns the transformed attribute.
370 #define ATTR(X)
371 #define PRAGMA_SPELLING_ATTR(X)                                                \
372   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
373 #include "clang/Basic/AttrList.inc"
374 
375   /// Transform the given expression.
376   ///
377   /// By default, this routine transforms an expression by delegating to the
378   /// appropriate TransformXXXExpr function to build a new expression.
379   /// Subclasses may override this function to transform expressions using some
380   /// other mechanism.
381   ///
382   /// \returns the transformed expression.
383   ExprResult TransformExpr(Expr *E);
384 
385   /// Transform the given initializer.
386   ///
387   /// By default, this routine transforms an initializer by stripping off the
388   /// semantic nodes added by initialization, then passing the result to
389   /// TransformExpr or TransformExprs.
390   ///
391   /// \returns the transformed initializer.
392   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
393 
394   /// Transform the given list of expressions.
395   ///
396   /// This routine transforms a list of expressions by invoking
397   /// \c TransformExpr() for each subexpression. However, it also provides
398   /// support for variadic templates by expanding any pack expansions (if the
399   /// derived class permits such expansion) along the way. When pack expansions
400   /// are present, the number of outputs may not equal the number of inputs.
401   ///
402   /// \param Inputs The set of expressions to be transformed.
403   ///
404   /// \param NumInputs The number of expressions in \c Inputs.
405   ///
406   /// \param IsCall If \c true, then this transform is being performed on
407   /// function-call arguments, and any arguments that should be dropped, will
408   /// be.
409   ///
410   /// \param Outputs The transformed input expressions will be added to this
411   /// vector.
412   ///
413   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
414   /// due to transformation.
415   ///
416   /// \returns true if an error occurred, false otherwise.
417   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
418                       SmallVectorImpl<Expr *> &Outputs,
419                       bool *ArgChanged = nullptr);
420 
421   /// Transform the given declaration, which is referenced from a type
422   /// or expression.
423   ///
424   /// By default, acts as the identity function on declarations, unless the
425   /// transformer has had to transform the declaration itself. Subclasses
426   /// may override this function to provide alternate behavior.
427   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
428     llvm::DenseMap<Decl *, Decl *>::iterator Known
429       = TransformedLocalDecls.find(D);
430     if (Known != TransformedLocalDecls.end())
431       return Known->second;
432 
433     return D;
434   }
435 
436   /// Transform the specified condition.
437   ///
438   /// By default, this transforms the variable and expression and rebuilds
439   /// the condition.
440   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
441                                            Expr *Expr,
442                                            Sema::ConditionKind Kind);
443 
444   /// Transform the attributes associated with the given declaration and
445   /// place them on the new declaration.
446   ///
447   /// By default, this operation does nothing. Subclasses may override this
448   /// behavior to transform attributes.
449   void transformAttrs(Decl *Old, Decl *New) { }
450 
451   /// Note that a local declaration has been transformed by this
452   /// transformer.
453   ///
454   /// Local declarations are typically transformed via a call to
455   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
456   /// the transformer itself has to transform the declarations. This routine
457   /// can be overridden by a subclass that keeps track of such mappings.
458   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
459     assert(New.size() == 1 &&
460            "must override transformedLocalDecl if performing pack expansion");
461     TransformedLocalDecls[Old] = New.front();
462   }
463 
464   /// Transform the definition of the given declaration.
465   ///
466   /// By default, invokes TransformDecl() to transform the declaration.
467   /// Subclasses may override this function to provide alternate behavior.
468   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
469     return getDerived().TransformDecl(Loc, D);
470   }
471 
472   /// Transform the given declaration, which was the first part of a
473   /// nested-name-specifier in a member access expression.
474   ///
475   /// This specific declaration transformation only applies to the first
476   /// identifier in a nested-name-specifier of a member access expression, e.g.,
477   /// the \c T in \c x->T::member
478   ///
479   /// By default, invokes TransformDecl() to transform the declaration.
480   /// Subclasses may override this function to provide alternate behavior.
481   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
482     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
483   }
484 
485   /// Transform the set of declarations in an OverloadExpr.
486   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
487                                   LookupResult &R);
488 
489   /// Transform the given nested-name-specifier with source-location
490   /// information.
491   ///
492   /// By default, transforms all of the types and declarations within the
493   /// nested-name-specifier. Subclasses may override this function to provide
494   /// alternate behavior.
495   NestedNameSpecifierLoc
496   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
497                                   QualType ObjectType = QualType(),
498                                   NamedDecl *FirstQualifierInScope = nullptr);
499 
500   /// Transform the given declaration name.
501   ///
502   /// By default, transforms the types of conversion function, constructor,
503   /// and destructor names and then (if needed) rebuilds the declaration name.
504   /// Identifiers and selectors are returned unmodified. Sublcasses may
505   /// override this function to provide alternate behavior.
506   DeclarationNameInfo
507   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
508 
509   /// Transform the given template name.
510   ///
511   /// \param SS The nested-name-specifier that qualifies the template
512   /// name. This nested-name-specifier must already have been transformed.
513   ///
514   /// \param Name The template name to transform.
515   ///
516   /// \param NameLoc The source location of the template name.
517   ///
518   /// \param ObjectType If we're translating a template name within a member
519   /// access expression, this is the type of the object whose member template
520   /// is being referenced.
521   ///
522   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
523   /// also refers to a name within the current (lexical) scope, this is the
524   /// declaration it refers to.
525   ///
526   /// By default, transforms the template name by transforming the declarations
527   /// and nested-name-specifiers that occur within the template name.
528   /// Subclasses may override this function to provide alternate behavior.
529   TemplateName
530   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
531                         SourceLocation NameLoc,
532                         QualType ObjectType = QualType(),
533                         NamedDecl *FirstQualifierInScope = nullptr,
534                         bool AllowInjectedClassName = false);
535 
536   /// Transform the given template argument.
537   ///
538   /// By default, this operation transforms the type, expression, or
539   /// declaration stored within the template argument and constructs a
540   /// new template argument from the transformed result. Subclasses may
541   /// override this function to provide alternate behavior.
542   ///
543   /// Returns true if there was an error.
544   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
545                                  TemplateArgumentLoc &Output,
546                                  bool Uneval = false);
547 
548   /// Transform the given set of template arguments.
549   ///
550   /// By default, this operation transforms all of the template arguments
551   /// in the input set using \c TransformTemplateArgument(), and appends
552   /// the transformed arguments to the output list.
553   ///
554   /// Note that this overload of \c TransformTemplateArguments() is merely
555   /// a convenience function. Subclasses that wish to override this behavior
556   /// should override the iterator-based member template version.
557   ///
558   /// \param Inputs The set of template arguments to be transformed.
559   ///
560   /// \param NumInputs The number of template arguments in \p Inputs.
561   ///
562   /// \param Outputs The set of transformed template arguments output by this
563   /// routine.
564   ///
565   /// Returns true if an error occurred.
566   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
567                                   unsigned NumInputs,
568                                   TemplateArgumentListInfo &Outputs,
569                                   bool Uneval = false) {
570     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
571                                       Uneval);
572   }
573 
574   /// Transform the given set of template arguments.
575   ///
576   /// By default, this operation transforms all of the template arguments
577   /// in the input set using \c TransformTemplateArgument(), and appends
578   /// the transformed arguments to the output list.
579   ///
580   /// \param First An iterator to the first template argument.
581   ///
582   /// \param Last An iterator one step past the last template argument.
583   ///
584   /// \param Outputs The set of transformed template arguments output by this
585   /// routine.
586   ///
587   /// Returns true if an error occurred.
588   template<typename InputIterator>
589   bool TransformTemplateArguments(InputIterator First,
590                                   InputIterator Last,
591                                   TemplateArgumentListInfo &Outputs,
592                                   bool Uneval = false);
593 
594   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
595   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
596                                  TemplateArgumentLoc &ArgLoc);
597 
598   /// Fakes up a TypeSourceInfo for a type.
599   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
600     return SemaRef.Context.getTrivialTypeSourceInfo(T,
601                        getDerived().getBaseLocation());
602   }
603 
604 #define ABSTRACT_TYPELOC(CLASS, PARENT)
605 #define TYPELOC(CLASS, PARENT)                                   \
606   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
607 #include "clang/AST/TypeLocNodes.def"
608 
609   template<typename Fn>
610   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
611                                       FunctionProtoTypeLoc TL,
612                                       CXXRecordDecl *ThisContext,
613                                       Qualifiers ThisTypeQuals,
614                                       Fn TransformExceptionSpec);
615 
616   bool TransformExceptionSpec(SourceLocation Loc,
617                               FunctionProtoType::ExceptionSpecInfo &ESI,
618                               SmallVectorImpl<QualType> &Exceptions,
619                               bool &Changed);
620 
621   StmtResult TransformSEHHandler(Stmt *Handler);
622 
623   QualType
624   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
625                                       TemplateSpecializationTypeLoc TL,
626                                       TemplateName Template);
627 
628   QualType
629   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
630                                       DependentTemplateSpecializationTypeLoc TL,
631                                                TemplateName Template,
632                                                CXXScopeSpec &SS);
633 
634   QualType TransformDependentTemplateSpecializationType(
635       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
636       NestedNameSpecifierLoc QualifierLoc);
637 
638   /// Transforms the parameters of a function type into the
639   /// given vectors.
640   ///
641   /// The result vectors should be kept in sync; null entries in the
642   /// variables vector are acceptable.
643   ///
644   /// Return true on error.
645   bool TransformFunctionTypeParams(
646       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
647       const QualType *ParamTypes,
648       const FunctionProtoType::ExtParameterInfo *ParamInfos,
649       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
650       Sema::ExtParameterInfoBuilder &PInfos);
651 
652   /// Transforms a single function-type parameter.  Return null
653   /// on error.
654   ///
655   /// \param indexAdjustment - A number to add to the parameter's
656   ///   scope index;  can be negative
657   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
658                                           int indexAdjustment,
659                                           Optional<unsigned> NumExpansions,
660                                           bool ExpectParameterPack);
661 
662   /// Transform the body of a lambda-expression.
663   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
664   /// Alternative implementation of TransformLambdaBody that skips transforming
665   /// the body.
666   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
667 
668   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
669 
670   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
671   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
672 
673   TemplateParameterList *TransformTemplateParameterList(
674         TemplateParameterList *TPL) {
675     return TPL;
676   }
677 
678   ExprResult TransformAddressOfOperand(Expr *E);
679 
680   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
681                                                 bool IsAddressOfOperand,
682                                                 TypeSourceInfo **RecoveryTSI);
683 
684   ExprResult TransformParenDependentScopeDeclRefExpr(
685       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
686       TypeSourceInfo **RecoveryTSI);
687 
688   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
689 
690 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
691 // amount of stack usage with clang.
692 #define STMT(Node, Parent)                        \
693   LLVM_ATTRIBUTE_NOINLINE \
694   StmtResult Transform##Node(Node *S);
695 #define VALUESTMT(Node, Parent)                   \
696   LLVM_ATTRIBUTE_NOINLINE \
697   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
698 #define EXPR(Node, Parent)                        \
699   LLVM_ATTRIBUTE_NOINLINE \
700   ExprResult Transform##Node(Node *E);
701 #define ABSTRACT_STMT(Stmt)
702 #include "clang/AST/StmtNodes.inc"
703 
704 #define OPENMP_CLAUSE(Name, Class)                        \
705   LLVM_ATTRIBUTE_NOINLINE \
706   OMPClause *Transform ## Class(Class *S);
707 #include "clang/Basic/OpenMPKinds.def"
708 
709   /// Build a new qualified type given its unqualified type and type location.
710   ///
711   /// By default, this routine adds type qualifiers only to types that can
712   /// have qualifiers, and silently suppresses those qualifiers that are not
713   /// permitted. Subclasses may override this routine to provide different
714   /// behavior.
715   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
716 
717   /// Build a new pointer type given its pointee type.
718   ///
719   /// By default, performs semantic analysis when building the pointer type.
720   /// Subclasses may override this routine to provide different behavior.
721   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
722 
723   /// Build a new block pointer type given its pointee type.
724   ///
725   /// By default, performs semantic analysis when building the block pointer
726   /// type. Subclasses may override this routine to provide different behavior.
727   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
728 
729   /// Build a new reference type given the type it references.
730   ///
731   /// By default, performs semantic analysis when building the
732   /// reference type. Subclasses may override this routine to provide
733   /// different behavior.
734   ///
735   /// \param LValue whether the type was written with an lvalue sigil
736   /// or an rvalue sigil.
737   QualType RebuildReferenceType(QualType ReferentType,
738                                 bool LValue,
739                                 SourceLocation Sigil);
740 
741   /// Build a new member pointer type given the pointee type and the
742   /// class type it refers into.
743   ///
744   /// By default, performs semantic analysis when building the member pointer
745   /// type. Subclasses may override this routine to provide different behavior.
746   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
747                                     SourceLocation Sigil);
748 
749   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
750                                     SourceLocation ProtocolLAngleLoc,
751                                     ArrayRef<ObjCProtocolDecl *> Protocols,
752                                     ArrayRef<SourceLocation> ProtocolLocs,
753                                     SourceLocation ProtocolRAngleLoc);
754 
755   /// Build an Objective-C object type.
756   ///
757   /// By default, performs semantic analysis when building the object type.
758   /// Subclasses may override this routine to provide different behavior.
759   QualType RebuildObjCObjectType(QualType BaseType,
760                                  SourceLocation Loc,
761                                  SourceLocation TypeArgsLAngleLoc,
762                                  ArrayRef<TypeSourceInfo *> TypeArgs,
763                                  SourceLocation TypeArgsRAngleLoc,
764                                  SourceLocation ProtocolLAngleLoc,
765                                  ArrayRef<ObjCProtocolDecl *> Protocols,
766                                  ArrayRef<SourceLocation> ProtocolLocs,
767                                  SourceLocation ProtocolRAngleLoc);
768 
769   /// Build a new Objective-C object pointer type given the pointee type.
770   ///
771   /// By default, directly builds the pointer type, with no additional semantic
772   /// analysis.
773   QualType RebuildObjCObjectPointerType(QualType PointeeType,
774                                         SourceLocation Star);
775 
776   /// Build a new array type given the element type, size
777   /// modifier, size of the array (if known), size expression, and index type
778   /// qualifiers.
779   ///
780   /// By default, performs semantic analysis when building the array type.
781   /// Subclasses may override this routine to provide different behavior.
782   /// Also by default, all of the other Rebuild*Array
783   QualType RebuildArrayType(QualType ElementType,
784                             ArrayType::ArraySizeModifier SizeMod,
785                             const llvm::APInt *Size,
786                             Expr *SizeExpr,
787                             unsigned IndexTypeQuals,
788                             SourceRange BracketsRange);
789 
790   /// Build a new constant array type given the element type, size
791   /// modifier, (known) size of the array, and index type qualifiers.
792   ///
793   /// By default, performs semantic analysis when building the array type.
794   /// Subclasses may override this routine to provide different behavior.
795   QualType RebuildConstantArrayType(QualType ElementType,
796                                     ArrayType::ArraySizeModifier SizeMod,
797                                     const llvm::APInt &Size,
798                                     unsigned IndexTypeQuals,
799                                     SourceRange BracketsRange);
800 
801   /// Build a new incomplete array type given the element type, size
802   /// modifier, and index type qualifiers.
803   ///
804   /// By default, performs semantic analysis when building the array type.
805   /// Subclasses may override this routine to provide different behavior.
806   QualType RebuildIncompleteArrayType(QualType ElementType,
807                                       ArrayType::ArraySizeModifier SizeMod,
808                                       unsigned IndexTypeQuals,
809                                       SourceRange BracketsRange);
810 
811   /// Build a new variable-length array type given the element type,
812   /// size modifier, size expression, and index type qualifiers.
813   ///
814   /// By default, performs semantic analysis when building the array type.
815   /// Subclasses may override this routine to provide different behavior.
816   QualType RebuildVariableArrayType(QualType ElementType,
817                                     ArrayType::ArraySizeModifier SizeMod,
818                                     Expr *SizeExpr,
819                                     unsigned IndexTypeQuals,
820                                     SourceRange BracketsRange);
821 
822   /// Build a new dependent-sized array type given the element type,
823   /// size modifier, size expression, and index type qualifiers.
824   ///
825   /// By default, performs semantic analysis when building the array type.
826   /// Subclasses may override this routine to provide different behavior.
827   QualType RebuildDependentSizedArrayType(QualType ElementType,
828                                           ArrayType::ArraySizeModifier SizeMod,
829                                           Expr *SizeExpr,
830                                           unsigned IndexTypeQuals,
831                                           SourceRange BracketsRange);
832 
833   /// Build a new vector type given the element type and
834   /// number of elements.
835   ///
836   /// By default, performs semantic analysis when building the vector type.
837   /// Subclasses may override this routine to provide different behavior.
838   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
839                              VectorType::VectorKind VecKind);
840 
841   /// Build a new potentially dependently-sized extended vector type
842   /// given the element type and number of elements.
843   ///
844   /// By default, performs semantic analysis when building the vector type.
845   /// Subclasses may override this routine to provide different behavior.
846   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
847                                            SourceLocation AttributeLoc,
848                                            VectorType::VectorKind);
849 
850   /// Build a new extended vector type given the element type and
851   /// number of elements.
852   ///
853   /// By default, performs semantic analysis when building the vector type.
854   /// Subclasses may override this routine to provide different behavior.
855   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
856                                 SourceLocation AttributeLoc);
857 
858   /// Build a new potentially dependently-sized extended vector type
859   /// given the element type and number of elements.
860   ///
861   /// By default, performs semantic analysis when building the vector type.
862   /// Subclasses may override this routine to provide different behavior.
863   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
864                                               Expr *SizeExpr,
865                                               SourceLocation AttributeLoc);
866 
867   /// Build a new DependentAddressSpaceType or return the pointee
868   /// type variable with the correct address space (retrieved from
869   /// AddrSpaceExpr) applied to it. The former will be returned in cases
870   /// where the address space remains dependent.
871   ///
872   /// By default, performs semantic analysis when building the type with address
873   /// space applied. Subclasses may override this routine to provide different
874   /// behavior.
875   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
876                                             Expr *AddrSpaceExpr,
877                                             SourceLocation AttributeLoc);
878 
879   /// Build a new function type.
880   ///
881   /// By default, performs semantic analysis when building the function type.
882   /// Subclasses may override this routine to provide different behavior.
883   QualType RebuildFunctionProtoType(QualType T,
884                                     MutableArrayRef<QualType> ParamTypes,
885                                     const FunctionProtoType::ExtProtoInfo &EPI);
886 
887   /// Build a new unprototyped function type.
888   QualType RebuildFunctionNoProtoType(QualType ResultType);
889 
890   /// Rebuild an unresolved typename type, given the decl that
891   /// the UnresolvedUsingTypenameDecl was transformed to.
892   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
893 
894   /// Build a new typedef type.
895   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
896     return SemaRef.Context.getTypeDeclType(Typedef);
897   }
898 
899   /// Build a new MacroDefined type.
900   QualType RebuildMacroQualifiedType(QualType T,
901                                      const IdentifierInfo *MacroII) {
902     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
903   }
904 
905   /// Build a new class/struct/union type.
906   QualType RebuildRecordType(RecordDecl *Record) {
907     return SemaRef.Context.getTypeDeclType(Record);
908   }
909 
910   /// Build a new Enum type.
911   QualType RebuildEnumType(EnumDecl *Enum) {
912     return SemaRef.Context.getTypeDeclType(Enum);
913   }
914 
915   /// Build a new typeof(expr) type.
916   ///
917   /// By default, performs semantic analysis when building the typeof type.
918   /// Subclasses may override this routine to provide different behavior.
919   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
920 
921   /// Build a new typeof(type) type.
922   ///
923   /// By default, builds a new TypeOfType with the given underlying type.
924   QualType RebuildTypeOfType(QualType Underlying);
925 
926   /// Build a new unary transform type.
927   QualType RebuildUnaryTransformType(QualType BaseType,
928                                      UnaryTransformType::UTTKind UKind,
929                                      SourceLocation Loc);
930 
931   /// Build a new C++11 decltype type.
932   ///
933   /// By default, performs semantic analysis when building the decltype type.
934   /// Subclasses may override this routine to provide different behavior.
935   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
936 
937   /// Build a new C++11 auto type.
938   ///
939   /// By default, builds a new AutoType with the given deduced type.
940   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
941     // Note, IsDependent is always false here: we implicitly convert an 'auto'
942     // which has been deduced to a dependent type into an undeduced 'auto', so
943     // that we'll retry deduction after the transformation.
944     return SemaRef.Context.getAutoType(Deduced, Keyword,
945                                        /*IsDependent*/ false);
946   }
947 
948   /// By default, builds a new DeducedTemplateSpecializationType with the given
949   /// deduced type.
950   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
951       QualType Deduced) {
952     return SemaRef.Context.getDeducedTemplateSpecializationType(
953         Template, Deduced, /*IsDependent*/ false);
954   }
955 
956   /// Build a new template specialization type.
957   ///
958   /// By default, performs semantic analysis when building the template
959   /// specialization type. Subclasses may override this routine to provide
960   /// different behavior.
961   QualType RebuildTemplateSpecializationType(TemplateName Template,
962                                              SourceLocation TemplateLoc,
963                                              TemplateArgumentListInfo &Args);
964 
965   /// Build a new parenthesized type.
966   ///
967   /// By default, builds a new ParenType type from the inner type.
968   /// Subclasses may override this routine to provide different behavior.
969   QualType RebuildParenType(QualType InnerType) {
970     return SemaRef.BuildParenType(InnerType);
971   }
972 
973   /// Build a new qualified name type.
974   ///
975   /// By default, builds a new ElaboratedType type from the keyword,
976   /// the nested-name-specifier and the named type.
977   /// Subclasses may override this routine to provide different behavior.
978   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
979                                  ElaboratedTypeKeyword Keyword,
980                                  NestedNameSpecifierLoc QualifierLoc,
981                                  QualType Named) {
982     return SemaRef.Context.getElaboratedType(Keyword,
983                                          QualifierLoc.getNestedNameSpecifier(),
984                                              Named);
985   }
986 
987   /// Build a new typename type that refers to a template-id.
988   ///
989   /// By default, builds a new DependentNameType type from the
990   /// nested-name-specifier and the given type. Subclasses may override
991   /// this routine to provide different behavior.
992   QualType RebuildDependentTemplateSpecializationType(
993                                           ElaboratedTypeKeyword Keyword,
994                                           NestedNameSpecifierLoc QualifierLoc,
995                                           SourceLocation TemplateKWLoc,
996                                           const IdentifierInfo *Name,
997                                           SourceLocation NameLoc,
998                                           TemplateArgumentListInfo &Args,
999                                           bool AllowInjectedClassName) {
1000     // Rebuild the template name.
1001     // TODO: avoid TemplateName abstraction
1002     CXXScopeSpec SS;
1003     SS.Adopt(QualifierLoc);
1004     TemplateName InstName = getDerived().RebuildTemplateName(
1005         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1006         AllowInjectedClassName);
1007 
1008     if (InstName.isNull())
1009       return QualType();
1010 
1011     // If it's still dependent, make a dependent specialization.
1012     if (InstName.getAsDependentTemplateName())
1013       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1014                                           QualifierLoc.getNestedNameSpecifier(),
1015                                                                     Name,
1016                                                                     Args);
1017 
1018     // Otherwise, make an elaborated type wrapping a non-dependent
1019     // specialization.
1020     QualType T =
1021     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1022     if (T.isNull()) return QualType();
1023 
1024     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1025       return T;
1026 
1027     return SemaRef.Context.getElaboratedType(Keyword,
1028                                        QualifierLoc.getNestedNameSpecifier(),
1029                                              T);
1030   }
1031 
1032   /// Build a new typename type that refers to an identifier.
1033   ///
1034   /// By default, performs semantic analysis when building the typename type
1035   /// (or elaborated type). Subclasses may override this routine to provide
1036   /// different behavior.
1037   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1038                                     SourceLocation KeywordLoc,
1039                                     NestedNameSpecifierLoc QualifierLoc,
1040                                     const IdentifierInfo *Id,
1041                                     SourceLocation IdLoc,
1042                                     bool DeducedTSTContext) {
1043     CXXScopeSpec SS;
1044     SS.Adopt(QualifierLoc);
1045 
1046     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1047       // If the name is still dependent, just build a new dependent name type.
1048       if (!SemaRef.computeDeclContext(SS))
1049         return SemaRef.Context.getDependentNameType(Keyword,
1050                                           QualifierLoc.getNestedNameSpecifier(),
1051                                                     Id);
1052     }
1053 
1054     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1055       QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1056                                              *Id, IdLoc);
1057       // If a dependent name resolves to a deduced template specialization type,
1058       // check that we're in one of the syntactic contexts permitting it.
1059       if (!DeducedTSTContext) {
1060         if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1061                 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1062           SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1063             << (int)SemaRef.getTemplateNameKindForDiagnostics(
1064                    Deduced->getTemplateName())
1065             << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1066           if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1067             SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1068           return QualType();
1069         }
1070       }
1071       return T;
1072     }
1073 
1074     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1075 
1076     // We had a dependent elaborated-type-specifier that has been transformed
1077     // into a non-dependent elaborated-type-specifier. Find the tag we're
1078     // referring to.
1079     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1080     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1081     if (!DC)
1082       return QualType();
1083 
1084     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1085       return QualType();
1086 
1087     TagDecl *Tag = nullptr;
1088     SemaRef.LookupQualifiedName(Result, DC);
1089     switch (Result.getResultKind()) {
1090       case LookupResult::NotFound:
1091       case LookupResult::NotFoundInCurrentInstantiation:
1092         break;
1093 
1094       case LookupResult::Found:
1095         Tag = Result.getAsSingle<TagDecl>();
1096         break;
1097 
1098       case LookupResult::FoundOverloaded:
1099       case LookupResult::FoundUnresolvedValue:
1100         llvm_unreachable("Tag lookup cannot find non-tags");
1101 
1102       case LookupResult::Ambiguous:
1103         // Let the LookupResult structure handle ambiguities.
1104         return QualType();
1105     }
1106 
1107     if (!Tag) {
1108       // Check where the name exists but isn't a tag type and use that to emit
1109       // better diagnostics.
1110       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1111       SemaRef.LookupQualifiedName(Result, DC);
1112       switch (Result.getResultKind()) {
1113         case LookupResult::Found:
1114         case LookupResult::FoundOverloaded:
1115         case LookupResult::FoundUnresolvedValue: {
1116           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1117           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1118           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1119                                                                << NTK << Kind;
1120           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1121           break;
1122         }
1123         default:
1124           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1125               << Kind << Id << DC << QualifierLoc.getSourceRange();
1126           break;
1127       }
1128       return QualType();
1129     }
1130 
1131     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1132                                               IdLoc, Id)) {
1133       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1134       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1135       return QualType();
1136     }
1137 
1138     // Build the elaborated-type-specifier type.
1139     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1140     return SemaRef.Context.getElaboratedType(Keyword,
1141                                          QualifierLoc.getNestedNameSpecifier(),
1142                                              T);
1143   }
1144 
1145   /// Build a new pack expansion type.
1146   ///
1147   /// By default, builds a new PackExpansionType type from the given pattern.
1148   /// Subclasses may override this routine to provide different behavior.
1149   QualType RebuildPackExpansionType(QualType Pattern,
1150                                     SourceRange PatternRange,
1151                                     SourceLocation EllipsisLoc,
1152                                     Optional<unsigned> NumExpansions) {
1153     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1154                                         NumExpansions);
1155   }
1156 
1157   /// Build a new atomic type given its value type.
1158   ///
1159   /// By default, performs semantic analysis when building the atomic type.
1160   /// Subclasses may override this routine to provide different behavior.
1161   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1162 
1163   /// Build a new pipe type given its value type.
1164   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1165                            bool isReadPipe);
1166 
1167   /// Build a new template name given a nested name specifier, a flag
1168   /// indicating whether the "template" keyword was provided, and the template
1169   /// that the template name refers to.
1170   ///
1171   /// By default, builds the new template name directly. Subclasses may override
1172   /// this routine to provide different behavior.
1173   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1174                                    bool TemplateKW,
1175                                    TemplateDecl *Template);
1176 
1177   /// Build a new template name given a nested name specifier and the
1178   /// name that is referred to as a template.
1179   ///
1180   /// By default, performs semantic analysis to determine whether the name can
1181   /// be resolved to a specific template, then builds the appropriate kind of
1182   /// template name. Subclasses may override this routine to provide different
1183   /// behavior.
1184   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1185                                    SourceLocation TemplateKWLoc,
1186                                    const IdentifierInfo &Name,
1187                                    SourceLocation NameLoc, QualType ObjectType,
1188                                    NamedDecl *FirstQualifierInScope,
1189                                    bool AllowInjectedClassName);
1190 
1191   /// Build a new template name given a nested name specifier and the
1192   /// overloaded operator name that is referred to as a template.
1193   ///
1194   /// By default, performs semantic analysis to determine whether the name can
1195   /// be resolved to a specific template, then builds the appropriate kind of
1196   /// template name. Subclasses may override this routine to provide different
1197   /// behavior.
1198   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1199                                    SourceLocation TemplateKWLoc,
1200                                    OverloadedOperatorKind Operator,
1201                                    SourceLocation NameLoc, QualType ObjectType,
1202                                    bool AllowInjectedClassName);
1203 
1204   /// Build a new template name given a template template parameter pack
1205   /// and the
1206   ///
1207   /// By default, performs semantic analysis to determine whether the name can
1208   /// be resolved to a specific template, then builds the appropriate kind of
1209   /// template name. Subclasses may override this routine to provide different
1210   /// behavior.
1211   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1212                                    const TemplateArgument &ArgPack) {
1213     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1214   }
1215 
1216   /// Build a new compound statement.
1217   ///
1218   /// By default, performs semantic analysis to build the new statement.
1219   /// Subclasses may override this routine to provide different behavior.
1220   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1221                                        MultiStmtArg Statements,
1222                                        SourceLocation RBraceLoc,
1223                                        bool IsStmtExpr) {
1224     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1225                                        IsStmtExpr);
1226   }
1227 
1228   /// Build a new case statement.
1229   ///
1230   /// By default, performs semantic analysis to build the new statement.
1231   /// Subclasses may override this routine to provide different behavior.
1232   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1233                                    Expr *LHS,
1234                                    SourceLocation EllipsisLoc,
1235                                    Expr *RHS,
1236                                    SourceLocation ColonLoc) {
1237     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1238                                    ColonLoc);
1239   }
1240 
1241   /// Attach the body to a new case statement.
1242   ///
1243   /// By default, performs semantic analysis to build the new statement.
1244   /// Subclasses may override this routine to provide different behavior.
1245   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1246     getSema().ActOnCaseStmtBody(S, Body);
1247     return S;
1248   }
1249 
1250   /// Build a new default statement.
1251   ///
1252   /// By default, performs semantic analysis to build the new statement.
1253   /// Subclasses may override this routine to provide different behavior.
1254   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1255                                       SourceLocation ColonLoc,
1256                                       Stmt *SubStmt) {
1257     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1258                                       /*CurScope=*/nullptr);
1259   }
1260 
1261   /// Build a new label statement.
1262   ///
1263   /// By default, performs semantic analysis to build the new statement.
1264   /// Subclasses may override this routine to provide different behavior.
1265   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1266                               SourceLocation ColonLoc, Stmt *SubStmt) {
1267     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1268   }
1269 
1270   /// Build a new label statement.
1271   ///
1272   /// By default, performs semantic analysis to build the new statement.
1273   /// Subclasses may override this routine to provide different behavior.
1274   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1275                                    ArrayRef<const Attr*> Attrs,
1276                                    Stmt *SubStmt) {
1277     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1278   }
1279 
1280   /// Build a new "if" statement.
1281   ///
1282   /// By default, performs semantic analysis to build the new statement.
1283   /// Subclasses may override this routine to provide different behavior.
1284   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1285                            Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1286                            SourceLocation ElseLoc, Stmt *Else) {
1287     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1288                                  ElseLoc, Else);
1289   }
1290 
1291   /// Start building a new switch statement.
1292   ///
1293   /// By default, performs semantic analysis to build the new statement.
1294   /// Subclasses may override this routine to provide different behavior.
1295   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1296                                     Sema::ConditionResult Cond) {
1297     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1298   }
1299 
1300   /// Attach the body to the switch statement.
1301   ///
1302   /// By default, performs semantic analysis to build the new statement.
1303   /// Subclasses may override this routine to provide different behavior.
1304   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1305                                    Stmt *Switch, Stmt *Body) {
1306     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1307   }
1308 
1309   /// Build a new while statement.
1310   ///
1311   /// By default, performs semantic analysis to build the new statement.
1312   /// Subclasses may override this routine to provide different behavior.
1313   StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1314                               Sema::ConditionResult Cond, Stmt *Body) {
1315     return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1316   }
1317 
1318   /// Build a new do-while statement.
1319   ///
1320   /// By default, performs semantic analysis to build the new statement.
1321   /// Subclasses may override this routine to provide different behavior.
1322   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1323                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1324                            Expr *Cond, SourceLocation RParenLoc) {
1325     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1326                                  Cond, RParenLoc);
1327   }
1328 
1329   /// Build a new for statement.
1330   ///
1331   /// By default, performs semantic analysis to build the new statement.
1332   /// Subclasses may override this routine to provide different behavior.
1333   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1334                             Stmt *Init, Sema::ConditionResult Cond,
1335                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1336                             Stmt *Body) {
1337     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1338                                   Inc, RParenLoc, Body);
1339   }
1340 
1341   /// Build a new goto statement.
1342   ///
1343   /// By default, performs semantic analysis to build the new statement.
1344   /// Subclasses may override this routine to provide different behavior.
1345   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1346                              LabelDecl *Label) {
1347     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1348   }
1349 
1350   /// Build a new indirect goto statement.
1351   ///
1352   /// By default, performs semantic analysis to build the new statement.
1353   /// Subclasses may override this routine to provide different behavior.
1354   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1355                                      SourceLocation StarLoc,
1356                                      Expr *Target) {
1357     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1358   }
1359 
1360   /// Build a new return statement.
1361   ///
1362   /// By default, performs semantic analysis to build the new statement.
1363   /// Subclasses may override this routine to provide different behavior.
1364   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1365     return getSema().BuildReturnStmt(ReturnLoc, Result);
1366   }
1367 
1368   /// Build a new declaration 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 RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1373                              SourceLocation StartLoc, SourceLocation EndLoc) {
1374     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1375     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1376   }
1377 
1378   /// Build a new inline asm statement.
1379   ///
1380   /// By default, performs semantic analysis to build the new statement.
1381   /// Subclasses may override this routine to provide different behavior.
1382   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1383                                bool IsVolatile, unsigned NumOutputs,
1384                                unsigned NumInputs, IdentifierInfo **Names,
1385                                MultiExprArg Constraints, MultiExprArg Exprs,
1386                                Expr *AsmString, MultiExprArg Clobbers,
1387                                unsigned NumLabels,
1388                                SourceLocation RParenLoc) {
1389     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1390                                      NumInputs, Names, Constraints, Exprs,
1391                                      AsmString, Clobbers, NumLabels, RParenLoc);
1392   }
1393 
1394   /// Build a new MS style inline asm statement.
1395   ///
1396   /// By default, performs semantic analysis to build the new statement.
1397   /// Subclasses may override this routine to provide different behavior.
1398   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1399                               ArrayRef<Token> AsmToks,
1400                               StringRef AsmString,
1401                               unsigned NumOutputs, unsigned NumInputs,
1402                               ArrayRef<StringRef> Constraints,
1403                               ArrayRef<StringRef> Clobbers,
1404                               ArrayRef<Expr*> Exprs,
1405                               SourceLocation EndLoc) {
1406     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1407                                     NumOutputs, NumInputs,
1408                                     Constraints, Clobbers, Exprs, EndLoc);
1409   }
1410 
1411   /// Build a new co_return 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 RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1416                                  bool IsImplicit) {
1417     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1418   }
1419 
1420   /// Build a new co_await expression.
1421   ///
1422   /// By default, performs semantic analysis to build the new expression.
1423   /// Subclasses may override this routine to provide different behavior.
1424   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1425                                 bool IsImplicit) {
1426     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1427   }
1428 
1429   /// Build a new co_await expression.
1430   ///
1431   /// By default, performs semantic analysis to build the new expression.
1432   /// Subclasses may override this routine to provide different behavior.
1433   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1434                                          Expr *Result,
1435                                          UnresolvedLookupExpr *Lookup) {
1436     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1437   }
1438 
1439   /// Build a new co_yield expression.
1440   ///
1441   /// By default, performs semantic analysis to build the new expression.
1442   /// Subclasses may override this routine to provide different behavior.
1443   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1444     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1445   }
1446 
1447   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1448     return getSema().BuildCoroutineBodyStmt(Args);
1449   }
1450 
1451   /// Build a new Objective-C \@try statement.
1452   ///
1453   /// By default, performs semantic analysis to build the new statement.
1454   /// Subclasses may override this routine to provide different behavior.
1455   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1456                                         Stmt *TryBody,
1457                                         MultiStmtArg CatchStmts,
1458                                         Stmt *Finally) {
1459     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1460                                         Finally);
1461   }
1462 
1463   /// Rebuild an Objective-C exception declaration.
1464   ///
1465   /// By default, performs semantic analysis to build the new declaration.
1466   /// Subclasses may override this routine to provide different behavior.
1467   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1468                                     TypeSourceInfo *TInfo, QualType T) {
1469     return getSema().BuildObjCExceptionDecl(TInfo, T,
1470                                             ExceptionDecl->getInnerLocStart(),
1471                                             ExceptionDecl->getLocation(),
1472                                             ExceptionDecl->getIdentifier());
1473   }
1474 
1475   /// Build a new Objective-C \@catch statement.
1476   ///
1477   /// By default, performs semantic analysis to build the new statement.
1478   /// Subclasses may override this routine to provide different behavior.
1479   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1480                                           SourceLocation RParenLoc,
1481                                           VarDecl *Var,
1482                                           Stmt *Body) {
1483     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1484                                           Var, Body);
1485   }
1486 
1487   /// Build a new Objective-C \@finally statement.
1488   ///
1489   /// By default, performs semantic analysis to build the new statement.
1490   /// Subclasses may override this routine to provide different behavior.
1491   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1492                                             Stmt *Body) {
1493     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1494   }
1495 
1496   /// Build a new Objective-C \@throw statement.
1497   ///
1498   /// By default, performs semantic analysis to build the new statement.
1499   /// Subclasses may override this routine to provide different behavior.
1500   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1501                                           Expr *Operand) {
1502     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1503   }
1504 
1505   /// Build a new OpenMP executable directive.
1506   ///
1507   /// By default, performs semantic analysis to build the new statement.
1508   /// Subclasses may override this routine to provide different behavior.
1509   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1510                                            DeclarationNameInfo DirName,
1511                                            OpenMPDirectiveKind CancelRegion,
1512                                            ArrayRef<OMPClause *> Clauses,
1513                                            Stmt *AStmt, SourceLocation StartLoc,
1514                                            SourceLocation EndLoc) {
1515     return getSema().ActOnOpenMPExecutableDirective(
1516         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1517   }
1518 
1519   /// Build a new OpenMP 'if' clause.
1520   ///
1521   /// By default, performs semantic analysis to build the new OpenMP clause.
1522   /// Subclasses may override this routine to provide different behavior.
1523   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1524                                 Expr *Condition, SourceLocation StartLoc,
1525                                 SourceLocation LParenLoc,
1526                                 SourceLocation NameModifierLoc,
1527                                 SourceLocation ColonLoc,
1528                                 SourceLocation EndLoc) {
1529     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1530                                          LParenLoc, NameModifierLoc, ColonLoc,
1531                                          EndLoc);
1532   }
1533 
1534   /// Build a new OpenMP 'final' clause.
1535   ///
1536   /// By default, performs semantic analysis to build the new OpenMP clause.
1537   /// Subclasses may override this routine to provide different behavior.
1538   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1539                                    SourceLocation LParenLoc,
1540                                    SourceLocation EndLoc) {
1541     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1542                                             EndLoc);
1543   }
1544 
1545   /// Build a new OpenMP 'num_threads' clause.
1546   ///
1547   /// By default, performs semantic analysis to build the new OpenMP clause.
1548   /// Subclasses may override this routine to provide different behavior.
1549   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1550                                         SourceLocation StartLoc,
1551                                         SourceLocation LParenLoc,
1552                                         SourceLocation EndLoc) {
1553     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1554                                                  LParenLoc, EndLoc);
1555   }
1556 
1557   /// Build a new OpenMP 'safelen' clause.
1558   ///
1559   /// By default, performs semantic analysis to build the new OpenMP clause.
1560   /// Subclasses may override this routine to provide different behavior.
1561   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1562                                      SourceLocation LParenLoc,
1563                                      SourceLocation EndLoc) {
1564     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1565   }
1566 
1567   /// Build a new OpenMP 'simdlen' clause.
1568   ///
1569   /// By default, performs semantic analysis to build the new OpenMP clause.
1570   /// Subclasses may override this routine to provide different behavior.
1571   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1572                                      SourceLocation LParenLoc,
1573                                      SourceLocation EndLoc) {
1574     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1575   }
1576 
1577   /// Build a new OpenMP 'allocator' clause.
1578   ///
1579   /// By default, performs semantic analysis to build the new OpenMP clause.
1580   /// Subclasses may override this routine to provide different behavior.
1581   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1582                                        SourceLocation LParenLoc,
1583                                        SourceLocation EndLoc) {
1584     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1585   }
1586 
1587   /// Build a new OpenMP 'collapse' clause.
1588   ///
1589   /// By default, performs semantic analysis to build the new OpenMP clause.
1590   /// Subclasses may override this routine to provide different behavior.
1591   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1592                                       SourceLocation LParenLoc,
1593                                       SourceLocation EndLoc) {
1594     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1595                                                EndLoc);
1596   }
1597 
1598   /// Build a new OpenMP 'default' clause.
1599   ///
1600   /// By default, performs semantic analysis to build the new OpenMP clause.
1601   /// Subclasses may override this routine to provide different behavior.
1602   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1603                                      SourceLocation KindKwLoc,
1604                                      SourceLocation StartLoc,
1605                                      SourceLocation LParenLoc,
1606                                      SourceLocation EndLoc) {
1607     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1608                                               StartLoc, LParenLoc, EndLoc);
1609   }
1610 
1611   /// Build a new OpenMP 'proc_bind' clause.
1612   ///
1613   /// By default, performs semantic analysis to build the new OpenMP clause.
1614   /// Subclasses may override this routine to provide different behavior.
1615   OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1616                                       SourceLocation KindKwLoc,
1617                                       SourceLocation StartLoc,
1618                                       SourceLocation LParenLoc,
1619                                       SourceLocation EndLoc) {
1620     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1621                                                StartLoc, LParenLoc, EndLoc);
1622   }
1623 
1624   /// Build a new OpenMP 'schedule' clause.
1625   ///
1626   /// By default, performs semantic analysis to build the new OpenMP clause.
1627   /// Subclasses may override this routine to provide different behavior.
1628   OMPClause *RebuildOMPScheduleClause(
1629       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1630       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1631       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1632       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1633     return getSema().ActOnOpenMPScheduleClause(
1634         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1635         CommaLoc, EndLoc);
1636   }
1637 
1638   /// Build a new OpenMP 'ordered' clause.
1639   ///
1640   /// By default, performs semantic analysis to build the new OpenMP clause.
1641   /// Subclasses may override this routine to provide different behavior.
1642   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1643                                      SourceLocation EndLoc,
1644                                      SourceLocation LParenLoc, Expr *Num) {
1645     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1646   }
1647 
1648   /// Build a new OpenMP 'private' clause.
1649   ///
1650   /// By default, performs semantic analysis to build the new OpenMP clause.
1651   /// Subclasses may override this routine to provide different behavior.
1652   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1653                                      SourceLocation StartLoc,
1654                                      SourceLocation LParenLoc,
1655                                      SourceLocation EndLoc) {
1656     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1657                                               EndLoc);
1658   }
1659 
1660   /// Build a new OpenMP 'firstprivate' clause.
1661   ///
1662   /// By default, performs semantic analysis to build the new OpenMP clause.
1663   /// Subclasses may override this routine to provide different behavior.
1664   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1665                                           SourceLocation StartLoc,
1666                                           SourceLocation LParenLoc,
1667                                           SourceLocation EndLoc) {
1668     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1669                                                    EndLoc);
1670   }
1671 
1672   /// Build a new OpenMP 'lastprivate' clause.
1673   ///
1674   /// By default, performs semantic analysis to build the new OpenMP clause.
1675   /// Subclasses may override this routine to provide different behavior.
1676   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1677                                          SourceLocation StartLoc,
1678                                          SourceLocation LParenLoc,
1679                                          SourceLocation EndLoc) {
1680     return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1681                                                   EndLoc);
1682   }
1683 
1684   /// Build a new OpenMP 'shared' 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 *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1689                                     SourceLocation StartLoc,
1690                                     SourceLocation LParenLoc,
1691                                     SourceLocation EndLoc) {
1692     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1693                                              EndLoc);
1694   }
1695 
1696   /// Build a new OpenMP 'reduction' clause.
1697   ///
1698   /// By default, performs semantic analysis to build the new statement.
1699   /// Subclasses may override this routine to provide different behavior.
1700   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1701                                        SourceLocation StartLoc,
1702                                        SourceLocation LParenLoc,
1703                                        SourceLocation ColonLoc,
1704                                        SourceLocation EndLoc,
1705                                        CXXScopeSpec &ReductionIdScopeSpec,
1706                                        const DeclarationNameInfo &ReductionId,
1707                                        ArrayRef<Expr *> UnresolvedReductions) {
1708     return getSema().ActOnOpenMPReductionClause(
1709         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1710         ReductionId, UnresolvedReductions);
1711   }
1712 
1713   /// Build a new OpenMP 'task_reduction' clause.
1714   ///
1715   /// By default, performs semantic analysis to build the new statement.
1716   /// Subclasses may override this routine to provide different behavior.
1717   OMPClause *RebuildOMPTaskReductionClause(
1718       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1719       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1720       CXXScopeSpec &ReductionIdScopeSpec,
1721       const DeclarationNameInfo &ReductionId,
1722       ArrayRef<Expr *> UnresolvedReductions) {
1723     return getSema().ActOnOpenMPTaskReductionClause(
1724         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1725         ReductionId, UnresolvedReductions);
1726   }
1727 
1728   /// Build a new OpenMP 'in_reduction' clause.
1729   ///
1730   /// By default, performs semantic analysis to build the new statement.
1731   /// Subclasses may override this routine to provide different behavior.
1732   OMPClause *
1733   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1734                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1735                               SourceLocation EndLoc,
1736                               CXXScopeSpec &ReductionIdScopeSpec,
1737                               const DeclarationNameInfo &ReductionId,
1738                               ArrayRef<Expr *> UnresolvedReductions) {
1739     return getSema().ActOnOpenMPInReductionClause(
1740         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1741         ReductionId, UnresolvedReductions);
1742   }
1743 
1744   /// Build a new OpenMP 'linear' clause.
1745   ///
1746   /// By default, performs semantic analysis to build the new OpenMP clause.
1747   /// Subclasses may override this routine to provide different behavior.
1748   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1749                                     SourceLocation StartLoc,
1750                                     SourceLocation LParenLoc,
1751                                     OpenMPLinearClauseKind Modifier,
1752                                     SourceLocation ModifierLoc,
1753                                     SourceLocation ColonLoc,
1754                                     SourceLocation EndLoc) {
1755     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1756                                              Modifier, ModifierLoc, ColonLoc,
1757                                              EndLoc);
1758   }
1759 
1760   /// Build a new OpenMP 'aligned' clause.
1761   ///
1762   /// By default, performs semantic analysis to build the new OpenMP clause.
1763   /// Subclasses may override this routine to provide different behavior.
1764   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1765                                      SourceLocation StartLoc,
1766                                      SourceLocation LParenLoc,
1767                                      SourceLocation ColonLoc,
1768                                      SourceLocation EndLoc) {
1769     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1770                                               LParenLoc, ColonLoc, EndLoc);
1771   }
1772 
1773   /// Build a new OpenMP 'copyin' clause.
1774   ///
1775   /// By default, performs semantic analysis to build the new OpenMP clause.
1776   /// Subclasses may override this routine to provide different behavior.
1777   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1778                                     SourceLocation StartLoc,
1779                                     SourceLocation LParenLoc,
1780                                     SourceLocation EndLoc) {
1781     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1782                                              EndLoc);
1783   }
1784 
1785   /// Build a new OpenMP 'copyprivate' clause.
1786   ///
1787   /// By default, performs semantic analysis to build the new OpenMP clause.
1788   /// Subclasses may override this routine to provide different behavior.
1789   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1790                                          SourceLocation StartLoc,
1791                                          SourceLocation LParenLoc,
1792                                          SourceLocation EndLoc) {
1793     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1794                                                   EndLoc);
1795   }
1796 
1797   /// Build a new OpenMP 'flush' pseudo 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 *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1802                                    SourceLocation StartLoc,
1803                                    SourceLocation LParenLoc,
1804                                    SourceLocation EndLoc) {
1805     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1806                                             EndLoc);
1807   }
1808 
1809   /// Build a new OpenMP 'depend' pseudo clause.
1810   ///
1811   /// By default, performs semantic analysis to build the new OpenMP clause.
1812   /// Subclasses may override this routine to provide different behavior.
1813   OMPClause *
1814   RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1815                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1816                          SourceLocation StartLoc, SourceLocation LParenLoc,
1817                          SourceLocation EndLoc) {
1818     return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1819                                              StartLoc, LParenLoc, EndLoc);
1820   }
1821 
1822   /// Build a new OpenMP 'device' clause.
1823   ///
1824   /// By default, performs semantic analysis to build the new statement.
1825   /// Subclasses may override this routine to provide different behavior.
1826   OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1827                                     SourceLocation LParenLoc,
1828                                     SourceLocation EndLoc) {
1829     return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1830                                              EndLoc);
1831   }
1832 
1833   /// Build a new OpenMP 'map' clause.
1834   ///
1835   /// By default, performs semantic analysis to build the new OpenMP clause.
1836   /// Subclasses may override this routine to provide different behavior.
1837   OMPClause *RebuildOMPMapClause(
1838       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1839       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1840       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1841       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1842       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1843       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1844     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1845                                           MapperIdScopeSpec, MapperId, MapType,
1846                                           IsMapTypeImplicit, MapLoc, ColonLoc,
1847                                           VarList, Locs, UnresolvedMappers);
1848   }
1849 
1850   /// Build a new OpenMP 'allocate' clause.
1851   ///
1852   /// By default, performs semantic analysis to build the new OpenMP clause.
1853   /// Subclasses may override this routine to provide different behavior.
1854   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1855                                       SourceLocation StartLoc,
1856                                       SourceLocation LParenLoc,
1857                                       SourceLocation ColonLoc,
1858                                       SourceLocation EndLoc) {
1859     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1860                                                LParenLoc, ColonLoc, EndLoc);
1861   }
1862 
1863   /// Build a new OpenMP 'num_teams' clause.
1864   ///
1865   /// By default, performs semantic analysis to build the new statement.
1866   /// Subclasses may override this routine to provide different behavior.
1867   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1868                                       SourceLocation LParenLoc,
1869                                       SourceLocation EndLoc) {
1870     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1871                                                EndLoc);
1872   }
1873 
1874   /// Build a new OpenMP 'thread_limit' 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 *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1879                                          SourceLocation StartLoc,
1880                                          SourceLocation LParenLoc,
1881                                          SourceLocation EndLoc) {
1882     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1883                                                   LParenLoc, EndLoc);
1884   }
1885 
1886   /// Build a new OpenMP 'priority' clause.
1887   ///
1888   /// By default, performs semantic analysis to build the new statement.
1889   /// Subclasses may override this routine to provide different behavior.
1890   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1891                                       SourceLocation LParenLoc,
1892                                       SourceLocation EndLoc) {
1893     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1894                                                EndLoc);
1895   }
1896 
1897   /// Build a new OpenMP 'grainsize' clause.
1898   ///
1899   /// By default, performs semantic analysis to build the new statement.
1900   /// Subclasses may override this routine to provide different behavior.
1901   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1902                                        SourceLocation LParenLoc,
1903                                        SourceLocation EndLoc) {
1904     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1905                                                 EndLoc);
1906   }
1907 
1908   /// Build a new OpenMP 'num_tasks' clause.
1909   ///
1910   /// By default, performs semantic analysis to build the new statement.
1911   /// Subclasses may override this routine to provide different behavior.
1912   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1913                                       SourceLocation LParenLoc,
1914                                       SourceLocation EndLoc) {
1915     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1916                                                EndLoc);
1917   }
1918 
1919   /// Build a new OpenMP 'hint' clause.
1920   ///
1921   /// By default, performs semantic analysis to build the new statement.
1922   /// Subclasses may override this routine to provide different behavior.
1923   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1924                                   SourceLocation LParenLoc,
1925                                   SourceLocation EndLoc) {
1926     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1927   }
1928 
1929   /// Build a new OpenMP 'dist_schedule' clause.
1930   ///
1931   /// By default, performs semantic analysis to build the new OpenMP clause.
1932   /// Subclasses may override this routine to provide different behavior.
1933   OMPClause *
1934   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1935                                Expr *ChunkSize, SourceLocation StartLoc,
1936                                SourceLocation LParenLoc, SourceLocation KindLoc,
1937                                SourceLocation CommaLoc, SourceLocation EndLoc) {
1938     return getSema().ActOnOpenMPDistScheduleClause(
1939         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1940   }
1941 
1942   /// Build a new OpenMP 'to' clause.
1943   ///
1944   /// By default, performs semantic analysis to build the new statement.
1945   /// Subclasses may override this routine to provide different behavior.
1946   OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1947                                 CXXScopeSpec &MapperIdScopeSpec,
1948                                 DeclarationNameInfo &MapperId,
1949                                 const OMPVarListLocTy &Locs,
1950                                 ArrayRef<Expr *> UnresolvedMappers) {
1951     return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1952                                          Locs, UnresolvedMappers);
1953   }
1954 
1955   /// Build a new OpenMP 'from' clause.
1956   ///
1957   /// By default, performs semantic analysis to build the new statement.
1958   /// Subclasses may override this routine to provide different behavior.
1959   OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1960                                   CXXScopeSpec &MapperIdScopeSpec,
1961                                   DeclarationNameInfo &MapperId,
1962                                   const OMPVarListLocTy &Locs,
1963                                   ArrayRef<Expr *> UnresolvedMappers) {
1964     return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1965                                            Locs, UnresolvedMappers);
1966   }
1967 
1968   /// Build a new OpenMP 'use_device_ptr' clause.
1969   ///
1970   /// By default, performs semantic analysis to build the new OpenMP clause.
1971   /// Subclasses may override this routine to provide different behavior.
1972   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1973                                           const OMPVarListLocTy &Locs) {
1974     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1975   }
1976 
1977   /// Build a new OpenMP 'is_device_ptr' clause.
1978   ///
1979   /// By default, performs semantic analysis to build the new OpenMP clause.
1980   /// Subclasses may override this routine to provide different behavior.
1981   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1982                                          const OMPVarListLocTy &Locs) {
1983     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1984   }
1985 
1986   /// Rebuild the operand to an Objective-C \@synchronized statement.
1987   ///
1988   /// By default, performs semantic analysis to build the new statement.
1989   /// Subclasses may override this routine to provide different behavior.
1990   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1991                                               Expr *object) {
1992     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1993   }
1994 
1995   /// Build a new Objective-C \@synchronized statement.
1996   ///
1997   /// By default, performs semantic analysis to build the new statement.
1998   /// Subclasses may override this routine to provide different behavior.
1999   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2000                                            Expr *Object, Stmt *Body) {
2001     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2002   }
2003 
2004   /// Build a new Objective-C \@autoreleasepool statement.
2005   ///
2006   /// By default, performs semantic analysis to build the new statement.
2007   /// Subclasses may override this routine to provide different behavior.
2008   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2009                                             Stmt *Body) {
2010     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2011   }
2012 
2013   /// Build a new Objective-C fast enumeration statement.
2014   ///
2015   /// By default, performs semantic analysis to build the new statement.
2016   /// Subclasses may override this routine to provide different behavior.
2017   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2018                                           Stmt *Element,
2019                                           Expr *Collection,
2020                                           SourceLocation RParenLoc,
2021                                           Stmt *Body) {
2022     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2023                                                 Element,
2024                                                 Collection,
2025                                                 RParenLoc);
2026     if (ForEachStmt.isInvalid())
2027       return StmtError();
2028 
2029     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2030   }
2031 
2032   /// Build a new C++ exception declaration.
2033   ///
2034   /// By default, performs semantic analysis to build the new decaration.
2035   /// Subclasses may override this routine to provide different behavior.
2036   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2037                                 TypeSourceInfo *Declarator,
2038                                 SourceLocation StartLoc,
2039                                 SourceLocation IdLoc,
2040                                 IdentifierInfo *Id) {
2041     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2042                                                        StartLoc, IdLoc, Id);
2043     if (Var)
2044       getSema().CurContext->addDecl(Var);
2045     return Var;
2046   }
2047 
2048   /// Build a new C++ catch statement.
2049   ///
2050   /// By default, performs semantic analysis to build the new statement.
2051   /// Subclasses may override this routine to provide different behavior.
2052   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2053                                  VarDecl *ExceptionDecl,
2054                                  Stmt *Handler) {
2055     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2056                                                       Handler));
2057   }
2058 
2059   /// Build a new C++ try statement.
2060   ///
2061   /// By default, performs semantic analysis to build the new statement.
2062   /// Subclasses may override this routine to provide different behavior.
2063   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2064                                ArrayRef<Stmt *> Handlers) {
2065     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2066   }
2067 
2068   /// Build a new C++0x range-based for statement.
2069   ///
2070   /// By default, performs semantic analysis to build the new statement.
2071   /// Subclasses may override this routine to provide different behavior.
2072   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2073                                     SourceLocation CoawaitLoc, Stmt *Init,
2074                                     SourceLocation ColonLoc, Stmt *Range,
2075                                     Stmt *Begin, Stmt *End, Expr *Cond,
2076                                     Expr *Inc, Stmt *LoopVar,
2077                                     SourceLocation RParenLoc) {
2078     // If we've just learned that the range is actually an Objective-C
2079     // collection, treat this as an Objective-C fast enumeration loop.
2080     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2081       if (RangeStmt->isSingleDecl()) {
2082         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2083           if (RangeVar->isInvalidDecl())
2084             return StmtError();
2085 
2086           Expr *RangeExpr = RangeVar->getInit();
2087           if (!RangeExpr->isTypeDependent() &&
2088               RangeExpr->getType()->isObjCObjectPointerType()) {
2089             // FIXME: Support init-statements in Objective-C++20 ranged for
2090             // statement.
2091             if (Init) {
2092               return SemaRef.Diag(Init->getBeginLoc(),
2093                                   diag::err_objc_for_range_init_stmt)
2094                          << Init->getSourceRange();
2095             }
2096             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2097                                                         RangeExpr, RParenLoc);
2098           }
2099         }
2100       }
2101     }
2102 
2103     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2104                                           Range, Begin, End, Cond, Inc, LoopVar,
2105                                           RParenLoc, Sema::BFRK_Rebuild);
2106   }
2107 
2108   /// Build a new C++0x range-based for statement.
2109   ///
2110   /// By default, performs semantic analysis to build the new statement.
2111   /// Subclasses may override this routine to provide different behavior.
2112   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2113                                           bool IsIfExists,
2114                                           NestedNameSpecifierLoc QualifierLoc,
2115                                           DeclarationNameInfo NameInfo,
2116                                           Stmt *Nested) {
2117     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2118                                                 QualifierLoc, NameInfo, Nested);
2119   }
2120 
2121   /// Attach body to a C++0x range-based for statement.
2122   ///
2123   /// By default, performs semantic analysis to finish the new statement.
2124   /// Subclasses may override this routine to provide different behavior.
2125   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2126     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2127   }
2128 
2129   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2130                                Stmt *TryBlock, Stmt *Handler) {
2131     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2132   }
2133 
2134   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2135                                   Stmt *Block) {
2136     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2137   }
2138 
2139   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2140     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2141   }
2142 
2143   /// Build a new predefined expression.
2144   ///
2145   /// By default, performs semantic analysis to build the new expression.
2146   /// Subclasses may override this routine to provide different behavior.
2147   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2148                                    PredefinedExpr::IdentKind IK) {
2149     return getSema().BuildPredefinedExpr(Loc, IK);
2150   }
2151 
2152   /// Build a new expression that references a declaration.
2153   ///
2154   /// By default, performs semantic analysis to build the new expression.
2155   /// Subclasses may override this routine to provide different behavior.
2156   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2157                                         LookupResult &R,
2158                                         bool RequiresADL) {
2159     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2160   }
2161 
2162 
2163   /// Build a new expression that references a declaration.
2164   ///
2165   /// By default, performs semantic analysis to build the new expression.
2166   /// Subclasses may override this routine to provide different behavior.
2167   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2168                                 ValueDecl *VD,
2169                                 const DeclarationNameInfo &NameInfo,
2170                                 NamedDecl *Found,
2171                                 TemplateArgumentListInfo *TemplateArgs) {
2172     CXXScopeSpec SS;
2173     SS.Adopt(QualifierLoc);
2174     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2175                                               TemplateArgs);
2176   }
2177 
2178   /// Build a new expression in parentheses.
2179   ///
2180   /// By default, performs semantic analysis to build the new expression.
2181   /// Subclasses may override this routine to provide different behavior.
2182   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2183                                     SourceLocation RParen) {
2184     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2185   }
2186 
2187   /// Build a new pseudo-destructor expression.
2188   ///
2189   /// By default, performs semantic analysis to build the new expression.
2190   /// Subclasses may override this routine to provide different behavior.
2191   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2192                                             SourceLocation OperatorLoc,
2193                                             bool isArrow,
2194                                             CXXScopeSpec &SS,
2195                                             TypeSourceInfo *ScopeType,
2196                                             SourceLocation CCLoc,
2197                                             SourceLocation TildeLoc,
2198                                         PseudoDestructorTypeStorage Destroyed);
2199 
2200   /// Build a new unary operator expression.
2201   ///
2202   /// By default, performs semantic analysis to build the new expression.
2203   /// Subclasses may override this routine to provide different behavior.
2204   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2205                                         UnaryOperatorKind Opc,
2206                                         Expr *SubExpr) {
2207     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2208   }
2209 
2210   /// Build a new builtin offsetof expression.
2211   ///
2212   /// By default, performs semantic analysis to build the new expression.
2213   /// Subclasses may override this routine to provide different behavior.
2214   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2215                                  TypeSourceInfo *Type,
2216                                  ArrayRef<Sema::OffsetOfComponent> Components,
2217                                  SourceLocation RParenLoc) {
2218     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2219                                           RParenLoc);
2220   }
2221 
2222   /// Build a new sizeof, alignof or vec_step expression with a
2223   /// type argument.
2224   ///
2225   /// By default, performs semantic analysis to build the new expression.
2226   /// Subclasses may override this routine to provide different behavior.
2227   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2228                                          SourceLocation OpLoc,
2229                                          UnaryExprOrTypeTrait ExprKind,
2230                                          SourceRange R) {
2231     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2232   }
2233 
2234   /// Build a new sizeof, alignof or vec step expression with an
2235   /// expression argument.
2236   ///
2237   /// By default, performs semantic analysis to build the new expression.
2238   /// Subclasses may override this routine to provide different behavior.
2239   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2240                                          UnaryExprOrTypeTrait ExprKind,
2241                                          SourceRange R) {
2242     ExprResult Result
2243       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2244     if (Result.isInvalid())
2245       return ExprError();
2246 
2247     return Result;
2248   }
2249 
2250   /// Build a new array subscript expression.
2251   ///
2252   /// By default, performs semantic analysis to build the new expression.
2253   /// Subclasses may override this routine to provide different behavior.
2254   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2255                                              SourceLocation LBracketLoc,
2256                                              Expr *RHS,
2257                                              SourceLocation RBracketLoc) {
2258     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2259                                              LBracketLoc, RHS,
2260                                              RBracketLoc);
2261   }
2262 
2263   /// Build a new array section expression.
2264   ///
2265   /// By default, performs semantic analysis to build the new expression.
2266   /// Subclasses may override this routine to provide different behavior.
2267   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2268                                         Expr *LowerBound,
2269                                         SourceLocation ColonLoc, Expr *Length,
2270                                         SourceLocation RBracketLoc) {
2271     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2272                                               ColonLoc, Length, RBracketLoc);
2273   }
2274 
2275   /// Build a new call expression.
2276   ///
2277   /// By default, performs semantic analysis to build the new expression.
2278   /// Subclasses may override this routine to provide different behavior.
2279   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2280                                    MultiExprArg Args,
2281                                    SourceLocation RParenLoc,
2282                                    Expr *ExecConfig = nullptr) {
2283     return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2284                                    RParenLoc, ExecConfig);
2285   }
2286 
2287   /// Build a new member access expression.
2288   ///
2289   /// By default, performs semantic analysis to build the new expression.
2290   /// Subclasses may override this routine to provide different behavior.
2291   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2292                                bool isArrow,
2293                                NestedNameSpecifierLoc QualifierLoc,
2294                                SourceLocation TemplateKWLoc,
2295                                const DeclarationNameInfo &MemberNameInfo,
2296                                ValueDecl *Member,
2297                                NamedDecl *FoundDecl,
2298                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2299                                NamedDecl *FirstQualifierInScope) {
2300     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2301                                                                       isArrow);
2302     if (!Member->getDeclName()) {
2303       // We have a reference to an unnamed field.  This is always the
2304       // base of an anonymous struct/union member access, i.e. the
2305       // field is always of record type.
2306       assert(Member->getType()->isRecordType() &&
2307              "unnamed member not of record type?");
2308 
2309       BaseResult =
2310         getSema().PerformObjectMemberConversion(BaseResult.get(),
2311                                                 QualifierLoc.getNestedNameSpecifier(),
2312                                                 FoundDecl, Member);
2313       if (BaseResult.isInvalid())
2314         return ExprError();
2315       Base = BaseResult.get();
2316 
2317       CXXScopeSpec EmptySS;
2318       return getSema().BuildFieldReferenceExpr(
2319           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2320           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2321     }
2322 
2323     CXXScopeSpec SS;
2324     SS.Adopt(QualifierLoc);
2325 
2326     Base = BaseResult.get();
2327     QualType BaseType = Base->getType();
2328 
2329     if (isArrow && !BaseType->isPointerType())
2330       return ExprError();
2331 
2332     // FIXME: this involves duplicating earlier analysis in a lot of
2333     // cases; we should avoid this when possible.
2334     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2335     R.addDecl(FoundDecl);
2336     R.resolveKind();
2337 
2338     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2339                                               SS, TemplateKWLoc,
2340                                               FirstQualifierInScope,
2341                                               R, ExplicitTemplateArgs,
2342                                               /*S*/nullptr);
2343   }
2344 
2345   /// Build a new binary operator expression.
2346   ///
2347   /// By default, performs semantic analysis to build the new expression.
2348   /// Subclasses may override this routine to provide different behavior.
2349   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2350                                          BinaryOperatorKind Opc,
2351                                          Expr *LHS, Expr *RHS) {
2352     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2353   }
2354 
2355   /// Build a new conditional operator expression.
2356   ///
2357   /// By default, performs semantic analysis to build the new expression.
2358   /// Subclasses may override this routine to provide different behavior.
2359   ExprResult RebuildConditionalOperator(Expr *Cond,
2360                                         SourceLocation QuestionLoc,
2361                                         Expr *LHS,
2362                                         SourceLocation ColonLoc,
2363                                         Expr *RHS) {
2364     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2365                                         LHS, RHS);
2366   }
2367 
2368   /// Build a new C-style cast expression.
2369   ///
2370   /// By default, performs semantic analysis to build the new expression.
2371   /// Subclasses may override this routine to provide different behavior.
2372   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2373                                          TypeSourceInfo *TInfo,
2374                                          SourceLocation RParenLoc,
2375                                          Expr *SubExpr) {
2376     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2377                                          SubExpr);
2378   }
2379 
2380   /// Build a new compound literal expression.
2381   ///
2382   /// By default, performs semantic analysis to build the new expression.
2383   /// Subclasses may override this routine to provide different behavior.
2384   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2385                                               TypeSourceInfo *TInfo,
2386                                               SourceLocation RParenLoc,
2387                                               Expr *Init) {
2388     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2389                                               Init);
2390   }
2391 
2392   /// Build a new extended vector element access expression.
2393   ///
2394   /// By default, performs semantic analysis to build the new expression.
2395   /// Subclasses may override this routine to provide different behavior.
2396   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2397                                                SourceLocation OpLoc,
2398                                                SourceLocation AccessorLoc,
2399                                                IdentifierInfo &Accessor) {
2400 
2401     CXXScopeSpec SS;
2402     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2403     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2404                                               OpLoc, /*IsArrow*/ false,
2405                                               SS, SourceLocation(),
2406                                               /*FirstQualifierInScope*/ nullptr,
2407                                               NameInfo,
2408                                               /* TemplateArgs */ nullptr,
2409                                               /*S*/ nullptr);
2410   }
2411 
2412   /// Build a new initializer list expression.
2413   ///
2414   /// By default, performs semantic analysis to build the new expression.
2415   /// Subclasses may override this routine to provide different behavior.
2416   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2417                              MultiExprArg Inits,
2418                              SourceLocation RBraceLoc) {
2419     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2420   }
2421 
2422   /// Build a new designated initializer expression.
2423   ///
2424   /// By default, performs semantic analysis to build the new expression.
2425   /// Subclasses may override this routine to provide different behavior.
2426   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2427                                              MultiExprArg ArrayExprs,
2428                                              SourceLocation EqualOrColonLoc,
2429                                              bool GNUSyntax,
2430                                              Expr *Init) {
2431     ExprResult Result
2432       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2433                                            Init);
2434     if (Result.isInvalid())
2435       return ExprError();
2436 
2437     return Result;
2438   }
2439 
2440   /// Build a new value-initialized expression.
2441   ///
2442   /// By default, builds the implicit value initialization without performing
2443   /// any semantic analysis. Subclasses may override this routine to provide
2444   /// different behavior.
2445   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2446     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2447   }
2448 
2449   /// Build a new \c va_arg expression.
2450   ///
2451   /// By default, performs semantic analysis to build the new expression.
2452   /// Subclasses may override this routine to provide different behavior.
2453   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2454                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2455                                     SourceLocation RParenLoc) {
2456     return getSema().BuildVAArgExpr(BuiltinLoc,
2457                                     SubExpr, TInfo,
2458                                     RParenLoc);
2459   }
2460 
2461   /// Build a new expression list in parentheses.
2462   ///
2463   /// By default, performs semantic analysis to build the new expression.
2464   /// Subclasses may override this routine to provide different behavior.
2465   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2466                                   MultiExprArg SubExprs,
2467                                   SourceLocation RParenLoc) {
2468     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2469   }
2470 
2471   /// Build a new address-of-label expression.
2472   ///
2473   /// By default, performs semantic analysis, using the name of the label
2474   /// rather than attempting to map the label statement itself.
2475   /// Subclasses may override this routine to provide different behavior.
2476   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2477                                   SourceLocation LabelLoc, LabelDecl *Label) {
2478     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2479   }
2480 
2481   /// Build a new GNU statement expression.
2482   ///
2483   /// By default, performs semantic analysis to build the new expression.
2484   /// Subclasses may override this routine to provide different behavior.
2485   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2486                                    Stmt *SubStmt,
2487                                    SourceLocation RParenLoc) {
2488     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2489   }
2490 
2491   /// Build a new __builtin_choose_expr expression.
2492   ///
2493   /// By default, performs semantic analysis to build the new expression.
2494   /// Subclasses may override this routine to provide different behavior.
2495   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2496                                      Expr *Cond, Expr *LHS, Expr *RHS,
2497                                      SourceLocation RParenLoc) {
2498     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2499                                    Cond, LHS, RHS,
2500                                    RParenLoc);
2501   }
2502 
2503   /// Build a new generic selection expression.
2504   ///
2505   /// By default, performs semantic analysis to build the new expression.
2506   /// Subclasses may override this routine to provide different behavior.
2507   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2508                                          SourceLocation DefaultLoc,
2509                                          SourceLocation RParenLoc,
2510                                          Expr *ControllingExpr,
2511                                          ArrayRef<TypeSourceInfo *> Types,
2512                                          ArrayRef<Expr *> Exprs) {
2513     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2514                                                 ControllingExpr, Types, Exprs);
2515   }
2516 
2517   /// Build a new overloaded operator call expression.
2518   ///
2519   /// By default, performs semantic analysis to build the new expression.
2520   /// The semantic analysis provides the behavior of template instantiation,
2521   /// copying with transformations that turn what looks like an overloaded
2522   /// operator call into a use of a builtin operator, performing
2523   /// argument-dependent lookup, etc. Subclasses may override this routine to
2524   /// provide different behavior.
2525   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2526                                               SourceLocation OpLoc,
2527                                               Expr *Callee,
2528                                               Expr *First,
2529                                               Expr *Second);
2530 
2531   /// Build a new C++ "named" cast expression, such as static_cast or
2532   /// reinterpret_cast.
2533   ///
2534   /// By default, this routine dispatches to one of the more-specific routines
2535   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2536   /// Subclasses may override this routine to provide different behavior.
2537   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2538                                            Stmt::StmtClass Class,
2539                                            SourceLocation LAngleLoc,
2540                                            TypeSourceInfo *TInfo,
2541                                            SourceLocation RAngleLoc,
2542                                            SourceLocation LParenLoc,
2543                                            Expr *SubExpr,
2544                                            SourceLocation RParenLoc) {
2545     switch (Class) {
2546     case Stmt::CXXStaticCastExprClass:
2547       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2548                                                    RAngleLoc, LParenLoc,
2549                                                    SubExpr, RParenLoc);
2550 
2551     case Stmt::CXXDynamicCastExprClass:
2552       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2553                                                     RAngleLoc, LParenLoc,
2554                                                     SubExpr, RParenLoc);
2555 
2556     case Stmt::CXXReinterpretCastExprClass:
2557       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2558                                                         RAngleLoc, LParenLoc,
2559                                                         SubExpr,
2560                                                         RParenLoc);
2561 
2562     case Stmt::CXXConstCastExprClass:
2563       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2564                                                    RAngleLoc, LParenLoc,
2565                                                    SubExpr, RParenLoc);
2566 
2567     default:
2568       llvm_unreachable("Invalid C++ named cast");
2569     }
2570   }
2571 
2572   /// Build a new C++ static_cast expression.
2573   ///
2574   /// By default, performs semantic analysis to build the new expression.
2575   /// Subclasses may override this routine to provide different behavior.
2576   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2577                                             SourceLocation LAngleLoc,
2578                                             TypeSourceInfo *TInfo,
2579                                             SourceLocation RAngleLoc,
2580                                             SourceLocation LParenLoc,
2581                                             Expr *SubExpr,
2582                                             SourceLocation RParenLoc) {
2583     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2584                                        TInfo, SubExpr,
2585                                        SourceRange(LAngleLoc, RAngleLoc),
2586                                        SourceRange(LParenLoc, RParenLoc));
2587   }
2588 
2589   /// Build a new C++ dynamic_cast expression.
2590   ///
2591   /// By default, performs semantic analysis to build the new expression.
2592   /// Subclasses may override this routine to provide different behavior.
2593   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2594                                              SourceLocation LAngleLoc,
2595                                              TypeSourceInfo *TInfo,
2596                                              SourceLocation RAngleLoc,
2597                                              SourceLocation LParenLoc,
2598                                              Expr *SubExpr,
2599                                              SourceLocation RParenLoc) {
2600     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2601                                        TInfo, SubExpr,
2602                                        SourceRange(LAngleLoc, RAngleLoc),
2603                                        SourceRange(LParenLoc, RParenLoc));
2604   }
2605 
2606   /// Build a new C++ reinterpret_cast expression.
2607   ///
2608   /// By default, performs semantic analysis to build the new expression.
2609   /// Subclasses may override this routine to provide different behavior.
2610   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2611                                                  SourceLocation LAngleLoc,
2612                                                  TypeSourceInfo *TInfo,
2613                                                  SourceLocation RAngleLoc,
2614                                                  SourceLocation LParenLoc,
2615                                                  Expr *SubExpr,
2616                                                  SourceLocation RParenLoc) {
2617     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2618                                        TInfo, SubExpr,
2619                                        SourceRange(LAngleLoc, RAngleLoc),
2620                                        SourceRange(LParenLoc, RParenLoc));
2621   }
2622 
2623   /// Build a new C++ const_cast expression.
2624   ///
2625   /// By default, performs semantic analysis to build the new expression.
2626   /// Subclasses may override this routine to provide different behavior.
2627   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2628                                            SourceLocation LAngleLoc,
2629                                            TypeSourceInfo *TInfo,
2630                                            SourceLocation RAngleLoc,
2631                                            SourceLocation LParenLoc,
2632                                            Expr *SubExpr,
2633                                            SourceLocation RParenLoc) {
2634     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2635                                        TInfo, SubExpr,
2636                                        SourceRange(LAngleLoc, RAngleLoc),
2637                                        SourceRange(LParenLoc, RParenLoc));
2638   }
2639 
2640   /// Build a new C++ functional-style cast expression.
2641   ///
2642   /// By default, performs semantic analysis to build the new expression.
2643   /// Subclasses may override this routine to provide different behavior.
2644   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2645                                           SourceLocation LParenLoc,
2646                                           Expr *Sub,
2647                                           SourceLocation RParenLoc,
2648                                           bool ListInitialization) {
2649     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2650                                                MultiExprArg(&Sub, 1), RParenLoc,
2651                                                ListInitialization);
2652   }
2653 
2654   /// Build a new C++ __builtin_bit_cast expression.
2655   ///
2656   /// By default, performs semantic analysis to build the new expression.
2657   /// Subclasses may override this routine to provide different behavior.
2658   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2659                                        TypeSourceInfo *TSI, Expr *Sub,
2660                                        SourceLocation RParenLoc) {
2661     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2662   }
2663 
2664   /// Build a new C++ typeid(type) expression.
2665   ///
2666   /// By default, performs semantic analysis to build the new expression.
2667   /// Subclasses may override this routine to provide different behavior.
2668   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2669                                         SourceLocation TypeidLoc,
2670                                         TypeSourceInfo *Operand,
2671                                         SourceLocation RParenLoc) {
2672     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2673                                     RParenLoc);
2674   }
2675 
2676 
2677   /// Build a new C++ typeid(expr) expression.
2678   ///
2679   /// By default, performs semantic analysis to build the new expression.
2680   /// Subclasses may override this routine to provide different behavior.
2681   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2682                                         SourceLocation TypeidLoc,
2683                                         Expr *Operand,
2684                                         SourceLocation RParenLoc) {
2685     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2686                                     RParenLoc);
2687   }
2688 
2689   /// Build a new C++ __uuidof(type) expression.
2690   ///
2691   /// By default, performs semantic analysis to build the new expression.
2692   /// Subclasses may override this routine to provide different behavior.
2693   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2694                                         SourceLocation TypeidLoc,
2695                                         TypeSourceInfo *Operand,
2696                                         SourceLocation RParenLoc) {
2697     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2698                                     RParenLoc);
2699   }
2700 
2701   /// Build a new C++ __uuidof(expr) expression.
2702   ///
2703   /// By default, performs semantic analysis to build the new expression.
2704   /// Subclasses may override this routine to provide different behavior.
2705   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2706                                         SourceLocation TypeidLoc,
2707                                         Expr *Operand,
2708                                         SourceLocation RParenLoc) {
2709     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2710                                     RParenLoc);
2711   }
2712 
2713   /// Build a new C++ "this" expression.
2714   ///
2715   /// By default, builds a new "this" expression without performing any
2716   /// semantic analysis. Subclasses may override this routine to provide
2717   /// different behavior.
2718   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2719                                 QualType ThisType,
2720                                 bool isImplicit) {
2721     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2722   }
2723 
2724   /// Build a new C++ throw expression.
2725   ///
2726   /// By default, performs semantic analysis to build the new expression.
2727   /// Subclasses may override this routine to provide different behavior.
2728   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2729                                  bool IsThrownVariableInScope) {
2730     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2731   }
2732 
2733   /// Build a new C++ default-argument expression.
2734   ///
2735   /// By default, builds a new default-argument expression, which does not
2736   /// require any semantic analysis. Subclasses may override this routine to
2737   /// provide different behavior.
2738   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2739     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2740                                      getSema().CurContext);
2741   }
2742 
2743   /// Build a new C++11 default-initialization expression.
2744   ///
2745   /// By default, builds a new default field initialization expression, which
2746   /// does not require any semantic analysis. Subclasses may override this
2747   /// routine to provide different behavior.
2748   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2749                                        FieldDecl *Field) {
2750     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2751                                       getSema().CurContext);
2752   }
2753 
2754   /// Build a new C++ zero-initialization expression.
2755   ///
2756   /// By default, performs semantic analysis to build the new expression.
2757   /// Subclasses may override this routine to provide different behavior.
2758   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2759                                            SourceLocation LParenLoc,
2760                                            SourceLocation RParenLoc) {
2761     return getSema().BuildCXXTypeConstructExpr(
2762         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2763   }
2764 
2765   /// Build a new C++ "new" expression.
2766   ///
2767   /// By default, performs semantic analysis to build the new expression.
2768   /// Subclasses may override this routine to provide different behavior.
2769   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2770                                bool UseGlobal,
2771                                SourceLocation PlacementLParen,
2772                                MultiExprArg PlacementArgs,
2773                                SourceLocation PlacementRParen,
2774                                SourceRange TypeIdParens,
2775                                QualType AllocatedType,
2776                                TypeSourceInfo *AllocatedTypeInfo,
2777                                Optional<Expr *> ArraySize,
2778                                SourceRange DirectInitRange,
2779                                Expr *Initializer) {
2780     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2781                                  PlacementLParen,
2782                                  PlacementArgs,
2783                                  PlacementRParen,
2784                                  TypeIdParens,
2785                                  AllocatedType,
2786                                  AllocatedTypeInfo,
2787                                  ArraySize,
2788                                  DirectInitRange,
2789                                  Initializer);
2790   }
2791 
2792   /// Build a new C++ "delete" expression.
2793   ///
2794   /// By default, performs semantic analysis to build the new expression.
2795   /// Subclasses may override this routine to provide different behavior.
2796   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2797                                         bool IsGlobalDelete,
2798                                         bool IsArrayForm,
2799                                         Expr *Operand) {
2800     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2801                                     Operand);
2802   }
2803 
2804   /// Build a new type trait expression.
2805   ///
2806   /// By default, performs semantic analysis to build the new expression.
2807   /// Subclasses may override this routine to provide different behavior.
2808   ExprResult RebuildTypeTrait(TypeTrait Trait,
2809                               SourceLocation StartLoc,
2810                               ArrayRef<TypeSourceInfo *> Args,
2811                               SourceLocation RParenLoc) {
2812     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2813   }
2814 
2815   /// Build a new array type trait expression.
2816   ///
2817   /// By default, performs semantic analysis to build the new expression.
2818   /// Subclasses may override this routine to provide different behavior.
2819   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2820                                    SourceLocation StartLoc,
2821                                    TypeSourceInfo *TSInfo,
2822                                    Expr *DimExpr,
2823                                    SourceLocation RParenLoc) {
2824     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2825   }
2826 
2827   /// Build a new expression trait expression.
2828   ///
2829   /// By default, performs semantic analysis to build the new expression.
2830   /// Subclasses may override this routine to provide different behavior.
2831   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2832                                    SourceLocation StartLoc,
2833                                    Expr *Queried,
2834                                    SourceLocation RParenLoc) {
2835     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2836   }
2837 
2838   /// Build a new (previously unresolved) declaration reference
2839   /// expression.
2840   ///
2841   /// By default, performs semantic analysis to build the new expression.
2842   /// Subclasses may override this routine to provide different behavior.
2843   ExprResult RebuildDependentScopeDeclRefExpr(
2844                                           NestedNameSpecifierLoc QualifierLoc,
2845                                           SourceLocation TemplateKWLoc,
2846                                        const DeclarationNameInfo &NameInfo,
2847                               const TemplateArgumentListInfo *TemplateArgs,
2848                                           bool IsAddressOfOperand,
2849                                           TypeSourceInfo **RecoveryTSI) {
2850     CXXScopeSpec SS;
2851     SS.Adopt(QualifierLoc);
2852 
2853     if (TemplateArgs || TemplateKWLoc.isValid())
2854       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2855                                                     TemplateArgs);
2856 
2857     return getSema().BuildQualifiedDeclarationNameExpr(
2858         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2859   }
2860 
2861   /// Build a new template-id expression.
2862   ///
2863   /// By default, performs semantic analysis to build the new expression.
2864   /// Subclasses may override this routine to provide different behavior.
2865   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2866                                    SourceLocation TemplateKWLoc,
2867                                    LookupResult &R,
2868                                    bool RequiresADL,
2869                               const TemplateArgumentListInfo *TemplateArgs) {
2870     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2871                                          TemplateArgs);
2872   }
2873 
2874   /// Build a new object-construction expression.
2875   ///
2876   /// By default, performs semantic analysis to build the new expression.
2877   /// Subclasses may override this routine to provide different behavior.
2878   ExprResult RebuildCXXConstructExpr(QualType T,
2879                                      SourceLocation Loc,
2880                                      CXXConstructorDecl *Constructor,
2881                                      bool IsElidable,
2882                                      MultiExprArg Args,
2883                                      bool HadMultipleCandidates,
2884                                      bool ListInitialization,
2885                                      bool StdInitListInitialization,
2886                                      bool RequiresZeroInit,
2887                              CXXConstructExpr::ConstructionKind ConstructKind,
2888                                      SourceRange ParenRange) {
2889     SmallVector<Expr*, 8> ConvertedArgs;
2890     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2891                                           ConvertedArgs))
2892       return ExprError();
2893 
2894     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2895                                            IsElidable,
2896                                            ConvertedArgs,
2897                                            HadMultipleCandidates,
2898                                            ListInitialization,
2899                                            StdInitListInitialization,
2900                                            RequiresZeroInit, ConstructKind,
2901                                            ParenRange);
2902   }
2903 
2904   /// Build a new implicit construction via inherited constructor
2905   /// expression.
2906   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2907                                              CXXConstructorDecl *Constructor,
2908                                              bool ConstructsVBase,
2909                                              bool InheritedFromVBase) {
2910     return new (getSema().Context) CXXInheritedCtorInitExpr(
2911         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2912   }
2913 
2914   /// Build a new object-construction expression.
2915   ///
2916   /// By default, performs semantic analysis to build the new expression.
2917   /// Subclasses may override this routine to provide different behavior.
2918   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2919                                            SourceLocation LParenOrBraceLoc,
2920                                            MultiExprArg Args,
2921                                            SourceLocation RParenOrBraceLoc,
2922                                            bool ListInitialization) {
2923     return getSema().BuildCXXTypeConstructExpr(
2924         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2925   }
2926 
2927   /// Build a new object-construction expression.
2928   ///
2929   /// By default, performs semantic analysis to build the new expression.
2930   /// Subclasses may override this routine to provide different behavior.
2931   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2932                                                SourceLocation LParenLoc,
2933                                                MultiExprArg Args,
2934                                                SourceLocation RParenLoc,
2935                                                bool ListInitialization) {
2936     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2937                                                RParenLoc, ListInitialization);
2938   }
2939 
2940   /// Build a new member reference expression.
2941   ///
2942   /// By default, performs semantic analysis to build the new expression.
2943   /// Subclasses may override this routine to provide different behavior.
2944   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2945                                                 QualType BaseType,
2946                                                 bool IsArrow,
2947                                                 SourceLocation OperatorLoc,
2948                                           NestedNameSpecifierLoc QualifierLoc,
2949                                                 SourceLocation TemplateKWLoc,
2950                                             NamedDecl *FirstQualifierInScope,
2951                                    const DeclarationNameInfo &MemberNameInfo,
2952                               const TemplateArgumentListInfo *TemplateArgs) {
2953     CXXScopeSpec SS;
2954     SS.Adopt(QualifierLoc);
2955 
2956     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2957                                             OperatorLoc, IsArrow,
2958                                             SS, TemplateKWLoc,
2959                                             FirstQualifierInScope,
2960                                             MemberNameInfo,
2961                                             TemplateArgs, /*S*/nullptr);
2962   }
2963 
2964   /// Build a new member reference expression.
2965   ///
2966   /// By default, performs semantic analysis to build the new expression.
2967   /// Subclasses may override this routine to provide different behavior.
2968   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2969                                          SourceLocation OperatorLoc,
2970                                          bool IsArrow,
2971                                          NestedNameSpecifierLoc QualifierLoc,
2972                                          SourceLocation TemplateKWLoc,
2973                                          NamedDecl *FirstQualifierInScope,
2974                                          LookupResult &R,
2975                                 const TemplateArgumentListInfo *TemplateArgs) {
2976     CXXScopeSpec SS;
2977     SS.Adopt(QualifierLoc);
2978 
2979     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2980                                             OperatorLoc, IsArrow,
2981                                             SS, TemplateKWLoc,
2982                                             FirstQualifierInScope,
2983                                             R, TemplateArgs, /*S*/nullptr);
2984   }
2985 
2986   /// Build a new noexcept expression.
2987   ///
2988   /// By default, performs semantic analysis to build the new expression.
2989   /// Subclasses may override this routine to provide different behavior.
2990   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2991     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2992   }
2993 
2994   /// Build a new expression to compute the length of a parameter pack.
2995   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
2996                                    NamedDecl *Pack,
2997                                    SourceLocation PackLoc,
2998                                    SourceLocation RParenLoc,
2999                                    Optional<unsigned> Length,
3000                                    ArrayRef<TemplateArgument> PartialArgs) {
3001     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3002                                   RParenLoc, Length, PartialArgs);
3003   }
3004 
3005   /// Build a new expression representing a call to a source location
3006   ///  builtin.
3007   ///
3008   /// By default, performs semantic analysis to build the new expression.
3009   /// Subclasses may override this routine to provide different behavior.
3010   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3011                                   SourceLocation BuiltinLoc,
3012                                   SourceLocation RPLoc,
3013                                   DeclContext *ParentContext) {
3014     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3015   }
3016 
3017   /// Build a new Objective-C boxed expression.
3018   ///
3019   /// By default, performs semantic analysis to build the new expression.
3020   /// Subclasses may override this routine to provide different behavior.
3021   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3022     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3023   }
3024 
3025   /// Build a new Objective-C array literal.
3026   ///
3027   /// By default, performs semantic analysis to build the new expression.
3028   /// Subclasses may override this routine to provide different behavior.
3029   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3030                                      Expr **Elements, unsigned NumElements) {
3031     return getSema().BuildObjCArrayLiteral(Range,
3032                                            MultiExprArg(Elements, NumElements));
3033   }
3034 
3035   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3036                                          Expr *Base, Expr *Key,
3037                                          ObjCMethodDecl *getterMethod,
3038                                          ObjCMethodDecl *setterMethod) {
3039     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3040                                                    getterMethod, setterMethod);
3041   }
3042 
3043   /// Build a new Objective-C dictionary literal.
3044   ///
3045   /// By default, performs semantic analysis to build the new expression.
3046   /// Subclasses may override this routine to provide different behavior.
3047   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3048                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3049     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3050   }
3051 
3052   /// Build a new Objective-C \@encode expression.
3053   ///
3054   /// By default, performs semantic analysis to build the new expression.
3055   /// Subclasses may override this routine to provide different behavior.
3056   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3057                                          TypeSourceInfo *EncodeTypeInfo,
3058                                          SourceLocation RParenLoc) {
3059     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3060   }
3061 
3062   /// Build a new Objective-C class message.
3063   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3064                                           Selector Sel,
3065                                           ArrayRef<SourceLocation> SelectorLocs,
3066                                           ObjCMethodDecl *Method,
3067                                           SourceLocation LBracLoc,
3068                                           MultiExprArg Args,
3069                                           SourceLocation RBracLoc) {
3070     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3071                                      ReceiverTypeInfo->getType(),
3072                                      /*SuperLoc=*/SourceLocation(),
3073                                      Sel, Method, LBracLoc, SelectorLocs,
3074                                      RBracLoc, Args);
3075   }
3076 
3077   /// Build a new Objective-C instance message.
3078   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3079                                           Selector Sel,
3080                                           ArrayRef<SourceLocation> SelectorLocs,
3081                                           ObjCMethodDecl *Method,
3082                                           SourceLocation LBracLoc,
3083                                           MultiExprArg Args,
3084                                           SourceLocation RBracLoc) {
3085     return SemaRef.BuildInstanceMessage(Receiver,
3086                                         Receiver->getType(),
3087                                         /*SuperLoc=*/SourceLocation(),
3088                                         Sel, Method, LBracLoc, SelectorLocs,
3089                                         RBracLoc, Args);
3090   }
3091 
3092   /// Build a new Objective-C instance/class message to 'super'.
3093   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3094                                     Selector Sel,
3095                                     ArrayRef<SourceLocation> SelectorLocs,
3096                                     QualType SuperType,
3097                                     ObjCMethodDecl *Method,
3098                                     SourceLocation LBracLoc,
3099                                     MultiExprArg Args,
3100                                     SourceLocation RBracLoc) {
3101     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3102                                           SuperType,
3103                                           SuperLoc,
3104                                           Sel, Method, LBracLoc, SelectorLocs,
3105                                           RBracLoc, Args)
3106                                       : SemaRef.BuildClassMessage(nullptr,
3107                                           SuperType,
3108                                           SuperLoc,
3109                                           Sel, Method, LBracLoc, SelectorLocs,
3110                                           RBracLoc, Args);
3111 
3112 
3113   }
3114 
3115   /// Build a new Objective-C ivar reference expression.
3116   ///
3117   /// By default, performs semantic analysis to build the new expression.
3118   /// Subclasses may override this routine to provide different behavior.
3119   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3120                                           SourceLocation IvarLoc,
3121                                           bool IsArrow, bool IsFreeIvar) {
3122     CXXScopeSpec SS;
3123     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3124     ExprResult Result = getSema().BuildMemberReferenceExpr(
3125         BaseArg, BaseArg->getType(),
3126         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3127         /*FirstQualifierInScope=*/nullptr, NameInfo,
3128         /*TemplateArgs=*/nullptr,
3129         /*S=*/nullptr);
3130     if (IsFreeIvar && Result.isUsable())
3131       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3132     return Result;
3133   }
3134 
3135   /// Build a new Objective-C property reference expression.
3136   ///
3137   /// By default, performs semantic analysis to build the new expression.
3138   /// Subclasses may override this routine to provide different behavior.
3139   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3140                                         ObjCPropertyDecl *Property,
3141                                         SourceLocation PropertyLoc) {
3142     CXXScopeSpec SS;
3143     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3144     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3145                                               /*FIXME:*/PropertyLoc,
3146                                               /*IsArrow=*/false,
3147                                               SS, SourceLocation(),
3148                                               /*FirstQualifierInScope=*/nullptr,
3149                                               NameInfo,
3150                                               /*TemplateArgs=*/nullptr,
3151                                               /*S=*/nullptr);
3152   }
3153 
3154   /// Build a new Objective-C property reference 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 RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3159                                         ObjCMethodDecl *Getter,
3160                                         ObjCMethodDecl *Setter,
3161                                         SourceLocation PropertyLoc) {
3162     // Since these expressions can only be value-dependent, we do not
3163     // need to perform semantic analysis again.
3164     return Owned(
3165       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3166                                                   VK_LValue, OK_ObjCProperty,
3167                                                   PropertyLoc, Base));
3168   }
3169 
3170   /// Build a new Objective-C "isa" expression.
3171   ///
3172   /// By default, performs semantic analysis to build the new expression.
3173   /// Subclasses may override this routine to provide different behavior.
3174   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3175                                 SourceLocation OpLoc, bool IsArrow) {
3176     CXXScopeSpec SS;
3177     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3178     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3179                                               OpLoc, IsArrow,
3180                                               SS, SourceLocation(),
3181                                               /*FirstQualifierInScope=*/nullptr,
3182                                               NameInfo,
3183                                               /*TemplateArgs=*/nullptr,
3184                                               /*S=*/nullptr);
3185   }
3186 
3187   /// Build a new shuffle vector expression.
3188   ///
3189   /// By default, performs semantic analysis to build the new expression.
3190   /// Subclasses may override this routine to provide different behavior.
3191   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3192                                       MultiExprArg SubExprs,
3193                                       SourceLocation RParenLoc) {
3194     // Find the declaration for __builtin_shufflevector
3195     const IdentifierInfo &Name
3196       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3197     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3198     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3199     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3200 
3201     // Build a reference to the __builtin_shufflevector builtin
3202     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3203     Expr *Callee = new (SemaRef.Context)
3204         DeclRefExpr(SemaRef.Context, Builtin, false,
3205                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3206     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3207     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3208                                        CK_BuiltinFnToFnPtr).get();
3209 
3210     // Build the CallExpr
3211     ExprResult TheCall = CallExpr::Create(
3212         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3213         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3214 
3215     // Type-check the __builtin_shufflevector expression.
3216     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3217   }
3218 
3219   /// Build a new convert vector expression.
3220   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3221                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3222                                       SourceLocation RParenLoc) {
3223     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3224                                          BuiltinLoc, RParenLoc);
3225   }
3226 
3227   /// Build a new template argument pack expansion.
3228   ///
3229   /// By default, performs semantic analysis to build a new pack expansion
3230   /// for a template argument. Subclasses may override this routine to provide
3231   /// different behavior.
3232   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3233                                            SourceLocation EllipsisLoc,
3234                                            Optional<unsigned> NumExpansions) {
3235     switch (Pattern.getArgument().getKind()) {
3236     case TemplateArgument::Expression: {
3237       ExprResult Result
3238         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3239                                        EllipsisLoc, NumExpansions);
3240       if (Result.isInvalid())
3241         return TemplateArgumentLoc();
3242 
3243       return TemplateArgumentLoc(Result.get(), Result.get());
3244     }
3245 
3246     case TemplateArgument::Template:
3247       return TemplateArgumentLoc(TemplateArgument(
3248                                           Pattern.getArgument().getAsTemplate(),
3249                                                   NumExpansions),
3250                                  Pattern.getTemplateQualifierLoc(),
3251                                  Pattern.getTemplateNameLoc(),
3252                                  EllipsisLoc);
3253 
3254     case TemplateArgument::Null:
3255     case TemplateArgument::Integral:
3256     case TemplateArgument::Declaration:
3257     case TemplateArgument::Pack:
3258     case TemplateArgument::TemplateExpansion:
3259     case TemplateArgument::NullPtr:
3260       llvm_unreachable("Pack expansion pattern has no parameter packs");
3261 
3262     case TemplateArgument::Type:
3263       if (TypeSourceInfo *Expansion
3264             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3265                                            EllipsisLoc,
3266                                            NumExpansions))
3267         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3268                                    Expansion);
3269       break;
3270     }
3271 
3272     return TemplateArgumentLoc();
3273   }
3274 
3275   /// Build a new expression pack expansion.
3276   ///
3277   /// By default, performs semantic analysis to build a new pack expansion
3278   /// for an expression. Subclasses may override this routine to provide
3279   /// different behavior.
3280   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3281                                   Optional<unsigned> NumExpansions) {
3282     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3283   }
3284 
3285   /// Build a new C++1z fold-expression.
3286   ///
3287   /// By default, performs semantic analysis in order to build a new fold
3288   /// expression.
3289   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3290                                 BinaryOperatorKind Operator,
3291                                 SourceLocation EllipsisLoc, Expr *RHS,
3292                                 SourceLocation RParenLoc,
3293                                 Optional<unsigned> NumExpansions) {
3294     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3295                                       RHS, RParenLoc, NumExpansions);
3296   }
3297 
3298   /// Build an empty C++1z fold-expression with the given operator.
3299   ///
3300   /// By default, produces the fallback value for the fold-expression, or
3301   /// produce an error if there is no fallback value.
3302   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3303                                      BinaryOperatorKind Operator) {
3304     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3305   }
3306 
3307   /// Build a new atomic operation expression.
3308   ///
3309   /// By default, performs semantic analysis to build the new expression.
3310   /// Subclasses may override this routine to provide different behavior.
3311   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3312                                AtomicExpr::AtomicOp Op,
3313                                SourceLocation RParenLoc) {
3314     // Use this for all of the locations, since we don't know the difference
3315     // between the call and the expr at this point.
3316     SourceRange Range{BuiltinLoc, RParenLoc};
3317     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3318                                      Sema::AtomicArgumentOrder::AST);
3319   }
3320 
3321 private:
3322   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3323                                      QualType ObjectType,
3324                                      NamedDecl *FirstQualifierInScope,
3325                                      CXXScopeSpec &SS);
3326 
3327   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3328                                              QualType ObjectType,
3329                                              NamedDecl *FirstQualifierInScope,
3330                                              CXXScopeSpec &SS);
3331 
3332   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3333                                             NamedDecl *FirstQualifierInScope,
3334                                             CXXScopeSpec &SS);
3335 
3336   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3337                                       DependentNameTypeLoc TL,
3338                                       bool DeducibleTSTContext);
3339 };
3340 
3341 template <typename Derived>
3342 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3343   if (!S)
3344     return S;
3345 
3346   switch (S->getStmtClass()) {
3347   case Stmt::NoStmtClass: break;
3348 
3349   // Transform individual statement nodes
3350   // Pass SDK into statements that can produce a value
3351 #define STMT(Node, Parent)                                              \
3352   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3353 #define VALUESTMT(Node, Parent)                                         \
3354   case Stmt::Node##Class:                                               \
3355     return getDerived().Transform##Node(cast<Node>(S), SDK);
3356 #define ABSTRACT_STMT(Node)
3357 #define EXPR(Node, Parent)
3358 #include "clang/AST/StmtNodes.inc"
3359 
3360   // Transform expressions by calling TransformExpr.
3361 #define STMT(Node, Parent)
3362 #define ABSTRACT_STMT(Stmt)
3363 #define EXPR(Node, Parent) case Stmt::Node##Class:
3364 #include "clang/AST/StmtNodes.inc"
3365     {
3366       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3367 
3368       if (SDK == SDK_StmtExprResult)
3369         E = getSema().ActOnStmtExprResult(E);
3370       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3371     }
3372   }
3373 
3374   return S;
3375 }
3376 
3377 template<typename Derived>
3378 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3379   if (!S)
3380     return S;
3381 
3382   switch (S->getClauseKind()) {
3383   default: break;
3384   // Transform individual clause nodes
3385 #define OPENMP_CLAUSE(Name, Class)                                             \
3386   case OMPC_ ## Name :                                                         \
3387     return getDerived().Transform ## Class(cast<Class>(S));
3388 #include "clang/Basic/OpenMPKinds.def"
3389   }
3390 
3391   return S;
3392 }
3393 
3394 
3395 template<typename Derived>
3396 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3397   if (!E)
3398     return E;
3399 
3400   switch (E->getStmtClass()) {
3401     case Stmt::NoStmtClass: break;
3402 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3403 #define ABSTRACT_STMT(Stmt)
3404 #define EXPR(Node, Parent)                                              \
3405     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3406 #include "clang/AST/StmtNodes.inc"
3407   }
3408 
3409   return E;
3410 }
3411 
3412 template<typename Derived>
3413 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3414                                                         bool NotCopyInit) {
3415   // Initializers are instantiated like expressions, except that various outer
3416   // layers are stripped.
3417   if (!Init)
3418     return Init;
3419 
3420   if (auto *FE = dyn_cast<FullExpr>(Init))
3421     Init = FE->getSubExpr();
3422 
3423   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3424     Init = AIL->getCommonExpr();
3425 
3426   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3427     Init = MTE->GetTemporaryExpr();
3428 
3429   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3430     Init = Binder->getSubExpr();
3431 
3432   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3433     Init = ICE->getSubExprAsWritten();
3434 
3435   if (CXXStdInitializerListExpr *ILE =
3436           dyn_cast<CXXStdInitializerListExpr>(Init))
3437     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3438 
3439   // If this is copy-initialization, we only need to reconstruct
3440   // InitListExprs. Other forms of copy-initialization will be a no-op if
3441   // the initializer is already the right type.
3442   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3443   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3444     return getDerived().TransformExpr(Init);
3445 
3446   // Revert value-initialization back to empty parens.
3447   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3448     SourceRange Parens = VIE->getSourceRange();
3449     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3450                                              Parens.getEnd());
3451   }
3452 
3453   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3454   if (isa<ImplicitValueInitExpr>(Init))
3455     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3456                                              SourceLocation());
3457 
3458   // Revert initialization by constructor back to a parenthesized or braced list
3459   // of expressions. Any other form of initializer can just be reused directly.
3460   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3461     return getDerived().TransformExpr(Init);
3462 
3463   // If the initialization implicitly converted an initializer list to a
3464   // std::initializer_list object, unwrap the std::initializer_list too.
3465   if (Construct && Construct->isStdInitListInitialization())
3466     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3467 
3468   // Enter a list-init context if this was list initialization.
3469   EnterExpressionEvaluationContext Context(
3470       getSema(), EnterExpressionEvaluationContext::InitList,
3471       Construct->isListInitialization());
3472 
3473   SmallVector<Expr*, 8> NewArgs;
3474   bool ArgChanged = false;
3475   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3476                                   /*IsCall*/true, NewArgs, &ArgChanged))
3477     return ExprError();
3478 
3479   // If this was list initialization, revert to syntactic list form.
3480   if (Construct->isListInitialization())
3481     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3482                                         Construct->getEndLoc());
3483 
3484   // Build a ParenListExpr to represent anything else.
3485   SourceRange Parens = Construct->getParenOrBraceRange();
3486   if (Parens.isInvalid()) {
3487     // This was a variable declaration's initialization for which no initializer
3488     // was specified.
3489     assert(NewArgs.empty() &&
3490            "no parens or braces but have direct init with arguments?");
3491     return ExprEmpty();
3492   }
3493   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3494                                            Parens.getEnd());
3495 }
3496 
3497 template<typename Derived>
3498 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3499                                             unsigned NumInputs,
3500                                             bool IsCall,
3501                                       SmallVectorImpl<Expr *> &Outputs,
3502                                             bool *ArgChanged) {
3503   for (unsigned I = 0; I != NumInputs; ++I) {
3504     // If requested, drop call arguments that need to be dropped.
3505     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3506       if (ArgChanged)
3507         *ArgChanged = true;
3508 
3509       break;
3510     }
3511 
3512     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3513       Expr *Pattern = Expansion->getPattern();
3514 
3515       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3516       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3517       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3518 
3519       // Determine whether the set of unexpanded parameter packs can and should
3520       // be expanded.
3521       bool Expand = true;
3522       bool RetainExpansion = false;
3523       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3524       Optional<unsigned> NumExpansions = OrigNumExpansions;
3525       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3526                                                Pattern->getSourceRange(),
3527                                                Unexpanded,
3528                                                Expand, RetainExpansion,
3529                                                NumExpansions))
3530         return true;
3531 
3532       if (!Expand) {
3533         // The transform has determined that we should perform a simple
3534         // transformation on the pack expansion, producing another pack
3535         // expansion.
3536         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3537         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3538         if (OutPattern.isInvalid())
3539           return true;
3540 
3541         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3542                                                 Expansion->getEllipsisLoc(),
3543                                                            NumExpansions);
3544         if (Out.isInvalid())
3545           return true;
3546 
3547         if (ArgChanged)
3548           *ArgChanged = true;
3549         Outputs.push_back(Out.get());
3550         continue;
3551       }
3552 
3553       // Record right away that the argument was changed.  This needs
3554       // to happen even if the array expands to nothing.
3555       if (ArgChanged) *ArgChanged = true;
3556 
3557       // The transform has determined that we should perform an elementwise
3558       // expansion of the pattern. Do so.
3559       for (unsigned I = 0; I != *NumExpansions; ++I) {
3560         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3561         ExprResult Out = getDerived().TransformExpr(Pattern);
3562         if (Out.isInvalid())
3563           return true;
3564 
3565         if (Out.get()->containsUnexpandedParameterPack()) {
3566           Out = getDerived().RebuildPackExpansion(
3567               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3568           if (Out.isInvalid())
3569             return true;
3570         }
3571 
3572         Outputs.push_back(Out.get());
3573       }
3574 
3575       // If we're supposed to retain a pack expansion, do so by temporarily
3576       // forgetting the partially-substituted parameter pack.
3577       if (RetainExpansion) {
3578         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3579 
3580         ExprResult Out = getDerived().TransformExpr(Pattern);
3581         if (Out.isInvalid())
3582           return true;
3583 
3584         Out = getDerived().RebuildPackExpansion(
3585             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3586         if (Out.isInvalid())
3587           return true;
3588 
3589         Outputs.push_back(Out.get());
3590       }
3591 
3592       continue;
3593     }
3594 
3595     ExprResult Result =
3596       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3597              : getDerived().TransformExpr(Inputs[I]);
3598     if (Result.isInvalid())
3599       return true;
3600 
3601     if (Result.get() != Inputs[I] && ArgChanged)
3602       *ArgChanged = true;
3603 
3604     Outputs.push_back(Result.get());
3605   }
3606 
3607   return false;
3608 }
3609 
3610 template <typename Derived>
3611 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3612     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3613   if (Var) {
3614     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3615         getDerived().TransformDefinition(Var->getLocation(), Var));
3616 
3617     if (!ConditionVar)
3618       return Sema::ConditionError();
3619 
3620     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3621   }
3622 
3623   if (Expr) {
3624     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3625 
3626     if (CondExpr.isInvalid())
3627       return Sema::ConditionError();
3628 
3629     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3630   }
3631 
3632   return Sema::ConditionResult();
3633 }
3634 
3635 template<typename Derived>
3636 NestedNameSpecifierLoc
3637 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3638                                                     NestedNameSpecifierLoc NNS,
3639                                                      QualType ObjectType,
3640                                              NamedDecl *FirstQualifierInScope) {
3641   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3642   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3643        Qualifier = Qualifier.getPrefix())
3644     Qualifiers.push_back(Qualifier);
3645 
3646   CXXScopeSpec SS;
3647   while (!Qualifiers.empty()) {
3648     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3649     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3650 
3651     switch (QNNS->getKind()) {
3652     case NestedNameSpecifier::Identifier: {
3653       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3654                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3655       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3656                                               SS, FirstQualifierInScope, false))
3657         return NestedNameSpecifierLoc();
3658     }
3659       break;
3660 
3661     case NestedNameSpecifier::Namespace: {
3662       NamespaceDecl *NS
3663         = cast_or_null<NamespaceDecl>(
3664                                     getDerived().TransformDecl(
3665                                                           Q.getLocalBeginLoc(),
3666                                                        QNNS->getAsNamespace()));
3667       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3668       break;
3669     }
3670 
3671     case NestedNameSpecifier::NamespaceAlias: {
3672       NamespaceAliasDecl *Alias
3673         = cast_or_null<NamespaceAliasDecl>(
3674                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3675                                                  QNNS->getAsNamespaceAlias()));
3676       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3677                 Q.getLocalEndLoc());
3678       break;
3679     }
3680 
3681     case NestedNameSpecifier::Global:
3682       // There is no meaningful transformation that one could perform on the
3683       // global scope.
3684       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3685       break;
3686 
3687     case NestedNameSpecifier::Super: {
3688       CXXRecordDecl *RD =
3689           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3690               SourceLocation(), QNNS->getAsRecordDecl()));
3691       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3692       break;
3693     }
3694 
3695     case NestedNameSpecifier::TypeSpecWithTemplate:
3696     case NestedNameSpecifier::TypeSpec: {
3697       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3698                                               FirstQualifierInScope, SS);
3699 
3700       if (!TL)
3701         return NestedNameSpecifierLoc();
3702 
3703       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3704           (SemaRef.getLangOpts().CPlusPlus11 &&
3705            TL.getType()->isEnumeralType())) {
3706         assert(!TL.getType().hasLocalQualifiers() &&
3707                "Can't get cv-qualifiers here");
3708         if (TL.getType()->isEnumeralType())
3709           SemaRef.Diag(TL.getBeginLoc(),
3710                        diag::warn_cxx98_compat_enum_nested_name_spec);
3711         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3712                   Q.getLocalEndLoc());
3713         break;
3714       }
3715       // If the nested-name-specifier is an invalid type def, don't emit an
3716       // error because a previous error should have already been emitted.
3717       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3718       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3719         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3720           << TL.getType() << SS.getRange();
3721       }
3722       return NestedNameSpecifierLoc();
3723     }
3724     }
3725 
3726     // The qualifier-in-scope and object type only apply to the leftmost entity.
3727     FirstQualifierInScope = nullptr;
3728     ObjectType = QualType();
3729   }
3730 
3731   // Don't rebuild the nested-name-specifier if we don't have to.
3732   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3733       !getDerived().AlwaysRebuild())
3734     return NNS;
3735 
3736   // If we can re-use the source-location data from the original
3737   // nested-name-specifier, do so.
3738   if (SS.location_size() == NNS.getDataLength() &&
3739       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3740     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3741 
3742   // Allocate new nested-name-specifier location information.
3743   return SS.getWithLocInContext(SemaRef.Context);
3744 }
3745 
3746 template<typename Derived>
3747 DeclarationNameInfo
3748 TreeTransform<Derived>
3749 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3750   DeclarationName Name = NameInfo.getName();
3751   if (!Name)
3752     return DeclarationNameInfo();
3753 
3754   switch (Name.getNameKind()) {
3755   case DeclarationName::Identifier:
3756   case DeclarationName::ObjCZeroArgSelector:
3757   case DeclarationName::ObjCOneArgSelector:
3758   case DeclarationName::ObjCMultiArgSelector:
3759   case DeclarationName::CXXOperatorName:
3760   case DeclarationName::CXXLiteralOperatorName:
3761   case DeclarationName::CXXUsingDirective:
3762     return NameInfo;
3763 
3764   case DeclarationName::CXXDeductionGuideName: {
3765     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3766     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3767         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3768     if (!NewTemplate)
3769       return DeclarationNameInfo();
3770 
3771     DeclarationNameInfo NewNameInfo(NameInfo);
3772     NewNameInfo.setName(
3773         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3774     return NewNameInfo;
3775   }
3776 
3777   case DeclarationName::CXXConstructorName:
3778   case DeclarationName::CXXDestructorName:
3779   case DeclarationName::CXXConversionFunctionName: {
3780     TypeSourceInfo *NewTInfo;
3781     CanQualType NewCanTy;
3782     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3783       NewTInfo = getDerived().TransformType(OldTInfo);
3784       if (!NewTInfo)
3785         return DeclarationNameInfo();
3786       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3787     }
3788     else {
3789       NewTInfo = nullptr;
3790       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3791       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3792       if (NewT.isNull())
3793         return DeclarationNameInfo();
3794       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3795     }
3796 
3797     DeclarationName NewName
3798       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3799                                                            NewCanTy);
3800     DeclarationNameInfo NewNameInfo(NameInfo);
3801     NewNameInfo.setName(NewName);
3802     NewNameInfo.setNamedTypeInfo(NewTInfo);
3803     return NewNameInfo;
3804   }
3805   }
3806 
3807   llvm_unreachable("Unknown name kind.");
3808 }
3809 
3810 template<typename Derived>
3811 TemplateName
3812 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3813                                               TemplateName Name,
3814                                               SourceLocation NameLoc,
3815                                               QualType ObjectType,
3816                                               NamedDecl *FirstQualifierInScope,
3817                                               bool AllowInjectedClassName) {
3818   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3819     TemplateDecl *Template = QTN->getTemplateDecl();
3820     assert(Template && "qualified template name must refer to a template");
3821 
3822     TemplateDecl *TransTemplate
3823       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3824                                                               Template));
3825     if (!TransTemplate)
3826       return TemplateName();
3827 
3828     if (!getDerived().AlwaysRebuild() &&
3829         SS.getScopeRep() == QTN->getQualifier() &&
3830         TransTemplate == Template)
3831       return Name;
3832 
3833     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3834                                             TransTemplate);
3835   }
3836 
3837   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3838     if (SS.getScopeRep()) {
3839       // These apply to the scope specifier, not the template.
3840       ObjectType = QualType();
3841       FirstQualifierInScope = nullptr;
3842     }
3843 
3844     if (!getDerived().AlwaysRebuild() &&
3845         SS.getScopeRep() == DTN->getQualifier() &&
3846         ObjectType.isNull())
3847       return Name;
3848 
3849     // FIXME: Preserve the location of the "template" keyword.
3850     SourceLocation TemplateKWLoc = NameLoc;
3851 
3852     if (DTN->isIdentifier()) {
3853       return getDerived().RebuildTemplateName(SS,
3854                                               TemplateKWLoc,
3855                                               *DTN->getIdentifier(),
3856                                               NameLoc,
3857                                               ObjectType,
3858                                               FirstQualifierInScope,
3859                                               AllowInjectedClassName);
3860     }
3861 
3862     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3863                                             DTN->getOperator(), NameLoc,
3864                                             ObjectType, AllowInjectedClassName);
3865   }
3866 
3867   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3868     TemplateDecl *TransTemplate
3869       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3870                                                               Template));
3871     if (!TransTemplate)
3872       return TemplateName();
3873 
3874     if (!getDerived().AlwaysRebuild() &&
3875         TransTemplate == Template)
3876       return Name;
3877 
3878     return TemplateName(TransTemplate);
3879   }
3880 
3881   if (SubstTemplateTemplateParmPackStorage *SubstPack
3882       = Name.getAsSubstTemplateTemplateParmPack()) {
3883     TemplateTemplateParmDecl *TransParam
3884     = cast_or_null<TemplateTemplateParmDecl>(
3885             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3886     if (!TransParam)
3887       return TemplateName();
3888 
3889     if (!getDerived().AlwaysRebuild() &&
3890         TransParam == SubstPack->getParameterPack())
3891       return Name;
3892 
3893     return getDerived().RebuildTemplateName(TransParam,
3894                                             SubstPack->getArgumentPack());
3895   }
3896 
3897   // These should be getting filtered out before they reach the AST.
3898   llvm_unreachable("overloaded function decl survived to here");
3899 }
3900 
3901 template<typename Derived>
3902 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3903                                          const TemplateArgument &Arg,
3904                                          TemplateArgumentLoc &Output) {
3905   SourceLocation Loc = getDerived().getBaseLocation();
3906   switch (Arg.getKind()) {
3907   case TemplateArgument::Null:
3908     llvm_unreachable("null template argument in TreeTransform");
3909     break;
3910 
3911   case TemplateArgument::Type:
3912     Output = TemplateArgumentLoc(Arg,
3913                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3914 
3915     break;
3916 
3917   case TemplateArgument::Template:
3918   case TemplateArgument::TemplateExpansion: {
3919     NestedNameSpecifierLocBuilder Builder;
3920     TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3921     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3922       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3923     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3924       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3925 
3926     if (Arg.getKind() == TemplateArgument::Template)
3927       Output = TemplateArgumentLoc(Arg,
3928                                    Builder.getWithLocInContext(SemaRef.Context),
3929                                    Loc);
3930     else
3931       Output = TemplateArgumentLoc(Arg,
3932                                    Builder.getWithLocInContext(SemaRef.Context),
3933                                    Loc, Loc);
3934 
3935     break;
3936   }
3937 
3938   case TemplateArgument::Expression:
3939     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3940     break;
3941 
3942   case TemplateArgument::Declaration:
3943   case TemplateArgument::Integral:
3944   case TemplateArgument::Pack:
3945   case TemplateArgument::NullPtr:
3946     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3947     break;
3948   }
3949 }
3950 
3951 template<typename Derived>
3952 bool TreeTransform<Derived>::TransformTemplateArgument(
3953                                          const TemplateArgumentLoc &Input,
3954                                          TemplateArgumentLoc &Output, bool Uneval) {
3955   const TemplateArgument &Arg = Input.getArgument();
3956   switch (Arg.getKind()) {
3957   case TemplateArgument::Null:
3958   case TemplateArgument::Integral:
3959   case TemplateArgument::Pack:
3960   case TemplateArgument::Declaration:
3961   case TemplateArgument::NullPtr:
3962     llvm_unreachable("Unexpected TemplateArgument");
3963 
3964   case TemplateArgument::Type: {
3965     TypeSourceInfo *DI = Input.getTypeSourceInfo();
3966     if (!DI)
3967       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3968 
3969     DI = getDerived().TransformType(DI);
3970     if (!DI) return true;
3971 
3972     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3973     return false;
3974   }
3975 
3976   case TemplateArgument::Template: {
3977     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3978     if (QualifierLoc) {
3979       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3980       if (!QualifierLoc)
3981         return true;
3982     }
3983 
3984     CXXScopeSpec SS;
3985     SS.Adopt(QualifierLoc);
3986     TemplateName Template
3987       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3988                                            Input.getTemplateNameLoc());
3989     if (Template.isNull())
3990       return true;
3991 
3992     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3993                                  Input.getTemplateNameLoc());
3994     return false;
3995   }
3996 
3997   case TemplateArgument::TemplateExpansion:
3998     llvm_unreachable("Caller should expand pack expansions");
3999 
4000   case TemplateArgument::Expression: {
4001     // Template argument expressions are constant expressions.
4002     EnterExpressionEvaluationContext Unevaluated(
4003         getSema(),
4004         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4005                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4006         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4007         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4008 
4009     Expr *InputExpr = Input.getSourceExpression();
4010     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4011 
4012     ExprResult E = getDerived().TransformExpr(InputExpr);
4013     E = SemaRef.ActOnConstantExpression(E);
4014     if (E.isInvalid()) return true;
4015     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4016     return false;
4017   }
4018   }
4019 
4020   // Work around bogus GCC warning
4021   return true;
4022 }
4023 
4024 /// Iterator adaptor that invents template argument location information
4025 /// for each of the template arguments in its underlying iterator.
4026 template<typename Derived, typename InputIterator>
4027 class TemplateArgumentLocInventIterator {
4028   TreeTransform<Derived> &Self;
4029   InputIterator Iter;
4030 
4031 public:
4032   typedef TemplateArgumentLoc value_type;
4033   typedef TemplateArgumentLoc reference;
4034   typedef typename std::iterator_traits<InputIterator>::difference_type
4035     difference_type;
4036   typedef std::input_iterator_tag iterator_category;
4037 
4038   class pointer {
4039     TemplateArgumentLoc Arg;
4040 
4041   public:
4042     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4043 
4044     const TemplateArgumentLoc *operator->() const { return &Arg; }
4045   };
4046 
4047   TemplateArgumentLocInventIterator() { }
4048 
4049   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4050                                              InputIterator Iter)
4051     : Self(Self), Iter(Iter) { }
4052 
4053   TemplateArgumentLocInventIterator &operator++() {
4054     ++Iter;
4055     return *this;
4056   }
4057 
4058   TemplateArgumentLocInventIterator operator++(int) {
4059     TemplateArgumentLocInventIterator Old(*this);
4060     ++(*this);
4061     return Old;
4062   }
4063 
4064   reference operator*() const {
4065     TemplateArgumentLoc Result;
4066     Self.InventTemplateArgumentLoc(*Iter, Result);
4067     return Result;
4068   }
4069 
4070   pointer operator->() const { return pointer(**this); }
4071 
4072   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4073                          const TemplateArgumentLocInventIterator &Y) {
4074     return X.Iter == Y.Iter;
4075   }
4076 
4077   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4078                          const TemplateArgumentLocInventIterator &Y) {
4079     return X.Iter != Y.Iter;
4080   }
4081 };
4082 
4083 template<typename Derived>
4084 template<typename InputIterator>
4085 bool TreeTransform<Derived>::TransformTemplateArguments(
4086     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4087     bool Uneval) {
4088   for (; First != Last; ++First) {
4089     TemplateArgumentLoc Out;
4090     TemplateArgumentLoc In = *First;
4091 
4092     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4093       // Unpack argument packs, which we translate them into separate
4094       // arguments.
4095       // FIXME: We could do much better if we could guarantee that the
4096       // TemplateArgumentLocInfo for the pack expansion would be usable for
4097       // all of the template arguments in the argument pack.
4098       typedef TemplateArgumentLocInventIterator<Derived,
4099                                                 TemplateArgument::pack_iterator>
4100         PackLocIterator;
4101       if (TransformTemplateArguments(PackLocIterator(*this,
4102                                                  In.getArgument().pack_begin()),
4103                                      PackLocIterator(*this,
4104                                                    In.getArgument().pack_end()),
4105                                      Outputs, Uneval))
4106         return true;
4107 
4108       continue;
4109     }
4110 
4111     if (In.getArgument().isPackExpansion()) {
4112       // We have a pack expansion, for which we will be substituting into
4113       // the pattern.
4114       SourceLocation Ellipsis;
4115       Optional<unsigned> OrigNumExpansions;
4116       TemplateArgumentLoc Pattern
4117         = getSema().getTemplateArgumentPackExpansionPattern(
4118               In, Ellipsis, OrigNumExpansions);
4119 
4120       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4121       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4122       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4123 
4124       // Determine whether the set of unexpanded parameter packs can and should
4125       // be expanded.
4126       bool Expand = true;
4127       bool RetainExpansion = false;
4128       Optional<unsigned> NumExpansions = OrigNumExpansions;
4129       if (getDerived().TryExpandParameterPacks(Ellipsis,
4130                                                Pattern.getSourceRange(),
4131                                                Unexpanded,
4132                                                Expand,
4133                                                RetainExpansion,
4134                                                NumExpansions))
4135         return true;
4136 
4137       if (!Expand) {
4138         // The transform has determined that we should perform a simple
4139         // transformation on the pack expansion, producing another pack
4140         // expansion.
4141         TemplateArgumentLoc OutPattern;
4142         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4143         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4144           return true;
4145 
4146         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4147                                                 NumExpansions);
4148         if (Out.getArgument().isNull())
4149           return true;
4150 
4151         Outputs.addArgument(Out);
4152         continue;
4153       }
4154 
4155       // The transform has determined that we should perform an elementwise
4156       // expansion of the pattern. Do so.
4157       for (unsigned I = 0; I != *NumExpansions; ++I) {
4158         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4159 
4160         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4161           return true;
4162 
4163         if (Out.getArgument().containsUnexpandedParameterPack()) {
4164           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4165                                                   OrigNumExpansions);
4166           if (Out.getArgument().isNull())
4167             return true;
4168         }
4169 
4170         Outputs.addArgument(Out);
4171       }
4172 
4173       // If we're supposed to retain a pack expansion, do so by temporarily
4174       // forgetting the partially-substituted parameter pack.
4175       if (RetainExpansion) {
4176         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4177 
4178         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4179           return true;
4180 
4181         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4182                                                 OrigNumExpansions);
4183         if (Out.getArgument().isNull())
4184           return true;
4185 
4186         Outputs.addArgument(Out);
4187       }
4188 
4189       continue;
4190     }
4191 
4192     // The simple case:
4193     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4194       return true;
4195 
4196     Outputs.addArgument(Out);
4197   }
4198 
4199   return false;
4200 
4201 }
4202 
4203 //===----------------------------------------------------------------------===//
4204 // Type transformation
4205 //===----------------------------------------------------------------------===//
4206 
4207 template<typename Derived>
4208 QualType TreeTransform<Derived>::TransformType(QualType T) {
4209   if (getDerived().AlreadyTransformed(T))
4210     return T;
4211 
4212   // Temporary workaround.  All of these transformations should
4213   // eventually turn into transformations on TypeLocs.
4214   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4215                                                 getDerived().getBaseLocation());
4216 
4217   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4218 
4219   if (!NewDI)
4220     return QualType();
4221 
4222   return NewDI->getType();
4223 }
4224 
4225 template<typename Derived>
4226 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4227   // Refine the base location to the type's location.
4228   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4229                        getDerived().getBaseEntity());
4230   if (getDerived().AlreadyTransformed(DI->getType()))
4231     return DI;
4232 
4233   TypeLocBuilder TLB;
4234 
4235   TypeLoc TL = DI->getTypeLoc();
4236   TLB.reserve(TL.getFullDataSize());
4237 
4238   QualType Result = getDerived().TransformType(TLB, TL);
4239   if (Result.isNull())
4240     return nullptr;
4241 
4242   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4243 }
4244 
4245 template<typename Derived>
4246 QualType
4247 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4248   switch (T.getTypeLocClass()) {
4249 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4250 #define TYPELOC(CLASS, PARENT)                                                 \
4251   case TypeLoc::CLASS:                                                         \
4252     return getDerived().Transform##CLASS##Type(TLB,                            \
4253                                                T.castAs<CLASS##TypeLoc>());
4254 #include "clang/AST/TypeLocNodes.def"
4255   }
4256 
4257   llvm_unreachable("unhandled type loc!");
4258 }
4259 
4260 template<typename Derived>
4261 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4262   if (!isa<DependentNameType>(T))
4263     return TransformType(T);
4264 
4265   if (getDerived().AlreadyTransformed(T))
4266     return T;
4267   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4268                                                 getDerived().getBaseLocation());
4269   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4270   return NewDI ? NewDI->getType() : QualType();
4271 }
4272 
4273 template<typename Derived>
4274 TypeSourceInfo *
4275 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4276   if (!isa<DependentNameType>(DI->getType()))
4277     return TransformType(DI);
4278 
4279   // Refine the base location to the type's location.
4280   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4281                        getDerived().getBaseEntity());
4282   if (getDerived().AlreadyTransformed(DI->getType()))
4283     return DI;
4284 
4285   TypeLocBuilder TLB;
4286 
4287   TypeLoc TL = DI->getTypeLoc();
4288   TLB.reserve(TL.getFullDataSize());
4289 
4290   auto QTL = TL.getAs<QualifiedTypeLoc>();
4291   if (QTL)
4292     TL = QTL.getUnqualifiedLoc();
4293 
4294   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4295 
4296   QualType Result = getDerived().TransformDependentNameType(
4297       TLB, DNTL, /*DeducedTSTContext*/true);
4298   if (Result.isNull())
4299     return nullptr;
4300 
4301   if (QTL) {
4302     Result = getDerived().RebuildQualifiedType(Result, QTL);
4303     if (Result.isNull())
4304       return nullptr;
4305     TLB.TypeWasModifiedSafely(Result);
4306   }
4307 
4308   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4309 }
4310 
4311 template<typename Derived>
4312 QualType
4313 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4314                                                QualifiedTypeLoc T) {
4315   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4316   if (Result.isNull())
4317     return QualType();
4318 
4319   Result = getDerived().RebuildQualifiedType(Result, T);
4320 
4321   if (Result.isNull())
4322     return QualType();
4323 
4324   // RebuildQualifiedType might have updated the type, but not in a way
4325   // that invalidates the TypeLoc. (There's no location information for
4326   // qualifiers.)
4327   TLB.TypeWasModifiedSafely(Result);
4328 
4329   return Result;
4330 }
4331 
4332 template <typename Derived>
4333 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4334                                                       QualifiedTypeLoc TL) {
4335 
4336   SourceLocation Loc = TL.getBeginLoc();
4337   Qualifiers Quals = TL.getType().getLocalQualifiers();
4338 
4339   if (((T.getAddressSpace() != LangAS::Default &&
4340         Quals.getAddressSpace() != LangAS::Default)) &&
4341       T.getAddressSpace() != Quals.getAddressSpace()) {
4342     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4343         << TL.getType() << T;
4344     return QualType();
4345   }
4346 
4347   // C++ [dcl.fct]p7:
4348   //   [When] adding cv-qualifications on top of the function type [...] the
4349   //   cv-qualifiers are ignored.
4350   if (T->isFunctionType()) {
4351     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4352                                                      Quals.getAddressSpace());
4353     return T;
4354   }
4355 
4356   // C++ [dcl.ref]p1:
4357   //   when the cv-qualifiers are introduced through the use of a typedef-name
4358   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4359   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4360   // applied to a reference type.
4361   if (T->isReferenceType()) {
4362     // The only qualifier that applies to a reference type is restrict.
4363     if (!Quals.hasRestrict())
4364       return T;
4365     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4366   }
4367 
4368   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4369   // resulting type.
4370   if (Quals.hasObjCLifetime()) {
4371     if (!T->isObjCLifetimeType() && !T->isDependentType())
4372       Quals.removeObjCLifetime();
4373     else if (T.getObjCLifetime()) {
4374       // Objective-C ARC:
4375       //   A lifetime qualifier applied to a substituted template parameter
4376       //   overrides the lifetime qualifier from the template argument.
4377       const AutoType *AutoTy;
4378       if (const SubstTemplateTypeParmType *SubstTypeParam
4379                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4380         QualType Replacement = SubstTypeParam->getReplacementType();
4381         Qualifiers Qs = Replacement.getQualifiers();
4382         Qs.removeObjCLifetime();
4383         Replacement = SemaRef.Context.getQualifiedType(
4384             Replacement.getUnqualifiedType(), Qs);
4385         T = SemaRef.Context.getSubstTemplateTypeParmType(
4386             SubstTypeParam->getReplacedParameter(), Replacement);
4387       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4388         // 'auto' types behave the same way as template parameters.
4389         QualType Deduced = AutoTy->getDeducedType();
4390         Qualifiers Qs = Deduced.getQualifiers();
4391         Qs.removeObjCLifetime();
4392         Deduced =
4393             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4394         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4395                                         AutoTy->isDependentType());
4396       } else {
4397         // Otherwise, complain about the addition of a qualifier to an
4398         // already-qualified type.
4399         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4400         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4401         Quals.removeObjCLifetime();
4402       }
4403     }
4404   }
4405 
4406   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4407 }
4408 
4409 template<typename Derived>
4410 TypeLoc
4411 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4412                                                    QualType ObjectType,
4413                                                    NamedDecl *UnqualLookup,
4414                                                    CXXScopeSpec &SS) {
4415   if (getDerived().AlreadyTransformed(TL.getType()))
4416     return TL;
4417 
4418   TypeSourceInfo *TSI =
4419       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4420   if (TSI)
4421     return TSI->getTypeLoc();
4422   return TypeLoc();
4423 }
4424 
4425 template<typename Derived>
4426 TypeSourceInfo *
4427 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4428                                                    QualType ObjectType,
4429                                                    NamedDecl *UnqualLookup,
4430                                                    CXXScopeSpec &SS) {
4431   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4432     return TSInfo;
4433 
4434   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4435                                    UnqualLookup, SS);
4436 }
4437 
4438 template <typename Derived>
4439 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4440     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4441     CXXScopeSpec &SS) {
4442   QualType T = TL.getType();
4443   assert(!getDerived().AlreadyTransformed(T));
4444 
4445   TypeLocBuilder TLB;
4446   QualType Result;
4447 
4448   if (isa<TemplateSpecializationType>(T)) {
4449     TemplateSpecializationTypeLoc SpecTL =
4450         TL.castAs<TemplateSpecializationTypeLoc>();
4451 
4452     TemplateName Template = getDerived().TransformTemplateName(
4453         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4454         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4455     if (Template.isNull())
4456       return nullptr;
4457 
4458     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4459                                                               Template);
4460   } else if (isa<DependentTemplateSpecializationType>(T)) {
4461     DependentTemplateSpecializationTypeLoc SpecTL =
4462         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4463 
4464     TemplateName Template
4465       = getDerived().RebuildTemplateName(SS,
4466                                          SpecTL.getTemplateKeywordLoc(),
4467                                          *SpecTL.getTypePtr()->getIdentifier(),
4468                                          SpecTL.getTemplateNameLoc(),
4469                                          ObjectType, UnqualLookup,
4470                                          /*AllowInjectedClassName*/true);
4471     if (Template.isNull())
4472       return nullptr;
4473 
4474     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4475                                                                        SpecTL,
4476                                                                        Template,
4477                                                                        SS);
4478   } else {
4479     // Nothing special needs to be done for these.
4480     Result = getDerived().TransformType(TLB, TL);
4481   }
4482 
4483   if (Result.isNull())
4484     return nullptr;
4485 
4486   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4487 }
4488 
4489 template <class TyLoc> static inline
4490 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4491   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4492   NewT.setNameLoc(T.getNameLoc());
4493   return T.getType();
4494 }
4495 
4496 template<typename Derived>
4497 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4498                                                       BuiltinTypeLoc T) {
4499   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4500   NewT.setBuiltinLoc(T.getBuiltinLoc());
4501   if (T.needsExtraLocalData())
4502     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4503   return T.getType();
4504 }
4505 
4506 template<typename Derived>
4507 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4508                                                       ComplexTypeLoc T) {
4509   // FIXME: recurse?
4510   return TransformTypeSpecType(TLB, T);
4511 }
4512 
4513 template <typename Derived>
4514 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4515                                                        AdjustedTypeLoc TL) {
4516   // Adjustments applied during transformation are handled elsewhere.
4517   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4518 }
4519 
4520 template<typename Derived>
4521 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4522                                                       DecayedTypeLoc TL) {
4523   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4524   if (OriginalType.isNull())
4525     return QualType();
4526 
4527   QualType Result = TL.getType();
4528   if (getDerived().AlwaysRebuild() ||
4529       OriginalType != TL.getOriginalLoc().getType())
4530     Result = SemaRef.Context.getDecayedType(OriginalType);
4531   TLB.push<DecayedTypeLoc>(Result);
4532   // Nothing to set for DecayedTypeLoc.
4533   return Result;
4534 }
4535 
4536 /// Helper to deduce addr space of a pointee type in OpenCL mode.
4537 /// If the type is updated it will be overwritten in PointeeType param.
4538 static void deduceOpenCLPointeeAddrSpace(Sema &SemaRef, QualType &PointeeType) {
4539   if (PointeeType.getAddressSpace() == LangAS::Default)
4540     PointeeType = SemaRef.Context.getAddrSpaceQualType(PointeeType,
4541                                                        LangAS::opencl_generic);
4542 }
4543 
4544 template<typename Derived>
4545 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4546                                                       PointerTypeLoc TL) {
4547   QualType PointeeType
4548     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4549   if (PointeeType.isNull())
4550     return QualType();
4551 
4552   if (SemaRef.getLangOpts().OpenCL)
4553     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4554 
4555   QualType Result = TL.getType();
4556   if (PointeeType->getAs<ObjCObjectType>()) {
4557     // A dependent pointer type 'T *' has is being transformed such
4558     // that an Objective-C class type is being replaced for 'T'. The
4559     // resulting pointer type is an ObjCObjectPointerType, not a
4560     // PointerType.
4561     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4562 
4563     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4564     NewT.setStarLoc(TL.getStarLoc());
4565     return Result;
4566   }
4567 
4568   if (getDerived().AlwaysRebuild() ||
4569       PointeeType != TL.getPointeeLoc().getType()) {
4570     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4571     if (Result.isNull())
4572       return QualType();
4573   }
4574 
4575   // Objective-C ARC can add lifetime qualifiers to the type that we're
4576   // pointing to.
4577   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4578 
4579   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4580   NewT.setSigilLoc(TL.getSigilLoc());
4581   return Result;
4582 }
4583 
4584 template<typename Derived>
4585 QualType
4586 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4587                                                   BlockPointerTypeLoc TL) {
4588   QualType PointeeType
4589     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4590   if (PointeeType.isNull())
4591     return QualType();
4592 
4593   if (SemaRef.getLangOpts().OpenCL)
4594     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4595 
4596   QualType Result = TL.getType();
4597   if (getDerived().AlwaysRebuild() ||
4598       PointeeType != TL.getPointeeLoc().getType()) {
4599     Result = getDerived().RebuildBlockPointerType(PointeeType,
4600                                                   TL.getSigilLoc());
4601     if (Result.isNull())
4602       return QualType();
4603   }
4604 
4605   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4606   NewT.setSigilLoc(TL.getSigilLoc());
4607   return Result;
4608 }
4609 
4610 /// Transforms a reference type.  Note that somewhat paradoxically we
4611 /// don't care whether the type itself is an l-value type or an r-value
4612 /// type;  we only care if the type was *written* as an l-value type
4613 /// or an r-value type.
4614 template<typename Derived>
4615 QualType
4616 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4617                                                ReferenceTypeLoc TL) {
4618   const ReferenceType *T = TL.getTypePtr();
4619 
4620   // Note that this works with the pointee-as-written.
4621   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4622   if (PointeeType.isNull())
4623     return QualType();
4624 
4625   if (SemaRef.getLangOpts().OpenCL)
4626     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4627 
4628   QualType Result = TL.getType();
4629   if (getDerived().AlwaysRebuild() ||
4630       PointeeType != T->getPointeeTypeAsWritten()) {
4631     Result = getDerived().RebuildReferenceType(PointeeType,
4632                                                T->isSpelledAsLValue(),
4633                                                TL.getSigilLoc());
4634     if (Result.isNull())
4635       return QualType();
4636   }
4637 
4638   // Objective-C ARC can add lifetime qualifiers to the type that we're
4639   // referring to.
4640   TLB.TypeWasModifiedSafely(
4641                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4642 
4643   // r-value references can be rebuilt as l-value references.
4644   ReferenceTypeLoc NewTL;
4645   if (isa<LValueReferenceType>(Result))
4646     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4647   else
4648     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4649   NewTL.setSigilLoc(TL.getSigilLoc());
4650 
4651   return Result;
4652 }
4653 
4654 template<typename Derived>
4655 QualType
4656 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4657                                                  LValueReferenceTypeLoc TL) {
4658   return TransformReferenceType(TLB, TL);
4659 }
4660 
4661 template<typename Derived>
4662 QualType
4663 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4664                                                  RValueReferenceTypeLoc TL) {
4665   return TransformReferenceType(TLB, TL);
4666 }
4667 
4668 template<typename Derived>
4669 QualType
4670 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4671                                                    MemberPointerTypeLoc TL) {
4672   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4673   if (PointeeType.isNull())
4674     return QualType();
4675 
4676   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4677   TypeSourceInfo *NewClsTInfo = nullptr;
4678   if (OldClsTInfo) {
4679     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4680     if (!NewClsTInfo)
4681       return QualType();
4682   }
4683 
4684   const MemberPointerType *T = TL.getTypePtr();
4685   QualType OldClsType = QualType(T->getClass(), 0);
4686   QualType NewClsType;
4687   if (NewClsTInfo)
4688     NewClsType = NewClsTInfo->getType();
4689   else {
4690     NewClsType = getDerived().TransformType(OldClsType);
4691     if (NewClsType.isNull())
4692       return QualType();
4693   }
4694 
4695   QualType Result = TL.getType();
4696   if (getDerived().AlwaysRebuild() ||
4697       PointeeType != T->getPointeeType() ||
4698       NewClsType != OldClsType) {
4699     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4700                                                    TL.getStarLoc());
4701     if (Result.isNull())
4702       return QualType();
4703   }
4704 
4705   // If we had to adjust the pointee type when building a member pointer, make
4706   // sure to push TypeLoc info for it.
4707   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4708   if (MPT && PointeeType != MPT->getPointeeType()) {
4709     assert(isa<AdjustedType>(MPT->getPointeeType()));
4710     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4711   }
4712 
4713   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4714   NewTL.setSigilLoc(TL.getSigilLoc());
4715   NewTL.setClassTInfo(NewClsTInfo);
4716 
4717   return Result;
4718 }
4719 
4720 template<typename Derived>
4721 QualType
4722 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4723                                                    ConstantArrayTypeLoc TL) {
4724   const ConstantArrayType *T = TL.getTypePtr();
4725   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4726   if (ElementType.isNull())
4727     return QualType();
4728 
4729   QualType Result = TL.getType();
4730   if (getDerived().AlwaysRebuild() ||
4731       ElementType != T->getElementType()) {
4732     Result = getDerived().RebuildConstantArrayType(ElementType,
4733                                                    T->getSizeModifier(),
4734                                                    T->getSize(),
4735                                              T->getIndexTypeCVRQualifiers(),
4736                                                    TL.getBracketsRange());
4737     if (Result.isNull())
4738       return QualType();
4739   }
4740 
4741   // We might have either a ConstantArrayType or a VariableArrayType now:
4742   // a ConstantArrayType is allowed to have an element type which is a
4743   // VariableArrayType if the type is dependent.  Fortunately, all array
4744   // types have the same location layout.
4745   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4746   NewTL.setLBracketLoc(TL.getLBracketLoc());
4747   NewTL.setRBracketLoc(TL.getRBracketLoc());
4748 
4749   Expr *Size = TL.getSizeExpr();
4750   if (Size) {
4751     EnterExpressionEvaluationContext Unevaluated(
4752         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4753     Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4754     Size = SemaRef.ActOnConstantExpression(Size).get();
4755   }
4756   NewTL.setSizeExpr(Size);
4757 
4758   return Result;
4759 }
4760 
4761 template<typename Derived>
4762 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4763                                               TypeLocBuilder &TLB,
4764                                               IncompleteArrayTypeLoc TL) {
4765   const IncompleteArrayType *T = TL.getTypePtr();
4766   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4767   if (ElementType.isNull())
4768     return QualType();
4769 
4770   QualType Result = TL.getType();
4771   if (getDerived().AlwaysRebuild() ||
4772       ElementType != T->getElementType()) {
4773     Result = getDerived().RebuildIncompleteArrayType(ElementType,
4774                                                      T->getSizeModifier(),
4775                                            T->getIndexTypeCVRQualifiers(),
4776                                                      TL.getBracketsRange());
4777     if (Result.isNull())
4778       return QualType();
4779   }
4780 
4781   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4782   NewTL.setLBracketLoc(TL.getLBracketLoc());
4783   NewTL.setRBracketLoc(TL.getRBracketLoc());
4784   NewTL.setSizeExpr(nullptr);
4785 
4786   return Result;
4787 }
4788 
4789 template<typename Derived>
4790 QualType
4791 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4792                                                    VariableArrayTypeLoc TL) {
4793   const VariableArrayType *T = TL.getTypePtr();
4794   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4795   if (ElementType.isNull())
4796     return QualType();
4797 
4798   ExprResult SizeResult;
4799   {
4800     EnterExpressionEvaluationContext Context(
4801         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4802     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4803   }
4804   if (SizeResult.isInvalid())
4805     return QualType();
4806   SizeResult =
4807       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
4808   if (SizeResult.isInvalid())
4809     return QualType();
4810 
4811   Expr *Size = SizeResult.get();
4812 
4813   QualType Result = TL.getType();
4814   if (getDerived().AlwaysRebuild() ||
4815       ElementType != T->getElementType() ||
4816       Size != T->getSizeExpr()) {
4817     Result = getDerived().RebuildVariableArrayType(ElementType,
4818                                                    T->getSizeModifier(),
4819                                                    Size,
4820                                              T->getIndexTypeCVRQualifiers(),
4821                                                    TL.getBracketsRange());
4822     if (Result.isNull())
4823       return QualType();
4824   }
4825 
4826   // We might have constant size array now, but fortunately it has the same
4827   // location layout.
4828   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4829   NewTL.setLBracketLoc(TL.getLBracketLoc());
4830   NewTL.setRBracketLoc(TL.getRBracketLoc());
4831   NewTL.setSizeExpr(Size);
4832 
4833   return Result;
4834 }
4835 
4836 template<typename Derived>
4837 QualType
4838 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4839                                              DependentSizedArrayTypeLoc TL) {
4840   const DependentSizedArrayType *T = TL.getTypePtr();
4841   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4842   if (ElementType.isNull())
4843     return QualType();
4844 
4845   // Array bounds are constant expressions.
4846   EnterExpressionEvaluationContext Unevaluated(
4847       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4848 
4849   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4850   Expr *origSize = TL.getSizeExpr();
4851   if (!origSize) origSize = T->getSizeExpr();
4852 
4853   ExprResult sizeResult
4854     = getDerived().TransformExpr(origSize);
4855   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4856   if (sizeResult.isInvalid())
4857     return QualType();
4858 
4859   Expr *size = sizeResult.get();
4860 
4861   QualType Result = TL.getType();
4862   if (getDerived().AlwaysRebuild() ||
4863       ElementType != T->getElementType() ||
4864       size != origSize) {
4865     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4866                                                          T->getSizeModifier(),
4867                                                          size,
4868                                                 T->getIndexTypeCVRQualifiers(),
4869                                                         TL.getBracketsRange());
4870     if (Result.isNull())
4871       return QualType();
4872   }
4873 
4874   // We might have any sort of array type now, but fortunately they
4875   // all have the same location layout.
4876   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4877   NewTL.setLBracketLoc(TL.getLBracketLoc());
4878   NewTL.setRBracketLoc(TL.getRBracketLoc());
4879   NewTL.setSizeExpr(size);
4880 
4881   return Result;
4882 }
4883 
4884 template <typename Derived>
4885 QualType TreeTransform<Derived>::TransformDependentVectorType(
4886     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4887   const DependentVectorType *T = TL.getTypePtr();
4888   QualType ElementType = getDerived().TransformType(T->getElementType());
4889   if (ElementType.isNull())
4890     return QualType();
4891 
4892   EnterExpressionEvaluationContext Unevaluated(
4893       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4894 
4895   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4896   Size = SemaRef.ActOnConstantExpression(Size);
4897   if (Size.isInvalid())
4898     return QualType();
4899 
4900   QualType Result = TL.getType();
4901   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
4902       Size.get() != T->getSizeExpr()) {
4903     Result = getDerived().RebuildDependentVectorType(
4904         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
4905     if (Result.isNull())
4906       return QualType();
4907   }
4908 
4909   // Result might be dependent or not.
4910   if (isa<DependentVectorType>(Result)) {
4911     DependentVectorTypeLoc NewTL =
4912         TLB.push<DependentVectorTypeLoc>(Result);
4913     NewTL.setNameLoc(TL.getNameLoc());
4914   } else {
4915     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4916     NewTL.setNameLoc(TL.getNameLoc());
4917   }
4918 
4919   return Result;
4920 }
4921 
4922 template<typename Derived>
4923 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4924                                       TypeLocBuilder &TLB,
4925                                       DependentSizedExtVectorTypeLoc TL) {
4926   const DependentSizedExtVectorType *T = TL.getTypePtr();
4927 
4928   // FIXME: ext vector locs should be nested
4929   QualType ElementType = getDerived().TransformType(T->getElementType());
4930   if (ElementType.isNull())
4931     return QualType();
4932 
4933   // Vector sizes are constant expressions.
4934   EnterExpressionEvaluationContext Unevaluated(
4935       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4936 
4937   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4938   Size = SemaRef.ActOnConstantExpression(Size);
4939   if (Size.isInvalid())
4940     return QualType();
4941 
4942   QualType Result = TL.getType();
4943   if (getDerived().AlwaysRebuild() ||
4944       ElementType != T->getElementType() ||
4945       Size.get() != T->getSizeExpr()) {
4946     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4947                                                              Size.get(),
4948                                                          T->getAttributeLoc());
4949     if (Result.isNull())
4950       return QualType();
4951   }
4952 
4953   // Result might be dependent or not.
4954   if (isa<DependentSizedExtVectorType>(Result)) {
4955     DependentSizedExtVectorTypeLoc NewTL
4956       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4957     NewTL.setNameLoc(TL.getNameLoc());
4958   } else {
4959     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4960     NewTL.setNameLoc(TL.getNameLoc());
4961   }
4962 
4963   return Result;
4964 }
4965 
4966 template <typename Derived>
4967 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
4968     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
4969   const DependentAddressSpaceType *T = TL.getTypePtr();
4970 
4971   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
4972 
4973   if (pointeeType.isNull())
4974     return QualType();
4975 
4976   // Address spaces are constant expressions.
4977   EnterExpressionEvaluationContext Unevaluated(
4978       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4979 
4980   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
4981   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
4982   if (AddrSpace.isInvalid())
4983     return QualType();
4984 
4985   QualType Result = TL.getType();
4986   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
4987       AddrSpace.get() != T->getAddrSpaceExpr()) {
4988     Result = getDerived().RebuildDependentAddressSpaceType(
4989         pointeeType, AddrSpace.get(), T->getAttributeLoc());
4990     if (Result.isNull())
4991       return QualType();
4992   }
4993 
4994   // Result might be dependent or not.
4995   if (isa<DependentAddressSpaceType>(Result)) {
4996     DependentAddressSpaceTypeLoc NewTL =
4997         TLB.push<DependentAddressSpaceTypeLoc>(Result);
4998 
4999     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5000     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5001     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5002 
5003   } else {
5004     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5005         Result, getDerived().getBaseLocation());
5006     TransformType(TLB, DI->getTypeLoc());
5007   }
5008 
5009   return Result;
5010 }
5011 
5012 template <typename Derived>
5013 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5014                                                      VectorTypeLoc TL) {
5015   const VectorType *T = TL.getTypePtr();
5016   QualType ElementType = getDerived().TransformType(T->getElementType());
5017   if (ElementType.isNull())
5018     return QualType();
5019 
5020   QualType Result = TL.getType();
5021   if (getDerived().AlwaysRebuild() ||
5022       ElementType != T->getElementType()) {
5023     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5024                                             T->getVectorKind());
5025     if (Result.isNull())
5026       return QualType();
5027   }
5028 
5029   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5030   NewTL.setNameLoc(TL.getNameLoc());
5031 
5032   return Result;
5033 }
5034 
5035 template<typename Derived>
5036 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5037                                                         ExtVectorTypeLoc TL) {
5038   const VectorType *T = TL.getTypePtr();
5039   QualType ElementType = getDerived().TransformType(T->getElementType());
5040   if (ElementType.isNull())
5041     return QualType();
5042 
5043   QualType Result = TL.getType();
5044   if (getDerived().AlwaysRebuild() ||
5045       ElementType != T->getElementType()) {
5046     Result = getDerived().RebuildExtVectorType(ElementType,
5047                                                T->getNumElements(),
5048                                                /*FIXME*/ SourceLocation());
5049     if (Result.isNull())
5050       return QualType();
5051   }
5052 
5053   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5054   NewTL.setNameLoc(TL.getNameLoc());
5055 
5056   return Result;
5057 }
5058 
5059 template <typename Derived>
5060 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5061     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5062     bool ExpectParameterPack) {
5063   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5064   TypeSourceInfo *NewDI = nullptr;
5065 
5066   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5067     // If we're substituting into a pack expansion type and we know the
5068     // length we want to expand to, just substitute for the pattern.
5069     TypeLoc OldTL = OldDI->getTypeLoc();
5070     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5071 
5072     TypeLocBuilder TLB;
5073     TypeLoc NewTL = OldDI->getTypeLoc();
5074     TLB.reserve(NewTL.getFullDataSize());
5075 
5076     QualType Result = getDerived().TransformType(TLB,
5077                                                OldExpansionTL.getPatternLoc());
5078     if (Result.isNull())
5079       return nullptr;
5080 
5081     Result = RebuildPackExpansionType(Result,
5082                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5083                                       OldExpansionTL.getEllipsisLoc(),
5084                                       NumExpansions);
5085     if (Result.isNull())
5086       return nullptr;
5087 
5088     PackExpansionTypeLoc NewExpansionTL
5089       = TLB.push<PackExpansionTypeLoc>(Result);
5090     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5091     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5092   } else
5093     NewDI = getDerived().TransformType(OldDI);
5094   if (!NewDI)
5095     return nullptr;
5096 
5097   if (NewDI == OldDI && indexAdjustment == 0)
5098     return OldParm;
5099 
5100   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5101                                              OldParm->getDeclContext(),
5102                                              OldParm->getInnerLocStart(),
5103                                              OldParm->getLocation(),
5104                                              OldParm->getIdentifier(),
5105                                              NewDI->getType(),
5106                                              NewDI,
5107                                              OldParm->getStorageClass(),
5108                                              /* DefArg */ nullptr);
5109   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5110                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5111   return newParm;
5112 }
5113 
5114 template <typename Derived>
5115 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5116     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5117     const QualType *ParamTypes,
5118     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5119     SmallVectorImpl<QualType> &OutParamTypes,
5120     SmallVectorImpl<ParmVarDecl *> *PVars,
5121     Sema::ExtParameterInfoBuilder &PInfos) {
5122   int indexAdjustment = 0;
5123 
5124   unsigned NumParams = Params.size();
5125   for (unsigned i = 0; i != NumParams; ++i) {
5126     if (ParmVarDecl *OldParm = Params[i]) {
5127       assert(OldParm->getFunctionScopeIndex() == i);
5128 
5129       Optional<unsigned> NumExpansions;
5130       ParmVarDecl *NewParm = nullptr;
5131       if (OldParm->isParameterPack()) {
5132         // We have a function parameter pack that may need to be expanded.
5133         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5134 
5135         // Find the parameter packs that could be expanded.
5136         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5137         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5138         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5139         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5140         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
5141 
5142         // Determine whether we should expand the parameter packs.
5143         bool ShouldExpand = false;
5144         bool RetainExpansion = false;
5145         Optional<unsigned> OrigNumExpansions =
5146             ExpansionTL.getTypePtr()->getNumExpansions();
5147         NumExpansions = OrigNumExpansions;
5148         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5149                                                  Pattern.getSourceRange(),
5150                                                  Unexpanded,
5151                                                  ShouldExpand,
5152                                                  RetainExpansion,
5153                                                  NumExpansions)) {
5154           return true;
5155         }
5156 
5157         if (ShouldExpand) {
5158           // Expand the function parameter pack into multiple, separate
5159           // parameters.
5160           getDerived().ExpandingFunctionParameterPack(OldParm);
5161           for (unsigned I = 0; I != *NumExpansions; ++I) {
5162             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5163             ParmVarDecl *NewParm
5164               = getDerived().TransformFunctionTypeParam(OldParm,
5165                                                         indexAdjustment++,
5166                                                         OrigNumExpansions,
5167                                                 /*ExpectParameterPack=*/false);
5168             if (!NewParm)
5169               return true;
5170 
5171             if (ParamInfos)
5172               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5173             OutParamTypes.push_back(NewParm->getType());
5174             if (PVars)
5175               PVars->push_back(NewParm);
5176           }
5177 
5178           // If we're supposed to retain a pack expansion, do so by temporarily
5179           // forgetting the partially-substituted parameter pack.
5180           if (RetainExpansion) {
5181             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5182             ParmVarDecl *NewParm
5183               = getDerived().TransformFunctionTypeParam(OldParm,
5184                                                         indexAdjustment++,
5185                                                         OrigNumExpansions,
5186                                                 /*ExpectParameterPack=*/false);
5187             if (!NewParm)
5188               return true;
5189 
5190             if (ParamInfos)
5191               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5192             OutParamTypes.push_back(NewParm->getType());
5193             if (PVars)
5194               PVars->push_back(NewParm);
5195           }
5196 
5197           // The next parameter should have the same adjustment as the
5198           // last thing we pushed, but we post-incremented indexAdjustment
5199           // on every push.  Also, if we push nothing, the adjustment should
5200           // go down by one.
5201           indexAdjustment--;
5202 
5203           // We're done with the pack expansion.
5204           continue;
5205         }
5206 
5207         // We'll substitute the parameter now without expanding the pack
5208         // expansion.
5209         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5210         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5211                                                           indexAdjustment,
5212                                                           NumExpansions,
5213                                                   /*ExpectParameterPack=*/true);
5214       } else {
5215         NewParm = getDerived().TransformFunctionTypeParam(
5216             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5217       }
5218 
5219       if (!NewParm)
5220         return true;
5221 
5222       if (ParamInfos)
5223         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5224       OutParamTypes.push_back(NewParm->getType());
5225       if (PVars)
5226         PVars->push_back(NewParm);
5227       continue;
5228     }
5229 
5230     // Deal with the possibility that we don't have a parameter
5231     // declaration for this parameter.
5232     QualType OldType = ParamTypes[i];
5233     bool IsPackExpansion = false;
5234     Optional<unsigned> NumExpansions;
5235     QualType NewType;
5236     if (const PackExpansionType *Expansion
5237                                        = dyn_cast<PackExpansionType>(OldType)) {
5238       // We have a function parameter pack that may need to be expanded.
5239       QualType Pattern = Expansion->getPattern();
5240       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5241       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5242 
5243       // Determine whether we should expand the parameter packs.
5244       bool ShouldExpand = false;
5245       bool RetainExpansion = false;
5246       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5247                                                Unexpanded,
5248                                                ShouldExpand,
5249                                                RetainExpansion,
5250                                                NumExpansions)) {
5251         return true;
5252       }
5253 
5254       if (ShouldExpand) {
5255         // Expand the function parameter pack into multiple, separate
5256         // parameters.
5257         for (unsigned I = 0; I != *NumExpansions; ++I) {
5258           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5259           QualType NewType = getDerived().TransformType(Pattern);
5260           if (NewType.isNull())
5261             return true;
5262 
5263           if (NewType->containsUnexpandedParameterPack()) {
5264             NewType =
5265                 getSema().getASTContext().getPackExpansionType(NewType, None);
5266 
5267             if (NewType.isNull())
5268               return true;
5269           }
5270 
5271           if (ParamInfos)
5272             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5273           OutParamTypes.push_back(NewType);
5274           if (PVars)
5275             PVars->push_back(nullptr);
5276         }
5277 
5278         // We're done with the pack expansion.
5279         continue;
5280       }
5281 
5282       // If we're supposed to retain a pack expansion, do so by temporarily
5283       // forgetting the partially-substituted parameter pack.
5284       if (RetainExpansion) {
5285         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5286         QualType NewType = getDerived().TransformType(Pattern);
5287         if (NewType.isNull())
5288           return true;
5289 
5290         if (ParamInfos)
5291           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5292         OutParamTypes.push_back(NewType);
5293         if (PVars)
5294           PVars->push_back(nullptr);
5295       }
5296 
5297       // We'll substitute the parameter now without expanding the pack
5298       // expansion.
5299       OldType = Expansion->getPattern();
5300       IsPackExpansion = true;
5301       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5302       NewType = getDerived().TransformType(OldType);
5303     } else {
5304       NewType = getDerived().TransformType(OldType);
5305     }
5306 
5307     if (NewType.isNull())
5308       return true;
5309 
5310     if (IsPackExpansion)
5311       NewType = getSema().Context.getPackExpansionType(NewType,
5312                                                        NumExpansions);
5313 
5314     if (ParamInfos)
5315       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5316     OutParamTypes.push_back(NewType);
5317     if (PVars)
5318       PVars->push_back(nullptr);
5319   }
5320 
5321 #ifndef NDEBUG
5322   if (PVars) {
5323     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5324       if (ParmVarDecl *parm = (*PVars)[i])
5325         assert(parm->getFunctionScopeIndex() == i);
5326   }
5327 #endif
5328 
5329   return false;
5330 }
5331 
5332 template<typename Derived>
5333 QualType
5334 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5335                                                    FunctionProtoTypeLoc TL) {
5336   SmallVector<QualType, 4> ExceptionStorage;
5337   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5338   return getDerived().TransformFunctionProtoType(
5339       TLB, TL, nullptr, Qualifiers(),
5340       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5341         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5342                                             ExceptionStorage, Changed);
5343       });
5344 }
5345 
5346 template<typename Derived> template<typename Fn>
5347 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5348     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5349     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5350 
5351   // Transform the parameters and return type.
5352   //
5353   // We are required to instantiate the params and return type in source order.
5354   // When the function has a trailing return type, we instantiate the
5355   // parameters before the return type,  since the return type can then refer
5356   // to the parameters themselves (via decltype, sizeof, etc.).
5357   //
5358   SmallVector<QualType, 4> ParamTypes;
5359   SmallVector<ParmVarDecl*, 4> ParamDecls;
5360   Sema::ExtParameterInfoBuilder ExtParamInfos;
5361   const FunctionProtoType *T = TL.getTypePtr();
5362 
5363   QualType ResultType;
5364 
5365   if (T->hasTrailingReturn()) {
5366     if (getDerived().TransformFunctionTypeParams(
5367             TL.getBeginLoc(), TL.getParams(),
5368             TL.getTypePtr()->param_type_begin(),
5369             T->getExtParameterInfosOrNull(),
5370             ParamTypes, &ParamDecls, ExtParamInfos))
5371       return QualType();
5372 
5373     {
5374       // C++11 [expr.prim.general]p3:
5375       //   If a declaration declares a member function or member function
5376       //   template of a class X, the expression this is a prvalue of type
5377       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5378       //   and the end of the function-definition, member-declarator, or
5379       //   declarator.
5380       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5381 
5382       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5383       if (ResultType.isNull())
5384         return QualType();
5385     }
5386   }
5387   else {
5388     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5389     if (ResultType.isNull())
5390       return QualType();
5391 
5392     if (getDerived().TransformFunctionTypeParams(
5393             TL.getBeginLoc(), TL.getParams(),
5394             TL.getTypePtr()->param_type_begin(),
5395             T->getExtParameterInfosOrNull(),
5396             ParamTypes, &ParamDecls, ExtParamInfos))
5397       return QualType();
5398   }
5399 
5400   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5401 
5402   bool EPIChanged = false;
5403   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5404     return QualType();
5405 
5406   // Handle extended parameter information.
5407   if (auto NewExtParamInfos =
5408         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5409     if (!EPI.ExtParameterInfos ||
5410         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5411           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5412       EPIChanged = true;
5413     }
5414     EPI.ExtParameterInfos = NewExtParamInfos;
5415   } else if (EPI.ExtParameterInfos) {
5416     EPIChanged = true;
5417     EPI.ExtParameterInfos = nullptr;
5418   }
5419 
5420   QualType Result = TL.getType();
5421   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5422       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5423     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5424     if (Result.isNull())
5425       return QualType();
5426   }
5427 
5428   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5429   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5430   NewTL.setLParenLoc(TL.getLParenLoc());
5431   NewTL.setRParenLoc(TL.getRParenLoc());
5432   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5433   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5434   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5435     NewTL.setParam(i, ParamDecls[i]);
5436 
5437   return Result;
5438 }
5439 
5440 template<typename Derived>
5441 bool TreeTransform<Derived>::TransformExceptionSpec(
5442     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5443     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5444   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5445 
5446   // Instantiate a dynamic noexcept expression, if any.
5447   if (isComputedNoexcept(ESI.Type)) {
5448     EnterExpressionEvaluationContext Unevaluated(
5449         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5450     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5451     if (NoexceptExpr.isInvalid())
5452       return true;
5453 
5454     ExceptionSpecificationType EST = ESI.Type;
5455     NoexceptExpr =
5456         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5457     if (NoexceptExpr.isInvalid())
5458       return true;
5459 
5460     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5461       Changed = true;
5462     ESI.NoexceptExpr = NoexceptExpr.get();
5463     ESI.Type = EST;
5464   }
5465 
5466   if (ESI.Type != EST_Dynamic)
5467     return false;
5468 
5469   // Instantiate a dynamic exception specification's type.
5470   for (QualType T : ESI.Exceptions) {
5471     if (const PackExpansionType *PackExpansion =
5472             T->getAs<PackExpansionType>()) {
5473       Changed = true;
5474 
5475       // We have a pack expansion. Instantiate it.
5476       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5477       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5478                                               Unexpanded);
5479       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5480 
5481       // Determine whether the set of unexpanded parameter packs can and
5482       // should
5483       // be expanded.
5484       bool Expand = false;
5485       bool RetainExpansion = false;
5486       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5487       // FIXME: Track the location of the ellipsis (and track source location
5488       // information for the types in the exception specification in general).
5489       if (getDerived().TryExpandParameterPacks(
5490               Loc, SourceRange(), Unexpanded, Expand,
5491               RetainExpansion, NumExpansions))
5492         return true;
5493 
5494       if (!Expand) {
5495         // We can't expand this pack expansion into separate arguments yet;
5496         // just substitute into the pattern and create a new pack expansion
5497         // type.
5498         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5499         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5500         if (U.isNull())
5501           return true;
5502 
5503         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5504         Exceptions.push_back(U);
5505         continue;
5506       }
5507 
5508       // Substitute into the pack expansion pattern for each slice of the
5509       // pack.
5510       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5511         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5512 
5513         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5514         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5515           return true;
5516 
5517         Exceptions.push_back(U);
5518       }
5519     } else {
5520       QualType U = getDerived().TransformType(T);
5521       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5522         return true;
5523       if (T != U)
5524         Changed = true;
5525 
5526       Exceptions.push_back(U);
5527     }
5528   }
5529 
5530   ESI.Exceptions = Exceptions;
5531   if (ESI.Exceptions.empty())
5532     ESI.Type = EST_DynamicNone;
5533   return false;
5534 }
5535 
5536 template<typename Derived>
5537 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5538                                                  TypeLocBuilder &TLB,
5539                                                  FunctionNoProtoTypeLoc TL) {
5540   const FunctionNoProtoType *T = TL.getTypePtr();
5541   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5542   if (ResultType.isNull())
5543     return QualType();
5544 
5545   QualType Result = TL.getType();
5546   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5547     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5548 
5549   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5550   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5551   NewTL.setLParenLoc(TL.getLParenLoc());
5552   NewTL.setRParenLoc(TL.getRParenLoc());
5553   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5554 
5555   return Result;
5556 }
5557 
5558 template<typename Derived> QualType
5559 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5560                                                  UnresolvedUsingTypeLoc TL) {
5561   const UnresolvedUsingType *T = TL.getTypePtr();
5562   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5563   if (!D)
5564     return QualType();
5565 
5566   QualType Result = TL.getType();
5567   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5568     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5569     if (Result.isNull())
5570       return QualType();
5571   }
5572 
5573   // We might get an arbitrary type spec type back.  We should at
5574   // least always get a type spec type, though.
5575   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5576   NewTL.setNameLoc(TL.getNameLoc());
5577 
5578   return Result;
5579 }
5580 
5581 template<typename Derived>
5582 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5583                                                       TypedefTypeLoc TL) {
5584   const TypedefType *T = TL.getTypePtr();
5585   TypedefNameDecl *Typedef
5586     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5587                                                                T->getDecl()));
5588   if (!Typedef)
5589     return QualType();
5590 
5591   QualType Result = TL.getType();
5592   if (getDerived().AlwaysRebuild() ||
5593       Typedef != T->getDecl()) {
5594     Result = getDerived().RebuildTypedefType(Typedef);
5595     if (Result.isNull())
5596       return QualType();
5597   }
5598 
5599   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5600   NewTL.setNameLoc(TL.getNameLoc());
5601 
5602   return Result;
5603 }
5604 
5605 template<typename Derived>
5606 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5607                                                       TypeOfExprTypeLoc TL) {
5608   // typeof expressions are not potentially evaluated contexts
5609   EnterExpressionEvaluationContext Unevaluated(
5610       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5611       Sema::ReuseLambdaContextDecl);
5612 
5613   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5614   if (E.isInvalid())
5615     return QualType();
5616 
5617   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5618   if (E.isInvalid())
5619     return QualType();
5620 
5621   QualType Result = TL.getType();
5622   if (getDerived().AlwaysRebuild() ||
5623       E.get() != TL.getUnderlyingExpr()) {
5624     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5625     if (Result.isNull())
5626       return QualType();
5627   }
5628   else E.get();
5629 
5630   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5631   NewTL.setTypeofLoc(TL.getTypeofLoc());
5632   NewTL.setLParenLoc(TL.getLParenLoc());
5633   NewTL.setRParenLoc(TL.getRParenLoc());
5634 
5635   return Result;
5636 }
5637 
5638 template<typename Derived>
5639 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5640                                                      TypeOfTypeLoc TL) {
5641   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5642   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5643   if (!New_Under_TI)
5644     return QualType();
5645 
5646   QualType Result = TL.getType();
5647   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5648     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5649     if (Result.isNull())
5650       return QualType();
5651   }
5652 
5653   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5654   NewTL.setTypeofLoc(TL.getTypeofLoc());
5655   NewTL.setLParenLoc(TL.getLParenLoc());
5656   NewTL.setRParenLoc(TL.getRParenLoc());
5657   NewTL.setUnderlyingTInfo(New_Under_TI);
5658 
5659   return Result;
5660 }
5661 
5662 template<typename Derived>
5663 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5664                                                        DecltypeTypeLoc TL) {
5665   const DecltypeType *T = TL.getTypePtr();
5666 
5667   // decltype expressions are not potentially evaluated contexts
5668   EnterExpressionEvaluationContext Unevaluated(
5669       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5670       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5671 
5672   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5673   if (E.isInvalid())
5674     return QualType();
5675 
5676   E = getSema().ActOnDecltypeExpression(E.get());
5677   if (E.isInvalid())
5678     return QualType();
5679 
5680   QualType Result = TL.getType();
5681   if (getDerived().AlwaysRebuild() ||
5682       E.get() != T->getUnderlyingExpr()) {
5683     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5684     if (Result.isNull())
5685       return QualType();
5686   }
5687   else E.get();
5688 
5689   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5690   NewTL.setNameLoc(TL.getNameLoc());
5691 
5692   return Result;
5693 }
5694 
5695 template<typename Derived>
5696 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5697                                                             TypeLocBuilder &TLB,
5698                                                      UnaryTransformTypeLoc TL) {
5699   QualType Result = TL.getType();
5700   if (Result->isDependentType()) {
5701     const UnaryTransformType *T = TL.getTypePtr();
5702     QualType NewBase =
5703       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5704     Result = getDerived().RebuildUnaryTransformType(NewBase,
5705                                                     T->getUTTKind(),
5706                                                     TL.getKWLoc());
5707     if (Result.isNull())
5708       return QualType();
5709   }
5710 
5711   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5712   NewTL.setKWLoc(TL.getKWLoc());
5713   NewTL.setParensRange(TL.getParensRange());
5714   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5715   return Result;
5716 }
5717 
5718 template<typename Derived>
5719 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5720                                                    AutoTypeLoc TL) {
5721   const AutoType *T = TL.getTypePtr();
5722   QualType OldDeduced = T->getDeducedType();
5723   QualType NewDeduced;
5724   if (!OldDeduced.isNull()) {
5725     NewDeduced = getDerived().TransformType(OldDeduced);
5726     if (NewDeduced.isNull())
5727       return QualType();
5728   }
5729 
5730   QualType Result = TL.getType();
5731   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5732       T->isDependentType()) {
5733     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5734     if (Result.isNull())
5735       return QualType();
5736   }
5737 
5738   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5739   NewTL.setNameLoc(TL.getNameLoc());
5740 
5741   return Result;
5742 }
5743 
5744 template<typename Derived>
5745 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5746     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5747   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5748 
5749   CXXScopeSpec SS;
5750   TemplateName TemplateName = getDerived().TransformTemplateName(
5751       SS, T->getTemplateName(), TL.getTemplateNameLoc());
5752   if (TemplateName.isNull())
5753     return QualType();
5754 
5755   QualType OldDeduced = T->getDeducedType();
5756   QualType NewDeduced;
5757   if (!OldDeduced.isNull()) {
5758     NewDeduced = getDerived().TransformType(OldDeduced);
5759     if (NewDeduced.isNull())
5760       return QualType();
5761   }
5762 
5763   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5764       TemplateName, NewDeduced);
5765   if (Result.isNull())
5766     return QualType();
5767 
5768   DeducedTemplateSpecializationTypeLoc NewTL =
5769       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5770   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5771 
5772   return Result;
5773 }
5774 
5775 template<typename Derived>
5776 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5777                                                      RecordTypeLoc TL) {
5778   const RecordType *T = TL.getTypePtr();
5779   RecordDecl *Record
5780     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5781                                                           T->getDecl()));
5782   if (!Record)
5783     return QualType();
5784 
5785   QualType Result = TL.getType();
5786   if (getDerived().AlwaysRebuild() ||
5787       Record != T->getDecl()) {
5788     Result = getDerived().RebuildRecordType(Record);
5789     if (Result.isNull())
5790       return QualType();
5791   }
5792 
5793   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5794   NewTL.setNameLoc(TL.getNameLoc());
5795 
5796   return Result;
5797 }
5798 
5799 template<typename Derived>
5800 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5801                                                    EnumTypeLoc TL) {
5802   const EnumType *T = TL.getTypePtr();
5803   EnumDecl *Enum
5804     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5805                                                         T->getDecl()));
5806   if (!Enum)
5807     return QualType();
5808 
5809   QualType Result = TL.getType();
5810   if (getDerived().AlwaysRebuild() ||
5811       Enum != T->getDecl()) {
5812     Result = getDerived().RebuildEnumType(Enum);
5813     if (Result.isNull())
5814       return QualType();
5815   }
5816 
5817   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5818   NewTL.setNameLoc(TL.getNameLoc());
5819 
5820   return Result;
5821 }
5822 
5823 template<typename Derived>
5824 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5825                                          TypeLocBuilder &TLB,
5826                                          InjectedClassNameTypeLoc TL) {
5827   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5828                                        TL.getTypePtr()->getDecl());
5829   if (!D) return QualType();
5830 
5831   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5832   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5833   return T;
5834 }
5835 
5836 template<typename Derived>
5837 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5838                                                 TypeLocBuilder &TLB,
5839                                                 TemplateTypeParmTypeLoc TL) {
5840   return TransformTypeSpecType(TLB, TL);
5841 }
5842 
5843 template<typename Derived>
5844 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5845                                          TypeLocBuilder &TLB,
5846                                          SubstTemplateTypeParmTypeLoc TL) {
5847   const SubstTemplateTypeParmType *T = TL.getTypePtr();
5848 
5849   // Substitute into the replacement type, which itself might involve something
5850   // that needs to be transformed. This only tends to occur with default
5851   // template arguments of template template parameters.
5852   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5853   QualType Replacement = getDerived().TransformType(T->getReplacementType());
5854   if (Replacement.isNull())
5855     return QualType();
5856 
5857   // Always canonicalize the replacement type.
5858   Replacement = SemaRef.Context.getCanonicalType(Replacement);
5859   QualType Result
5860     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5861                                                    Replacement);
5862 
5863   // Propagate type-source information.
5864   SubstTemplateTypeParmTypeLoc NewTL
5865     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5866   NewTL.setNameLoc(TL.getNameLoc());
5867   return Result;
5868 
5869 }
5870 
5871 template<typename Derived>
5872 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5873                                           TypeLocBuilder &TLB,
5874                                           SubstTemplateTypeParmPackTypeLoc TL) {
5875   return TransformTypeSpecType(TLB, TL);
5876 }
5877 
5878 template<typename Derived>
5879 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5880                                                         TypeLocBuilder &TLB,
5881                                            TemplateSpecializationTypeLoc TL) {
5882   const TemplateSpecializationType *T = TL.getTypePtr();
5883 
5884   // The nested-name-specifier never matters in a TemplateSpecializationType,
5885   // because we can't have a dependent nested-name-specifier anyway.
5886   CXXScopeSpec SS;
5887   TemplateName Template
5888     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5889                                          TL.getTemplateNameLoc());
5890   if (Template.isNull())
5891     return QualType();
5892 
5893   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5894 }
5895 
5896 template<typename Derived>
5897 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5898                                                      AtomicTypeLoc TL) {
5899   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5900   if (ValueType.isNull())
5901     return QualType();
5902 
5903   QualType Result = TL.getType();
5904   if (getDerived().AlwaysRebuild() ||
5905       ValueType != TL.getValueLoc().getType()) {
5906     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5907     if (Result.isNull())
5908       return QualType();
5909   }
5910 
5911   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5912   NewTL.setKWLoc(TL.getKWLoc());
5913   NewTL.setLParenLoc(TL.getLParenLoc());
5914   NewTL.setRParenLoc(TL.getRParenLoc());
5915 
5916   return Result;
5917 }
5918 
5919 template <typename Derived>
5920 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5921                                                    PipeTypeLoc TL) {
5922   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5923   if (ValueType.isNull())
5924     return QualType();
5925 
5926   QualType Result = TL.getType();
5927   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5928     const PipeType *PT = Result->getAs<PipeType>();
5929     bool isReadPipe = PT->isReadOnly();
5930     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5931     if (Result.isNull())
5932       return QualType();
5933   }
5934 
5935   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5936   NewTL.setKWLoc(TL.getKWLoc());
5937 
5938   return Result;
5939 }
5940 
5941   /// Simple iterator that traverses the template arguments in a
5942   /// container that provides a \c getArgLoc() member function.
5943   ///
5944   /// This iterator is intended to be used with the iterator form of
5945   /// \c TreeTransform<Derived>::TransformTemplateArguments().
5946   template<typename ArgLocContainer>
5947   class TemplateArgumentLocContainerIterator {
5948     ArgLocContainer *Container;
5949     unsigned Index;
5950 
5951   public:
5952     typedef TemplateArgumentLoc value_type;
5953     typedef TemplateArgumentLoc reference;
5954     typedef int difference_type;
5955     typedef std::input_iterator_tag iterator_category;
5956 
5957     class pointer {
5958       TemplateArgumentLoc Arg;
5959 
5960     public:
5961       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5962 
5963       const TemplateArgumentLoc *operator->() const {
5964         return &Arg;
5965       }
5966     };
5967 
5968 
5969     TemplateArgumentLocContainerIterator() {}
5970 
5971     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5972                                  unsigned Index)
5973       : Container(&Container), Index(Index) { }
5974 
5975     TemplateArgumentLocContainerIterator &operator++() {
5976       ++Index;
5977       return *this;
5978     }
5979 
5980     TemplateArgumentLocContainerIterator operator++(int) {
5981       TemplateArgumentLocContainerIterator Old(*this);
5982       ++(*this);
5983       return Old;
5984     }
5985 
5986     TemplateArgumentLoc operator*() const {
5987       return Container->getArgLoc(Index);
5988     }
5989 
5990     pointer operator->() const {
5991       return pointer(Container->getArgLoc(Index));
5992     }
5993 
5994     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5995                            const TemplateArgumentLocContainerIterator &Y) {
5996       return X.Container == Y.Container && X.Index == Y.Index;
5997     }
5998 
5999     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6000                            const TemplateArgumentLocContainerIterator &Y) {
6001       return !(X == Y);
6002     }
6003   };
6004 
6005 
6006 template <typename Derived>
6007 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6008                                                         TypeLocBuilder &TLB,
6009                                            TemplateSpecializationTypeLoc TL,
6010                                                       TemplateName Template) {
6011   TemplateArgumentListInfo NewTemplateArgs;
6012   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6013   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6014   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6015     ArgIterator;
6016   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6017                                               ArgIterator(TL, TL.getNumArgs()),
6018                                               NewTemplateArgs))
6019     return QualType();
6020 
6021   // FIXME: maybe don't rebuild if all the template arguments are the same.
6022 
6023   QualType Result =
6024     getDerived().RebuildTemplateSpecializationType(Template,
6025                                                    TL.getTemplateNameLoc(),
6026                                                    NewTemplateArgs);
6027 
6028   if (!Result.isNull()) {
6029     // Specializations of template template parameters are represented as
6030     // TemplateSpecializationTypes, and substitution of type alias templates
6031     // within a dependent context can transform them into
6032     // DependentTemplateSpecializationTypes.
6033     if (isa<DependentTemplateSpecializationType>(Result)) {
6034       DependentTemplateSpecializationTypeLoc NewTL
6035         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6036       NewTL.setElaboratedKeywordLoc(SourceLocation());
6037       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6038       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6039       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6040       NewTL.setLAngleLoc(TL.getLAngleLoc());
6041       NewTL.setRAngleLoc(TL.getRAngleLoc());
6042       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6043         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6044       return Result;
6045     }
6046 
6047     TemplateSpecializationTypeLoc NewTL
6048       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6049     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6050     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6051     NewTL.setLAngleLoc(TL.getLAngleLoc());
6052     NewTL.setRAngleLoc(TL.getRAngleLoc());
6053     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6054       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6055   }
6056 
6057   return Result;
6058 }
6059 
6060 template <typename Derived>
6061 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6062                                      TypeLocBuilder &TLB,
6063                                      DependentTemplateSpecializationTypeLoc TL,
6064                                      TemplateName Template,
6065                                      CXXScopeSpec &SS) {
6066   TemplateArgumentListInfo NewTemplateArgs;
6067   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6068   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6069   typedef TemplateArgumentLocContainerIterator<
6070             DependentTemplateSpecializationTypeLoc> ArgIterator;
6071   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6072                                               ArgIterator(TL, TL.getNumArgs()),
6073                                               NewTemplateArgs))
6074     return QualType();
6075 
6076   // FIXME: maybe don't rebuild if all the template arguments are the same.
6077 
6078   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6079     QualType Result
6080       = getSema().Context.getDependentTemplateSpecializationType(
6081                                                 TL.getTypePtr()->getKeyword(),
6082                                                          DTN->getQualifier(),
6083                                                          DTN->getIdentifier(),
6084                                                                NewTemplateArgs);
6085 
6086     DependentTemplateSpecializationTypeLoc NewTL
6087       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6088     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6089     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6090     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6091     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6092     NewTL.setLAngleLoc(TL.getLAngleLoc());
6093     NewTL.setRAngleLoc(TL.getRAngleLoc());
6094     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6095       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6096     return Result;
6097   }
6098 
6099   QualType Result
6100     = getDerived().RebuildTemplateSpecializationType(Template,
6101                                                      TL.getTemplateNameLoc(),
6102                                                      NewTemplateArgs);
6103 
6104   if (!Result.isNull()) {
6105     /// FIXME: Wrap this in an elaborated-type-specifier?
6106     TemplateSpecializationTypeLoc NewTL
6107       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6108     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6109     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6110     NewTL.setLAngleLoc(TL.getLAngleLoc());
6111     NewTL.setRAngleLoc(TL.getRAngleLoc());
6112     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6113       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6114   }
6115 
6116   return Result;
6117 }
6118 
6119 template<typename Derived>
6120 QualType
6121 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6122                                                 ElaboratedTypeLoc TL) {
6123   const ElaboratedType *T = TL.getTypePtr();
6124 
6125   NestedNameSpecifierLoc QualifierLoc;
6126   // NOTE: the qualifier in an ElaboratedType is optional.
6127   if (TL.getQualifierLoc()) {
6128     QualifierLoc
6129       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6130     if (!QualifierLoc)
6131       return QualType();
6132   }
6133 
6134   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6135   if (NamedT.isNull())
6136     return QualType();
6137 
6138   // C++0x [dcl.type.elab]p2:
6139   //   If the identifier resolves to a typedef-name or the simple-template-id
6140   //   resolves to an alias template specialization, the
6141   //   elaborated-type-specifier is ill-formed.
6142   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6143     if (const TemplateSpecializationType *TST =
6144           NamedT->getAs<TemplateSpecializationType>()) {
6145       TemplateName Template = TST->getTemplateName();
6146       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6147               Template.getAsTemplateDecl())) {
6148         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6149                      diag::err_tag_reference_non_tag)
6150             << TAT << Sema::NTK_TypeAliasTemplate
6151             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6152         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6153       }
6154     }
6155   }
6156 
6157   QualType Result = TL.getType();
6158   if (getDerived().AlwaysRebuild() ||
6159       QualifierLoc != TL.getQualifierLoc() ||
6160       NamedT != T->getNamedType()) {
6161     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6162                                                 T->getKeyword(),
6163                                                 QualifierLoc, NamedT);
6164     if (Result.isNull())
6165       return QualType();
6166   }
6167 
6168   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6169   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6170   NewTL.setQualifierLoc(QualifierLoc);
6171   return Result;
6172 }
6173 
6174 template<typename Derived>
6175 QualType TreeTransform<Derived>::TransformAttributedType(
6176                                                 TypeLocBuilder &TLB,
6177                                                 AttributedTypeLoc TL) {
6178   const AttributedType *oldType = TL.getTypePtr();
6179   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6180   if (modifiedType.isNull())
6181     return QualType();
6182 
6183   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6184   const Attr *oldAttr = TL.getAttr();
6185   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6186   if (oldAttr && !newAttr)
6187     return QualType();
6188 
6189   QualType result = TL.getType();
6190 
6191   // FIXME: dependent operand expressions?
6192   if (getDerived().AlwaysRebuild() ||
6193       modifiedType != oldType->getModifiedType()) {
6194     // TODO: this is really lame; we should really be rebuilding the
6195     // equivalent type from first principles.
6196     QualType equivalentType
6197       = getDerived().TransformType(oldType->getEquivalentType());
6198     if (equivalentType.isNull())
6199       return QualType();
6200 
6201     // Check whether we can add nullability; it is only represented as
6202     // type sugar, and therefore cannot be diagnosed in any other way.
6203     if (auto nullability = oldType->getImmediateNullability()) {
6204       if (!modifiedType->canHaveNullability()) {
6205         SemaRef.Diag(TL.getAttr()->getLocation(),
6206                      diag::err_nullability_nonpointer)
6207             << DiagNullabilityKind(*nullability, false) << modifiedType;
6208         return QualType();
6209       }
6210     }
6211 
6212     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6213                                                modifiedType,
6214                                                equivalentType);
6215   }
6216 
6217   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6218   newTL.setAttr(newAttr);
6219   return result;
6220 }
6221 
6222 template<typename Derived>
6223 QualType
6224 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6225                                            ParenTypeLoc TL) {
6226   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6227   if (Inner.isNull())
6228     return QualType();
6229 
6230   QualType Result = TL.getType();
6231   if (getDerived().AlwaysRebuild() ||
6232       Inner != TL.getInnerLoc().getType()) {
6233     Result = getDerived().RebuildParenType(Inner);
6234     if (Result.isNull())
6235       return QualType();
6236   }
6237 
6238   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6239   NewTL.setLParenLoc(TL.getLParenLoc());
6240   NewTL.setRParenLoc(TL.getRParenLoc());
6241   return Result;
6242 }
6243 
6244 template <typename Derived>
6245 QualType
6246 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6247                                                     MacroQualifiedTypeLoc TL) {
6248   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6249   if (Inner.isNull())
6250     return QualType();
6251 
6252   QualType Result = TL.getType();
6253   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6254     Result =
6255         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6256     if (Result.isNull())
6257       return QualType();
6258   }
6259 
6260   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6261   NewTL.setExpansionLoc(TL.getExpansionLoc());
6262   return Result;
6263 }
6264 
6265 template<typename Derived>
6266 QualType TreeTransform<Derived>::TransformDependentNameType(
6267     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6268   return TransformDependentNameType(TLB, TL, false);
6269 }
6270 
6271 template<typename Derived>
6272 QualType TreeTransform<Derived>::TransformDependentNameType(
6273     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6274   const DependentNameType *T = TL.getTypePtr();
6275 
6276   NestedNameSpecifierLoc QualifierLoc
6277     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6278   if (!QualifierLoc)
6279     return QualType();
6280 
6281   QualType Result
6282     = getDerived().RebuildDependentNameType(T->getKeyword(),
6283                                             TL.getElaboratedKeywordLoc(),
6284                                             QualifierLoc,
6285                                             T->getIdentifier(),
6286                                             TL.getNameLoc(),
6287                                             DeducedTSTContext);
6288   if (Result.isNull())
6289     return QualType();
6290 
6291   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6292     QualType NamedT = ElabT->getNamedType();
6293     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6294 
6295     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6296     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6297     NewTL.setQualifierLoc(QualifierLoc);
6298   } else {
6299     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6300     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6301     NewTL.setQualifierLoc(QualifierLoc);
6302     NewTL.setNameLoc(TL.getNameLoc());
6303   }
6304   return Result;
6305 }
6306 
6307 template<typename Derived>
6308 QualType TreeTransform<Derived>::
6309           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6310                                  DependentTemplateSpecializationTypeLoc TL) {
6311   NestedNameSpecifierLoc QualifierLoc;
6312   if (TL.getQualifierLoc()) {
6313     QualifierLoc
6314       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6315     if (!QualifierLoc)
6316       return QualType();
6317   }
6318 
6319   return getDerived()
6320            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6321 }
6322 
6323 template<typename Derived>
6324 QualType TreeTransform<Derived>::
6325 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6326                                    DependentTemplateSpecializationTypeLoc TL,
6327                                        NestedNameSpecifierLoc QualifierLoc) {
6328   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6329 
6330   TemplateArgumentListInfo NewTemplateArgs;
6331   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6332   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6333 
6334   typedef TemplateArgumentLocContainerIterator<
6335   DependentTemplateSpecializationTypeLoc> ArgIterator;
6336   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6337                                               ArgIterator(TL, TL.getNumArgs()),
6338                                               NewTemplateArgs))
6339     return QualType();
6340 
6341   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6342       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6343       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6344       /*AllowInjectedClassName*/ false);
6345   if (Result.isNull())
6346     return QualType();
6347 
6348   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6349     QualType NamedT = ElabT->getNamedType();
6350 
6351     // Copy information relevant to the template specialization.
6352     TemplateSpecializationTypeLoc NamedTL
6353       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6354     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6355     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6356     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6357     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6358     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6359       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6360 
6361     // Copy information relevant to the elaborated type.
6362     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6363     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6364     NewTL.setQualifierLoc(QualifierLoc);
6365   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6366     DependentTemplateSpecializationTypeLoc SpecTL
6367       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6368     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6369     SpecTL.setQualifierLoc(QualifierLoc);
6370     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6371     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6372     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6373     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6374     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6375       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6376   } else {
6377     TemplateSpecializationTypeLoc SpecTL
6378       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6379     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6380     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6381     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6382     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6383     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6384       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6385   }
6386   return Result;
6387 }
6388 
6389 template<typename Derived>
6390 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6391                                                       PackExpansionTypeLoc TL) {
6392   QualType Pattern
6393     = getDerived().TransformType(TLB, TL.getPatternLoc());
6394   if (Pattern.isNull())
6395     return QualType();
6396 
6397   QualType Result = TL.getType();
6398   if (getDerived().AlwaysRebuild() ||
6399       Pattern != TL.getPatternLoc().getType()) {
6400     Result = getDerived().RebuildPackExpansionType(Pattern,
6401                                            TL.getPatternLoc().getSourceRange(),
6402                                                    TL.getEllipsisLoc(),
6403                                            TL.getTypePtr()->getNumExpansions());
6404     if (Result.isNull())
6405       return QualType();
6406   }
6407 
6408   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6409   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6410   return Result;
6411 }
6412 
6413 template<typename Derived>
6414 QualType
6415 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6416                                                    ObjCInterfaceTypeLoc TL) {
6417   // ObjCInterfaceType is never dependent.
6418   TLB.pushFullCopy(TL);
6419   return TL.getType();
6420 }
6421 
6422 template<typename Derived>
6423 QualType
6424 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6425                                                    ObjCTypeParamTypeLoc TL) {
6426   const ObjCTypeParamType *T = TL.getTypePtr();
6427   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6428       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6429   if (!OTP)
6430     return QualType();
6431 
6432   QualType Result = TL.getType();
6433   if (getDerived().AlwaysRebuild() ||
6434       OTP != T->getDecl()) {
6435     Result = getDerived().RebuildObjCTypeParamType(OTP,
6436                  TL.getProtocolLAngleLoc(),
6437                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6438                                     TL.getNumProtocols()),
6439                  TL.getProtocolLocs(),
6440                  TL.getProtocolRAngleLoc());
6441     if (Result.isNull())
6442       return QualType();
6443   }
6444 
6445   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6446   if (TL.getNumProtocols()) {
6447     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6448     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6449       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6450     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6451   }
6452   return Result;
6453 }
6454 
6455 template<typename Derived>
6456 QualType
6457 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6458                                                 ObjCObjectTypeLoc TL) {
6459   // Transform base type.
6460   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6461   if (BaseType.isNull())
6462     return QualType();
6463 
6464   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6465 
6466   // Transform type arguments.
6467   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6468   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6469     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6470     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6471     QualType TypeArg = TypeArgInfo->getType();
6472     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6473       AnyChanged = true;
6474 
6475       // We have a pack expansion. Instantiate it.
6476       const auto *PackExpansion = PackExpansionLoc.getType()
6477                                     ->castAs<PackExpansionType>();
6478       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6479       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6480                                               Unexpanded);
6481       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6482 
6483       // Determine whether the set of unexpanded parameter packs can
6484       // and should be expanded.
6485       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6486       bool Expand = false;
6487       bool RetainExpansion = false;
6488       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6489       if (getDerived().TryExpandParameterPacks(
6490             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6491             Unexpanded, Expand, RetainExpansion, NumExpansions))
6492         return QualType();
6493 
6494       if (!Expand) {
6495         // We can't expand this pack expansion into separate arguments yet;
6496         // just substitute into the pattern and create a new pack expansion
6497         // type.
6498         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6499 
6500         TypeLocBuilder TypeArgBuilder;
6501         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6502         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6503                                                              PatternLoc);
6504         if (NewPatternType.isNull())
6505           return QualType();
6506 
6507         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6508                                       NewPatternType, NumExpansions);
6509         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6510         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6511         NewTypeArgInfos.push_back(
6512           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6513         continue;
6514       }
6515 
6516       // Substitute into the pack expansion pattern for each slice of the
6517       // pack.
6518       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6519         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6520 
6521         TypeLocBuilder TypeArgBuilder;
6522         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6523 
6524         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6525                                                          PatternLoc);
6526         if (NewTypeArg.isNull())
6527           return QualType();
6528 
6529         NewTypeArgInfos.push_back(
6530           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6531       }
6532 
6533       continue;
6534     }
6535 
6536     TypeLocBuilder TypeArgBuilder;
6537     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6538     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6539     if (NewTypeArg.isNull())
6540       return QualType();
6541 
6542     // If nothing changed, just keep the old TypeSourceInfo.
6543     if (NewTypeArg == TypeArg) {
6544       NewTypeArgInfos.push_back(TypeArgInfo);
6545       continue;
6546     }
6547 
6548     NewTypeArgInfos.push_back(
6549       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6550     AnyChanged = true;
6551   }
6552 
6553   QualType Result = TL.getType();
6554   if (getDerived().AlwaysRebuild() || AnyChanged) {
6555     // Rebuild the type.
6556     Result = getDerived().RebuildObjCObjectType(
6557         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6558         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6559         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6560         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6561 
6562     if (Result.isNull())
6563       return QualType();
6564   }
6565 
6566   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6567   NewT.setHasBaseTypeAsWritten(true);
6568   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6569   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6570     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6571   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6572   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6573   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6574     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6575   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6576   return Result;
6577 }
6578 
6579 template<typename Derived>
6580 QualType
6581 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6582                                                ObjCObjectPointerTypeLoc TL) {
6583   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6584   if (PointeeType.isNull())
6585     return QualType();
6586 
6587   QualType Result = TL.getType();
6588   if (getDerived().AlwaysRebuild() ||
6589       PointeeType != TL.getPointeeLoc().getType()) {
6590     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6591                                                        TL.getStarLoc());
6592     if (Result.isNull())
6593       return QualType();
6594   }
6595 
6596   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6597   NewT.setStarLoc(TL.getStarLoc());
6598   return Result;
6599 }
6600 
6601 //===----------------------------------------------------------------------===//
6602 // Statement transformation
6603 //===----------------------------------------------------------------------===//
6604 template<typename Derived>
6605 StmtResult
6606 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6607   return S;
6608 }
6609 
6610 template<typename Derived>
6611 StmtResult
6612 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6613   return getDerived().TransformCompoundStmt(S, false);
6614 }
6615 
6616 template<typename Derived>
6617 StmtResult
6618 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6619                                               bool IsStmtExpr) {
6620   Sema::CompoundScopeRAII CompoundScope(getSema());
6621 
6622   const Stmt *ExprResult = S->getStmtExprResult();
6623   bool SubStmtInvalid = false;
6624   bool SubStmtChanged = false;
6625   SmallVector<Stmt*, 8> Statements;
6626   for (auto *B : S->body()) {
6627     StmtResult Result = getDerived().TransformStmt(
6628         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
6629 
6630     if (Result.isInvalid()) {
6631       // Immediately fail if this was a DeclStmt, since it's very
6632       // likely that this will cause problems for future statements.
6633       if (isa<DeclStmt>(B))
6634         return StmtError();
6635 
6636       // Otherwise, just keep processing substatements and fail later.
6637       SubStmtInvalid = true;
6638       continue;
6639     }
6640 
6641     SubStmtChanged = SubStmtChanged || Result.get() != B;
6642     Statements.push_back(Result.getAs<Stmt>());
6643   }
6644 
6645   if (SubStmtInvalid)
6646     return StmtError();
6647 
6648   if (!getDerived().AlwaysRebuild() &&
6649       !SubStmtChanged)
6650     return S;
6651 
6652   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6653                                           Statements,
6654                                           S->getRBracLoc(),
6655                                           IsStmtExpr);
6656 }
6657 
6658 template<typename Derived>
6659 StmtResult
6660 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6661   ExprResult LHS, RHS;
6662   {
6663     EnterExpressionEvaluationContext Unevaluated(
6664         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6665 
6666     // Transform the left-hand case value.
6667     LHS = getDerived().TransformExpr(S->getLHS());
6668     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6669     if (LHS.isInvalid())
6670       return StmtError();
6671 
6672     // Transform the right-hand case value (for the GNU case-range extension).
6673     RHS = getDerived().TransformExpr(S->getRHS());
6674     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6675     if (RHS.isInvalid())
6676       return StmtError();
6677   }
6678 
6679   // Build the case statement.
6680   // Case statements are always rebuilt so that they will attached to their
6681   // transformed switch statement.
6682   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6683                                                        LHS.get(),
6684                                                        S->getEllipsisLoc(),
6685                                                        RHS.get(),
6686                                                        S->getColonLoc());
6687   if (Case.isInvalid())
6688     return StmtError();
6689 
6690   // Transform the statement following the case
6691   StmtResult SubStmt =
6692       getDerived().TransformStmt(S->getSubStmt());
6693   if (SubStmt.isInvalid())
6694     return StmtError();
6695 
6696   // Attach the body to the case statement
6697   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6698 }
6699 
6700 template <typename Derived>
6701 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6702   // Transform the statement following the default case
6703   StmtResult SubStmt =
6704       getDerived().TransformStmt(S->getSubStmt());
6705   if (SubStmt.isInvalid())
6706     return StmtError();
6707 
6708   // Default statements are always rebuilt
6709   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6710                                          SubStmt.get());
6711 }
6712 
6713 template<typename Derived>
6714 StmtResult
6715 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
6716   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6717   if (SubStmt.isInvalid())
6718     return StmtError();
6719 
6720   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6721                                         S->getDecl());
6722   if (!LD)
6723     return StmtError();
6724 
6725   // If we're transforming "in-place" (we're not creating new local
6726   // declarations), assume we're replacing the old label statement
6727   // and clear out the reference to it.
6728   if (LD == S->getDecl())
6729     S->getDecl()->setStmt(nullptr);
6730 
6731   // FIXME: Pass the real colon location in.
6732   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6733                                        cast<LabelDecl>(LD), SourceLocation(),
6734                                        SubStmt.get());
6735 }
6736 
6737 template <typename Derived>
6738 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6739   if (!R)
6740     return R;
6741 
6742   switch (R->getKind()) {
6743 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6744 #define ATTR(X)
6745 #define PRAGMA_SPELLING_ATTR(X)                                                \
6746   case attr::X:                                                                \
6747     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6748 #include "clang/Basic/AttrList.inc"
6749   default:
6750     return R;
6751   }
6752 }
6753 
6754 template <typename Derived>
6755 StmtResult
6756 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
6757                                                 StmtDiscardKind SDK) {
6758   bool AttrsChanged = false;
6759   SmallVector<const Attr *, 1> Attrs;
6760 
6761   // Visit attributes and keep track if any are transformed.
6762   for (const auto *I : S->getAttrs()) {
6763     const Attr *R = getDerived().TransformAttr(I);
6764     AttrsChanged |= (I != R);
6765     Attrs.push_back(R);
6766   }
6767 
6768   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6769   if (SubStmt.isInvalid())
6770     return StmtError();
6771 
6772   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6773     return S;
6774 
6775   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6776                                             SubStmt.get());
6777 }
6778 
6779 template<typename Derived>
6780 StmtResult
6781 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6782   // Transform the initialization statement
6783   StmtResult Init = getDerived().TransformStmt(S->getInit());
6784   if (Init.isInvalid())
6785     return StmtError();
6786 
6787   // Transform the condition
6788   Sema::ConditionResult Cond = getDerived().TransformCondition(
6789       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6790       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6791                        : Sema::ConditionKind::Boolean);
6792   if (Cond.isInvalid())
6793     return StmtError();
6794 
6795   // If this is a constexpr if, determine which arm we should instantiate.
6796   llvm::Optional<bool> ConstexprConditionValue;
6797   if (S->isConstexpr())
6798     ConstexprConditionValue = Cond.getKnownValue();
6799 
6800   // Transform the "then" branch.
6801   StmtResult Then;
6802   if (!ConstexprConditionValue || *ConstexprConditionValue) {
6803     Then = getDerived().TransformStmt(S->getThen());
6804     if (Then.isInvalid())
6805       return StmtError();
6806   } else {
6807     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6808   }
6809 
6810   // Transform the "else" branch.
6811   StmtResult Else;
6812   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6813     Else = getDerived().TransformStmt(S->getElse());
6814     if (Else.isInvalid())
6815       return StmtError();
6816   }
6817 
6818   if (!getDerived().AlwaysRebuild() &&
6819       Init.get() == S->getInit() &&
6820       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6821       Then.get() == S->getThen() &&
6822       Else.get() == S->getElse())
6823     return S;
6824 
6825   return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6826                                     Init.get(), Then.get(), S->getElseLoc(),
6827                                     Else.get());
6828 }
6829 
6830 template<typename Derived>
6831 StmtResult
6832 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6833   // Transform the initialization statement
6834   StmtResult Init = getDerived().TransformStmt(S->getInit());
6835   if (Init.isInvalid())
6836     return StmtError();
6837 
6838   // Transform the condition.
6839   Sema::ConditionResult Cond = getDerived().TransformCondition(
6840       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6841       Sema::ConditionKind::Switch);
6842   if (Cond.isInvalid())
6843     return StmtError();
6844 
6845   // Rebuild the switch statement.
6846   StmtResult Switch
6847     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
6848   if (Switch.isInvalid())
6849     return StmtError();
6850 
6851   // Transform the body of the switch statement.
6852   StmtResult Body = getDerived().TransformStmt(S->getBody());
6853   if (Body.isInvalid())
6854     return StmtError();
6855 
6856   // Complete the switch statement.
6857   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6858                                             Body.get());
6859 }
6860 
6861 template<typename Derived>
6862 StmtResult
6863 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6864   // Transform the condition
6865   Sema::ConditionResult Cond = getDerived().TransformCondition(
6866       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6867       Sema::ConditionKind::Boolean);
6868   if (Cond.isInvalid())
6869     return StmtError();
6870 
6871   // Transform the body
6872   StmtResult Body = getDerived().TransformStmt(S->getBody());
6873   if (Body.isInvalid())
6874     return StmtError();
6875 
6876   if (!getDerived().AlwaysRebuild() &&
6877       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6878       Body.get() == S->getBody())
6879     return Owned(S);
6880 
6881   return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6882 }
6883 
6884 template<typename Derived>
6885 StmtResult
6886 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6887   // Transform the body
6888   StmtResult Body = getDerived().TransformStmt(S->getBody());
6889   if (Body.isInvalid())
6890     return StmtError();
6891 
6892   // Transform the condition
6893   ExprResult Cond = getDerived().TransformExpr(S->getCond());
6894   if (Cond.isInvalid())
6895     return StmtError();
6896 
6897   if (!getDerived().AlwaysRebuild() &&
6898       Cond.get() == S->getCond() &&
6899       Body.get() == S->getBody())
6900     return S;
6901 
6902   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6903                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
6904                                     S->getRParenLoc());
6905 }
6906 
6907 template<typename Derived>
6908 StmtResult
6909 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6910   if (getSema().getLangOpts().OpenMP)
6911     getSema().startOpenMPLoop();
6912 
6913   // Transform the initialization statement
6914   StmtResult Init = getDerived().TransformStmt(S->getInit());
6915   if (Init.isInvalid())
6916     return StmtError();
6917 
6918   // In OpenMP loop region loop control variable must be captured and be
6919   // private. Perform analysis of first part (if any).
6920   if (getSema().getLangOpts().OpenMP && Init.isUsable())
6921     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6922 
6923   // Transform the condition
6924   Sema::ConditionResult Cond = getDerived().TransformCondition(
6925       S->getForLoc(), S->getConditionVariable(), S->getCond(),
6926       Sema::ConditionKind::Boolean);
6927   if (Cond.isInvalid())
6928     return StmtError();
6929 
6930   // Transform the increment
6931   ExprResult Inc = getDerived().TransformExpr(S->getInc());
6932   if (Inc.isInvalid())
6933     return StmtError();
6934 
6935   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6936   if (S->getInc() && !FullInc.get())
6937     return StmtError();
6938 
6939   // Transform the body
6940   StmtResult Body = getDerived().TransformStmt(S->getBody());
6941   if (Body.isInvalid())
6942     return StmtError();
6943 
6944   if (!getDerived().AlwaysRebuild() &&
6945       Init.get() == S->getInit() &&
6946       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6947       Inc.get() == S->getInc() &&
6948       Body.get() == S->getBody())
6949     return S;
6950 
6951   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6952                                      Init.get(), Cond, FullInc,
6953                                      S->getRParenLoc(), Body.get());
6954 }
6955 
6956 template<typename Derived>
6957 StmtResult
6958 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6959   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6960                                         S->getLabel());
6961   if (!LD)
6962     return StmtError();
6963 
6964   // Goto statements must always be rebuilt, to resolve the label.
6965   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6966                                       cast<LabelDecl>(LD));
6967 }
6968 
6969 template<typename Derived>
6970 StmtResult
6971 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6972   ExprResult Target = getDerived().TransformExpr(S->getTarget());
6973   if (Target.isInvalid())
6974     return StmtError();
6975   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6976 
6977   if (!getDerived().AlwaysRebuild() &&
6978       Target.get() == S->getTarget())
6979     return S;
6980 
6981   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6982                                               Target.get());
6983 }
6984 
6985 template<typename Derived>
6986 StmtResult
6987 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6988   return S;
6989 }
6990 
6991 template<typename Derived>
6992 StmtResult
6993 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6994   return S;
6995 }
6996 
6997 template<typename Derived>
6998 StmtResult
6999 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7000   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7001                                                         /*NotCopyInit*/false);
7002   if (Result.isInvalid())
7003     return StmtError();
7004 
7005   // FIXME: We always rebuild the return statement because there is no way
7006   // to tell whether the return type of the function has changed.
7007   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7008 }
7009 
7010 template<typename Derived>
7011 StmtResult
7012 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7013   bool DeclChanged = false;
7014   SmallVector<Decl *, 4> Decls;
7015   for (auto *D : S->decls()) {
7016     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7017     if (!Transformed)
7018       return StmtError();
7019 
7020     if (Transformed != D)
7021       DeclChanged = true;
7022 
7023     Decls.push_back(Transformed);
7024   }
7025 
7026   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7027     return S;
7028 
7029   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7030 }
7031 
7032 template<typename Derived>
7033 StmtResult
7034 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7035 
7036   SmallVector<Expr*, 8> Constraints;
7037   SmallVector<Expr*, 8> Exprs;
7038   SmallVector<IdentifierInfo *, 4> Names;
7039 
7040   ExprResult AsmString;
7041   SmallVector<Expr*, 8> Clobbers;
7042 
7043   bool ExprsChanged = false;
7044 
7045   // Go through the outputs.
7046   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7047     Names.push_back(S->getOutputIdentifier(I));
7048 
7049     // No need to transform the constraint literal.
7050     Constraints.push_back(S->getOutputConstraintLiteral(I));
7051 
7052     // Transform the output expr.
7053     Expr *OutputExpr = S->getOutputExpr(I);
7054     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7055     if (Result.isInvalid())
7056       return StmtError();
7057 
7058     ExprsChanged |= Result.get() != OutputExpr;
7059 
7060     Exprs.push_back(Result.get());
7061   }
7062 
7063   // Go through the inputs.
7064   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7065     Names.push_back(S->getInputIdentifier(I));
7066 
7067     // No need to transform the constraint literal.
7068     Constraints.push_back(S->getInputConstraintLiteral(I));
7069 
7070     // Transform the input expr.
7071     Expr *InputExpr = S->getInputExpr(I);
7072     ExprResult Result = getDerived().TransformExpr(InputExpr);
7073     if (Result.isInvalid())
7074       return StmtError();
7075 
7076     ExprsChanged |= Result.get() != InputExpr;
7077 
7078     Exprs.push_back(Result.get());
7079   }
7080 
7081   // Go through the Labels.
7082   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7083     Names.push_back(S->getLabelIdentifier(I));
7084 
7085     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7086     if (Result.isInvalid())
7087       return StmtError();
7088     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7089     Exprs.push_back(Result.get());
7090   }
7091   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7092     return S;
7093 
7094   // Go through the clobbers.
7095   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7096     Clobbers.push_back(S->getClobberStringLiteral(I));
7097 
7098   // No need to transform the asm string literal.
7099   AsmString = S->getAsmString();
7100   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7101                                         S->isVolatile(), S->getNumOutputs(),
7102                                         S->getNumInputs(), Names.data(),
7103                                         Constraints, Exprs, AsmString.get(),
7104                                         Clobbers, S->getNumLabels(),
7105                                         S->getRParenLoc());
7106 }
7107 
7108 template<typename Derived>
7109 StmtResult
7110 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7111   ArrayRef<Token> AsmToks =
7112     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7113 
7114   bool HadError = false, HadChange = false;
7115 
7116   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7117   SmallVector<Expr*, 8> TransformedExprs;
7118   TransformedExprs.reserve(SrcExprs.size());
7119   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7120     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7121     if (!Result.isUsable()) {
7122       HadError = true;
7123     } else {
7124       HadChange |= (Result.get() != SrcExprs[i]);
7125       TransformedExprs.push_back(Result.get());
7126     }
7127   }
7128 
7129   if (HadError) return StmtError();
7130   if (!HadChange && !getDerived().AlwaysRebuild())
7131     return Owned(S);
7132 
7133   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7134                                        AsmToks, S->getAsmString(),
7135                                        S->getNumOutputs(), S->getNumInputs(),
7136                                        S->getAllConstraints(), S->getClobbers(),
7137                                        TransformedExprs, S->getEndLoc());
7138 }
7139 
7140 // C++ Coroutines TS
7141 
7142 template<typename Derived>
7143 StmtResult
7144 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7145   auto *ScopeInfo = SemaRef.getCurFunction();
7146   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7147   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7148          ScopeInfo->NeedsCoroutineSuspends &&
7149          ScopeInfo->CoroutineSuspends.first == nullptr &&
7150          ScopeInfo->CoroutineSuspends.second == nullptr &&
7151          "expected clean scope info");
7152 
7153   // Set that we have (possibly-invalid) suspend points before we do anything
7154   // that may fail.
7155   ScopeInfo->setNeedsCoroutineSuspends(false);
7156 
7157   // The new CoroutinePromise object needs to be built and put into the current
7158   // FunctionScopeInfo before any transformations or rebuilding occurs.
7159   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7160     return StmtError();
7161   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7162   if (!Promise)
7163     return StmtError();
7164   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7165   ScopeInfo->CoroutinePromise = Promise;
7166 
7167   // Transform the implicit coroutine statements we built during the initial
7168   // parse.
7169   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7170   if (InitSuspend.isInvalid())
7171     return StmtError();
7172   StmtResult FinalSuspend =
7173       getDerived().TransformStmt(S->getFinalSuspendStmt());
7174   if (FinalSuspend.isInvalid())
7175     return StmtError();
7176   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7177   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7178 
7179   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7180   if (BodyRes.isInvalid())
7181     return StmtError();
7182 
7183   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7184   if (Builder.isInvalid())
7185     return StmtError();
7186 
7187   Expr *ReturnObject = S->getReturnValueInit();
7188   assert(ReturnObject && "the return object is expected to be valid");
7189   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7190                                                      /*NoCopyInit*/ false);
7191   if (Res.isInvalid())
7192     return StmtError();
7193   Builder.ReturnValue = Res.get();
7194 
7195   if (S->hasDependentPromiseType()) {
7196     // PR41909: We may find a generic coroutine lambda definition within a
7197     // template function that is being instantiated. In this case, the lambda
7198     // will have a dependent promise type, until it is used in an expression
7199     // that creates an instantiation with a non-dependent promise type. We
7200     // should not assert or build coroutine dependent statements for such a
7201     // generic lambda.
7202     auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD);
7203     if (!MD || !MD->getParent()->isGenericLambda()) {
7204       assert(!Promise->getType()->isDependentType() &&
7205              "the promise type must no longer be dependent");
7206       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7207              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7208              "these nodes should not have been built yet");
7209       if (!Builder.buildDependentStatements())
7210         return StmtError();
7211     }
7212   } else {
7213     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7214       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7215       if (Res.isInvalid())
7216         return StmtError();
7217       Builder.OnFallthrough = Res.get();
7218     }
7219 
7220     if (auto *OnException = S->getExceptionHandler()) {
7221       StmtResult Res = getDerived().TransformStmt(OnException);
7222       if (Res.isInvalid())
7223         return StmtError();
7224       Builder.OnException = Res.get();
7225     }
7226 
7227     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7228       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7229       if (Res.isInvalid())
7230         return StmtError();
7231       Builder.ReturnStmtOnAllocFailure = Res.get();
7232     }
7233 
7234     // Transform any additional statements we may have already built
7235     assert(S->getAllocate() && S->getDeallocate() &&
7236            "allocation and deallocation calls must already be built");
7237     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7238     if (AllocRes.isInvalid())
7239       return StmtError();
7240     Builder.Allocate = AllocRes.get();
7241 
7242     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7243     if (DeallocRes.isInvalid())
7244       return StmtError();
7245     Builder.Deallocate = DeallocRes.get();
7246 
7247     assert(S->getResultDecl() && "ResultDecl must already be built");
7248     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7249     if (ResultDecl.isInvalid())
7250       return StmtError();
7251     Builder.ResultDecl = ResultDecl.get();
7252 
7253     if (auto *ReturnStmt = S->getReturnStmt()) {
7254       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7255       if (Res.isInvalid())
7256         return StmtError();
7257       Builder.ReturnStmt = Res.get();
7258     }
7259   }
7260 
7261   return getDerived().RebuildCoroutineBodyStmt(Builder);
7262 }
7263 
7264 template<typename Derived>
7265 StmtResult
7266 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7267   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7268                                                         /*NotCopyInit*/false);
7269   if (Result.isInvalid())
7270     return StmtError();
7271 
7272   // Always rebuild; we don't know if this needs to be injected into a new
7273   // context or if the promise type has changed.
7274   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7275                                           S->isImplicit());
7276 }
7277 
7278 template<typename Derived>
7279 ExprResult
7280 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7281   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7282                                                         /*NotCopyInit*/false);
7283   if (Result.isInvalid())
7284     return ExprError();
7285 
7286   // Always rebuild; we don't know if this needs to be injected into a new
7287   // context or if the promise type has changed.
7288   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7289                                          E->isImplicit());
7290 }
7291 
7292 template <typename Derived>
7293 ExprResult
7294 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7295   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7296                                                         /*NotCopyInit*/ false);
7297   if (OperandResult.isInvalid())
7298     return ExprError();
7299 
7300   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7301           E->getOperatorCoawaitLookup());
7302 
7303   if (LookupResult.isInvalid())
7304     return ExprError();
7305 
7306   // Always rebuild; we don't know if this needs to be injected into a new
7307   // context or if the promise type has changed.
7308   return getDerived().RebuildDependentCoawaitExpr(
7309       E->getKeywordLoc(), OperandResult.get(),
7310       cast<UnresolvedLookupExpr>(LookupResult.get()));
7311 }
7312 
7313 template<typename Derived>
7314 ExprResult
7315 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7316   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7317                                                         /*NotCopyInit*/false);
7318   if (Result.isInvalid())
7319     return ExprError();
7320 
7321   // Always rebuild; we don't know if this needs to be injected into a new
7322   // context or if the promise type has changed.
7323   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7324 }
7325 
7326 // Objective-C Statements.
7327 
7328 template<typename Derived>
7329 StmtResult
7330 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7331   // Transform the body of the @try.
7332   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7333   if (TryBody.isInvalid())
7334     return StmtError();
7335 
7336   // Transform the @catch statements (if present).
7337   bool AnyCatchChanged = false;
7338   SmallVector<Stmt*, 8> CatchStmts;
7339   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7340     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7341     if (Catch.isInvalid())
7342       return StmtError();
7343     if (Catch.get() != S->getCatchStmt(I))
7344       AnyCatchChanged = true;
7345     CatchStmts.push_back(Catch.get());
7346   }
7347 
7348   // Transform the @finally statement (if present).
7349   StmtResult Finally;
7350   if (S->getFinallyStmt()) {
7351     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7352     if (Finally.isInvalid())
7353       return StmtError();
7354   }
7355 
7356   // If nothing changed, just retain this statement.
7357   if (!getDerived().AlwaysRebuild() &&
7358       TryBody.get() == S->getTryBody() &&
7359       !AnyCatchChanged &&
7360       Finally.get() == S->getFinallyStmt())
7361     return S;
7362 
7363   // Build a new statement.
7364   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7365                                            CatchStmts, Finally.get());
7366 }
7367 
7368 template<typename Derived>
7369 StmtResult
7370 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7371   // Transform the @catch parameter, if there is one.
7372   VarDecl *Var = nullptr;
7373   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7374     TypeSourceInfo *TSInfo = nullptr;
7375     if (FromVar->getTypeSourceInfo()) {
7376       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7377       if (!TSInfo)
7378         return StmtError();
7379     }
7380 
7381     QualType T;
7382     if (TSInfo)
7383       T = TSInfo->getType();
7384     else {
7385       T = getDerived().TransformType(FromVar->getType());
7386       if (T.isNull())
7387         return StmtError();
7388     }
7389 
7390     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7391     if (!Var)
7392       return StmtError();
7393   }
7394 
7395   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7396   if (Body.isInvalid())
7397     return StmtError();
7398 
7399   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7400                                              S->getRParenLoc(),
7401                                              Var, Body.get());
7402 }
7403 
7404 template<typename Derived>
7405 StmtResult
7406 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7407   // Transform the body.
7408   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7409   if (Body.isInvalid())
7410     return StmtError();
7411 
7412   // If nothing changed, just retain this statement.
7413   if (!getDerived().AlwaysRebuild() &&
7414       Body.get() == S->getFinallyBody())
7415     return S;
7416 
7417   // Build a new statement.
7418   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7419                                                Body.get());
7420 }
7421 
7422 template<typename Derived>
7423 StmtResult
7424 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7425   ExprResult Operand;
7426   if (S->getThrowExpr()) {
7427     Operand = getDerived().TransformExpr(S->getThrowExpr());
7428     if (Operand.isInvalid())
7429       return StmtError();
7430   }
7431 
7432   if (!getDerived().AlwaysRebuild() &&
7433       Operand.get() == S->getThrowExpr())
7434     return S;
7435 
7436   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7437 }
7438 
7439 template<typename Derived>
7440 StmtResult
7441 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7442                                                   ObjCAtSynchronizedStmt *S) {
7443   // Transform the object we are locking.
7444   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7445   if (Object.isInvalid())
7446     return StmtError();
7447   Object =
7448     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7449                                                   Object.get());
7450   if (Object.isInvalid())
7451     return StmtError();
7452 
7453   // Transform the body.
7454   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7455   if (Body.isInvalid())
7456     return StmtError();
7457 
7458   // If nothing change, just retain the current statement.
7459   if (!getDerived().AlwaysRebuild() &&
7460       Object.get() == S->getSynchExpr() &&
7461       Body.get() == S->getSynchBody())
7462     return S;
7463 
7464   // Build a new statement.
7465   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7466                                                     Object.get(), Body.get());
7467 }
7468 
7469 template<typename Derived>
7470 StmtResult
7471 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7472                                               ObjCAutoreleasePoolStmt *S) {
7473   // Transform the body.
7474   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7475   if (Body.isInvalid())
7476     return StmtError();
7477 
7478   // If nothing changed, just retain this statement.
7479   if (!getDerived().AlwaysRebuild() &&
7480       Body.get() == S->getSubStmt())
7481     return S;
7482 
7483   // Build a new statement.
7484   return getDerived().RebuildObjCAutoreleasePoolStmt(
7485                         S->getAtLoc(), Body.get());
7486 }
7487 
7488 template<typename Derived>
7489 StmtResult
7490 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7491                                                   ObjCForCollectionStmt *S) {
7492   // Transform the element statement.
7493   StmtResult Element =
7494       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7495   if (Element.isInvalid())
7496     return StmtError();
7497 
7498   // Transform the collection expression.
7499   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7500   if (Collection.isInvalid())
7501     return StmtError();
7502 
7503   // Transform the body.
7504   StmtResult Body = getDerived().TransformStmt(S->getBody());
7505   if (Body.isInvalid())
7506     return StmtError();
7507 
7508   // If nothing changed, just retain this statement.
7509   if (!getDerived().AlwaysRebuild() &&
7510       Element.get() == S->getElement() &&
7511       Collection.get() == S->getCollection() &&
7512       Body.get() == S->getBody())
7513     return S;
7514 
7515   // Build a new statement.
7516   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7517                                                    Element.get(),
7518                                                    Collection.get(),
7519                                                    S->getRParenLoc(),
7520                                                    Body.get());
7521 }
7522 
7523 template <typename Derived>
7524 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7525   // Transform the exception declaration, if any.
7526   VarDecl *Var = nullptr;
7527   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7528     TypeSourceInfo *T =
7529         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7530     if (!T)
7531       return StmtError();
7532 
7533     Var = getDerived().RebuildExceptionDecl(
7534         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7535         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7536     if (!Var || Var->isInvalidDecl())
7537       return StmtError();
7538   }
7539 
7540   // Transform the actual exception handler.
7541   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7542   if (Handler.isInvalid())
7543     return StmtError();
7544 
7545   if (!getDerived().AlwaysRebuild() && !Var &&
7546       Handler.get() == S->getHandlerBlock())
7547     return S;
7548 
7549   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7550 }
7551 
7552 template <typename Derived>
7553 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7554   // Transform the try block itself.
7555   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7556   if (TryBlock.isInvalid())
7557     return StmtError();
7558 
7559   // Transform the handlers.
7560   bool HandlerChanged = false;
7561   SmallVector<Stmt *, 8> Handlers;
7562   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7563     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7564     if (Handler.isInvalid())
7565       return StmtError();
7566 
7567     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7568     Handlers.push_back(Handler.getAs<Stmt>());
7569   }
7570 
7571   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7572       !HandlerChanged)
7573     return S;
7574 
7575   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7576                                         Handlers);
7577 }
7578 
7579 template<typename Derived>
7580 StmtResult
7581 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7582   StmtResult Init =
7583       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7584   if (Init.isInvalid())
7585     return StmtError();
7586 
7587   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7588   if (Range.isInvalid())
7589     return StmtError();
7590 
7591   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7592   if (Begin.isInvalid())
7593     return StmtError();
7594   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7595   if (End.isInvalid())
7596     return StmtError();
7597 
7598   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7599   if (Cond.isInvalid())
7600     return StmtError();
7601   if (Cond.get())
7602     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7603   if (Cond.isInvalid())
7604     return StmtError();
7605   if (Cond.get())
7606     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7607 
7608   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7609   if (Inc.isInvalid())
7610     return StmtError();
7611   if (Inc.get())
7612     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7613 
7614   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7615   if (LoopVar.isInvalid())
7616     return StmtError();
7617 
7618   StmtResult NewStmt = S;
7619   if (getDerived().AlwaysRebuild() ||
7620       Init.get() != S->getInit() ||
7621       Range.get() != S->getRangeStmt() ||
7622       Begin.get() != S->getBeginStmt() ||
7623       End.get() != S->getEndStmt() ||
7624       Cond.get() != S->getCond() ||
7625       Inc.get() != S->getInc() ||
7626       LoopVar.get() != S->getLoopVarStmt()) {
7627     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7628                                                   S->getCoawaitLoc(), Init.get(),
7629                                                   S->getColonLoc(), Range.get(),
7630                                                   Begin.get(), End.get(),
7631                                                   Cond.get(),
7632                                                   Inc.get(), LoopVar.get(),
7633                                                   S->getRParenLoc());
7634     if (NewStmt.isInvalid())
7635       return StmtError();
7636   }
7637 
7638   StmtResult Body = getDerived().TransformStmt(S->getBody());
7639   if (Body.isInvalid())
7640     return StmtError();
7641 
7642   // Body has changed but we didn't rebuild the for-range statement. Rebuild
7643   // it now so we have a new statement to attach the body to.
7644   if (Body.get() != S->getBody() && NewStmt.get() == S) {
7645     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7646                                                   S->getCoawaitLoc(), Init.get(),
7647                                                   S->getColonLoc(), Range.get(),
7648                                                   Begin.get(), End.get(),
7649                                                   Cond.get(),
7650                                                   Inc.get(), LoopVar.get(),
7651                                                   S->getRParenLoc());
7652     if (NewStmt.isInvalid())
7653       return StmtError();
7654   }
7655 
7656   if (NewStmt.get() == S)
7657     return S;
7658 
7659   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7660 }
7661 
7662 template<typename Derived>
7663 StmtResult
7664 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7665                                                     MSDependentExistsStmt *S) {
7666   // Transform the nested-name-specifier, if any.
7667   NestedNameSpecifierLoc QualifierLoc;
7668   if (S->getQualifierLoc()) {
7669     QualifierLoc
7670       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7671     if (!QualifierLoc)
7672       return StmtError();
7673   }
7674 
7675   // Transform the declaration name.
7676   DeclarationNameInfo NameInfo = S->getNameInfo();
7677   if (NameInfo.getName()) {
7678     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7679     if (!NameInfo.getName())
7680       return StmtError();
7681   }
7682 
7683   // Check whether anything changed.
7684   if (!getDerived().AlwaysRebuild() &&
7685       QualifierLoc == S->getQualifierLoc() &&
7686       NameInfo.getName() == S->getNameInfo().getName())
7687     return S;
7688 
7689   // Determine whether this name exists, if we can.
7690   CXXScopeSpec SS;
7691   SS.Adopt(QualifierLoc);
7692   bool Dependent = false;
7693   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7694   case Sema::IER_Exists:
7695     if (S->isIfExists())
7696       break;
7697 
7698     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7699 
7700   case Sema::IER_DoesNotExist:
7701     if (S->isIfNotExists())
7702       break;
7703 
7704     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7705 
7706   case Sema::IER_Dependent:
7707     Dependent = true;
7708     break;
7709 
7710   case Sema::IER_Error:
7711     return StmtError();
7712   }
7713 
7714   // We need to continue with the instantiation, so do so now.
7715   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7716   if (SubStmt.isInvalid())
7717     return StmtError();
7718 
7719   // If we have resolved the name, just transform to the substatement.
7720   if (!Dependent)
7721     return SubStmt;
7722 
7723   // The name is still dependent, so build a dependent expression again.
7724   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7725                                                    S->isIfExists(),
7726                                                    QualifierLoc,
7727                                                    NameInfo,
7728                                                    SubStmt.get());
7729 }
7730 
7731 template<typename Derived>
7732 ExprResult
7733 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7734   NestedNameSpecifierLoc QualifierLoc;
7735   if (E->getQualifierLoc()) {
7736     QualifierLoc
7737     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7738     if (!QualifierLoc)
7739       return ExprError();
7740   }
7741 
7742   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7743     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7744   if (!PD)
7745     return ExprError();
7746 
7747   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7748   if (Base.isInvalid())
7749     return ExprError();
7750 
7751   return new (SemaRef.getASTContext())
7752       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7753                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7754                         QualifierLoc, E->getMemberLoc());
7755 }
7756 
7757 template <typename Derived>
7758 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7759     MSPropertySubscriptExpr *E) {
7760   auto BaseRes = getDerived().TransformExpr(E->getBase());
7761   if (BaseRes.isInvalid())
7762     return ExprError();
7763   auto IdxRes = getDerived().TransformExpr(E->getIdx());
7764   if (IdxRes.isInvalid())
7765     return ExprError();
7766 
7767   if (!getDerived().AlwaysRebuild() &&
7768       BaseRes.get() == E->getBase() &&
7769       IdxRes.get() == E->getIdx())
7770     return E;
7771 
7772   return getDerived().RebuildArraySubscriptExpr(
7773       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7774 }
7775 
7776 template <typename Derived>
7777 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7778   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7779   if (TryBlock.isInvalid())
7780     return StmtError();
7781 
7782   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7783   if (Handler.isInvalid())
7784     return StmtError();
7785 
7786   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7787       Handler.get() == S->getHandler())
7788     return S;
7789 
7790   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7791                                         TryBlock.get(), Handler.get());
7792 }
7793 
7794 template <typename Derived>
7795 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7796   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7797   if (Block.isInvalid())
7798     return StmtError();
7799 
7800   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7801 }
7802 
7803 template <typename Derived>
7804 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7805   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7806   if (FilterExpr.isInvalid())
7807     return StmtError();
7808 
7809   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7810   if (Block.isInvalid())
7811     return StmtError();
7812 
7813   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7814                                            Block.get());
7815 }
7816 
7817 template <typename Derived>
7818 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7819   if (isa<SEHFinallyStmt>(Handler))
7820     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7821   else
7822     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7823 }
7824 
7825 template<typename Derived>
7826 StmtResult
7827 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7828   return S;
7829 }
7830 
7831 //===----------------------------------------------------------------------===//
7832 // OpenMP directive transformation
7833 //===----------------------------------------------------------------------===//
7834 template <typename Derived>
7835 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7836     OMPExecutableDirective *D) {
7837 
7838   // Transform the clauses
7839   llvm::SmallVector<OMPClause *, 16> TClauses;
7840   ArrayRef<OMPClause *> Clauses = D->clauses();
7841   TClauses.reserve(Clauses.size());
7842   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7843        I != E; ++I) {
7844     if (*I) {
7845       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7846       OMPClause *Clause = getDerived().TransformOMPClause(*I);
7847       getDerived().getSema().EndOpenMPClause();
7848       if (Clause)
7849         TClauses.push_back(Clause);
7850     } else {
7851       TClauses.push_back(nullptr);
7852     }
7853   }
7854   StmtResult AssociatedStmt;
7855   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7856     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7857                                                   /*CurScope=*/nullptr);
7858     StmtResult Body;
7859     {
7860       Sema::CompoundScopeRAII CompoundScope(getSema());
7861       Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
7862       Body = getDerived().TransformStmt(CS);
7863     }
7864     AssociatedStmt =
7865         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7866     if (AssociatedStmt.isInvalid()) {
7867       return StmtError();
7868     }
7869   }
7870   if (TClauses.size() != Clauses.size()) {
7871     return StmtError();
7872   }
7873 
7874   // Transform directive name for 'omp critical' directive.
7875   DeclarationNameInfo DirName;
7876   if (D->getDirectiveKind() == OMPD_critical) {
7877     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7878     DirName = getDerived().TransformDeclarationNameInfo(DirName);
7879   }
7880   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7881   if (D->getDirectiveKind() == OMPD_cancellation_point) {
7882     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7883   } else if (D->getDirectiveKind() == OMPD_cancel) {
7884     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7885   }
7886 
7887   return getDerived().RebuildOMPExecutableDirective(
7888       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7889       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
7890 }
7891 
7892 template <typename Derived>
7893 StmtResult
7894 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7895   DeclarationNameInfo DirName;
7896   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7897                                              D->getBeginLoc());
7898   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7899   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7900   return Res;
7901 }
7902 
7903 template <typename Derived>
7904 StmtResult
7905 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7906   DeclarationNameInfo DirName;
7907   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7908                                              D->getBeginLoc());
7909   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7910   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7911   return Res;
7912 }
7913 
7914 template <typename Derived>
7915 StmtResult
7916 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7917   DeclarationNameInfo DirName;
7918   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7919                                              D->getBeginLoc());
7920   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7921   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7922   return Res;
7923 }
7924 
7925 template <typename Derived>
7926 StmtResult
7927 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7928   DeclarationNameInfo DirName;
7929   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7930                                              D->getBeginLoc());
7931   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7932   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7933   return Res;
7934 }
7935 
7936 template <typename Derived>
7937 StmtResult
7938 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7939   DeclarationNameInfo DirName;
7940   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7941                                              D->getBeginLoc());
7942   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7943   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7944   return Res;
7945 }
7946 
7947 template <typename Derived>
7948 StmtResult
7949 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7950   DeclarationNameInfo DirName;
7951   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7952                                              D->getBeginLoc());
7953   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7954   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7955   return Res;
7956 }
7957 
7958 template <typename Derived>
7959 StmtResult
7960 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7961   DeclarationNameInfo DirName;
7962   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7963                                              D->getBeginLoc());
7964   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7965   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7966   return Res;
7967 }
7968 
7969 template <typename Derived>
7970 StmtResult
7971 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
7972   DeclarationNameInfo DirName;
7973   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
7974                                              D->getBeginLoc());
7975   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7976   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7977   return Res;
7978 }
7979 
7980 template <typename Derived>
7981 StmtResult
7982 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
7983   getDerived().getSema().StartOpenMPDSABlock(
7984       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
7985   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7986   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7987   return Res;
7988 }
7989 
7990 template <typename Derived>
7991 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
7992     OMPParallelForDirective *D) {
7993   DeclarationNameInfo DirName;
7994   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
7995                                              nullptr, D->getBeginLoc());
7996   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7997   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7998   return Res;
7999 }
8000 
8001 template <typename Derived>
8002 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8003     OMPParallelForSimdDirective *D) {
8004   DeclarationNameInfo DirName;
8005   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8006                                              nullptr, D->getBeginLoc());
8007   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8008   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8009   return Res;
8010 }
8011 
8012 template <typename Derived>
8013 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8014     OMPParallelSectionsDirective *D) {
8015   DeclarationNameInfo DirName;
8016   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8017                                              nullptr, D->getBeginLoc());
8018   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8019   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8020   return Res;
8021 }
8022 
8023 template <typename Derived>
8024 StmtResult
8025 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8026   DeclarationNameInfo DirName;
8027   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8028                                              D->getBeginLoc());
8029   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8030   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8031   return Res;
8032 }
8033 
8034 template <typename Derived>
8035 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8036     OMPTaskyieldDirective *D) {
8037   DeclarationNameInfo DirName;
8038   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8039                                              D->getBeginLoc());
8040   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8041   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8042   return Res;
8043 }
8044 
8045 template <typename Derived>
8046 StmtResult
8047 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8048   DeclarationNameInfo DirName;
8049   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8050                                              D->getBeginLoc());
8051   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8052   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8053   return Res;
8054 }
8055 
8056 template <typename Derived>
8057 StmtResult
8058 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8059   DeclarationNameInfo DirName;
8060   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8061                                              D->getBeginLoc());
8062   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8063   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8064   return Res;
8065 }
8066 
8067 template <typename Derived>
8068 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8069     OMPTaskgroupDirective *D) {
8070   DeclarationNameInfo DirName;
8071   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8072                                              D->getBeginLoc());
8073   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8074   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8075   return Res;
8076 }
8077 
8078 template <typename Derived>
8079 StmtResult
8080 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8081   DeclarationNameInfo DirName;
8082   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8083                                              D->getBeginLoc());
8084   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8085   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8086   return Res;
8087 }
8088 
8089 template <typename Derived>
8090 StmtResult
8091 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8092   DeclarationNameInfo DirName;
8093   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8094                                              D->getBeginLoc());
8095   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8096   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8097   return Res;
8098 }
8099 
8100 template <typename Derived>
8101 StmtResult
8102 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8103   DeclarationNameInfo DirName;
8104   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8105                                              D->getBeginLoc());
8106   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8107   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8108   return Res;
8109 }
8110 
8111 template <typename Derived>
8112 StmtResult
8113 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8114   DeclarationNameInfo DirName;
8115   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8116                                              D->getBeginLoc());
8117   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8118   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8119   return Res;
8120 }
8121 
8122 template <typename Derived>
8123 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8124     OMPTargetDataDirective *D) {
8125   DeclarationNameInfo DirName;
8126   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8127                                              D->getBeginLoc());
8128   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8129   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8130   return Res;
8131 }
8132 
8133 template <typename Derived>
8134 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8135     OMPTargetEnterDataDirective *D) {
8136   DeclarationNameInfo DirName;
8137   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8138                                              nullptr, D->getBeginLoc());
8139   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8140   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8141   return Res;
8142 }
8143 
8144 template <typename Derived>
8145 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8146     OMPTargetExitDataDirective *D) {
8147   DeclarationNameInfo DirName;
8148   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8149                                              nullptr, D->getBeginLoc());
8150   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8151   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8152   return Res;
8153 }
8154 
8155 template <typename Derived>
8156 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8157     OMPTargetParallelDirective *D) {
8158   DeclarationNameInfo DirName;
8159   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8160                                              nullptr, D->getBeginLoc());
8161   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8162   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8163   return Res;
8164 }
8165 
8166 template <typename Derived>
8167 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8168     OMPTargetParallelForDirective *D) {
8169   DeclarationNameInfo DirName;
8170   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8171                                              nullptr, D->getBeginLoc());
8172   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8173   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8174   return Res;
8175 }
8176 
8177 template <typename Derived>
8178 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8179     OMPTargetUpdateDirective *D) {
8180   DeclarationNameInfo DirName;
8181   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8182                                              nullptr, D->getBeginLoc());
8183   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8184   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8185   return Res;
8186 }
8187 
8188 template <typename Derived>
8189 StmtResult
8190 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8191   DeclarationNameInfo DirName;
8192   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8193                                              D->getBeginLoc());
8194   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8195   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8196   return Res;
8197 }
8198 
8199 template <typename Derived>
8200 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8201     OMPCancellationPointDirective *D) {
8202   DeclarationNameInfo DirName;
8203   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8204                                              nullptr, D->getBeginLoc());
8205   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8206   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8207   return Res;
8208 }
8209 
8210 template <typename Derived>
8211 StmtResult
8212 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8213   DeclarationNameInfo DirName;
8214   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8215                                              D->getBeginLoc());
8216   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8217   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8218   return Res;
8219 }
8220 
8221 template <typename Derived>
8222 StmtResult
8223 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8224   DeclarationNameInfo DirName;
8225   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8226                                              D->getBeginLoc());
8227   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8228   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8229   return Res;
8230 }
8231 
8232 template <typename Derived>
8233 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8234     OMPTaskLoopSimdDirective *D) {
8235   DeclarationNameInfo DirName;
8236   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8237                                              nullptr, D->getBeginLoc());
8238   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8239   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8240   return Res;
8241 }
8242 
8243 template <typename Derived>
8244 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8245     OMPDistributeDirective *D) {
8246   DeclarationNameInfo DirName;
8247   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8248                                              D->getBeginLoc());
8249   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8250   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8251   return Res;
8252 }
8253 
8254 template <typename Derived>
8255 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8256     OMPDistributeParallelForDirective *D) {
8257   DeclarationNameInfo DirName;
8258   getDerived().getSema().StartOpenMPDSABlock(
8259       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8260   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8261   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8262   return Res;
8263 }
8264 
8265 template <typename Derived>
8266 StmtResult
8267 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8268     OMPDistributeParallelForSimdDirective *D) {
8269   DeclarationNameInfo DirName;
8270   getDerived().getSema().StartOpenMPDSABlock(
8271       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8272   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8273   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8274   return Res;
8275 }
8276 
8277 template <typename Derived>
8278 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8279     OMPDistributeSimdDirective *D) {
8280   DeclarationNameInfo DirName;
8281   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8282                                              nullptr, D->getBeginLoc());
8283   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8284   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8285   return Res;
8286 }
8287 
8288 template <typename Derived>
8289 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8290     OMPTargetParallelForSimdDirective *D) {
8291   DeclarationNameInfo DirName;
8292   getDerived().getSema().StartOpenMPDSABlock(
8293       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8294   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8295   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8296   return Res;
8297 }
8298 
8299 template <typename Derived>
8300 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8301     OMPTargetSimdDirective *D) {
8302   DeclarationNameInfo DirName;
8303   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8304                                              D->getBeginLoc());
8305   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8306   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8307   return Res;
8308 }
8309 
8310 template <typename Derived>
8311 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8312     OMPTeamsDistributeDirective *D) {
8313   DeclarationNameInfo DirName;
8314   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8315                                              nullptr, D->getBeginLoc());
8316   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8317   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8318   return Res;
8319 }
8320 
8321 template <typename Derived>
8322 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8323     OMPTeamsDistributeSimdDirective *D) {
8324   DeclarationNameInfo DirName;
8325   getDerived().getSema().StartOpenMPDSABlock(
8326       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8327   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8328   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8329   return Res;
8330 }
8331 
8332 template <typename Derived>
8333 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8334     OMPTeamsDistributeParallelForSimdDirective *D) {
8335   DeclarationNameInfo DirName;
8336   getDerived().getSema().StartOpenMPDSABlock(
8337       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8338       D->getBeginLoc());
8339   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8340   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8341   return Res;
8342 }
8343 
8344 template <typename Derived>
8345 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8346     OMPTeamsDistributeParallelForDirective *D) {
8347   DeclarationNameInfo DirName;
8348   getDerived().getSema().StartOpenMPDSABlock(
8349       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8350   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8351   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8352   return Res;
8353 }
8354 
8355 template <typename Derived>
8356 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8357     OMPTargetTeamsDirective *D) {
8358   DeclarationNameInfo DirName;
8359   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8360                                              nullptr, D->getBeginLoc());
8361   auto Res = getDerived().TransformOMPExecutableDirective(D);
8362   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8363   return Res;
8364 }
8365 
8366 template <typename Derived>
8367 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8368     OMPTargetTeamsDistributeDirective *D) {
8369   DeclarationNameInfo DirName;
8370   getDerived().getSema().StartOpenMPDSABlock(
8371       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8372   auto Res = getDerived().TransformOMPExecutableDirective(D);
8373   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8374   return Res;
8375 }
8376 
8377 template <typename Derived>
8378 StmtResult
8379 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8380     OMPTargetTeamsDistributeParallelForDirective *D) {
8381   DeclarationNameInfo DirName;
8382   getDerived().getSema().StartOpenMPDSABlock(
8383       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8384       D->getBeginLoc());
8385   auto Res = getDerived().TransformOMPExecutableDirective(D);
8386   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8387   return Res;
8388 }
8389 
8390 template <typename Derived>
8391 StmtResult TreeTransform<Derived>::
8392     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8393         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8394   DeclarationNameInfo DirName;
8395   getDerived().getSema().StartOpenMPDSABlock(
8396       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8397       D->getBeginLoc());
8398   auto Res = getDerived().TransformOMPExecutableDirective(D);
8399   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8400   return Res;
8401 }
8402 
8403 template <typename Derived>
8404 StmtResult
8405 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8406     OMPTargetTeamsDistributeSimdDirective *D) {
8407   DeclarationNameInfo DirName;
8408   getDerived().getSema().StartOpenMPDSABlock(
8409       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8410   auto Res = getDerived().TransformOMPExecutableDirective(D);
8411   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8412   return Res;
8413 }
8414 
8415 
8416 //===----------------------------------------------------------------------===//
8417 // OpenMP clause transformation
8418 //===----------------------------------------------------------------------===//
8419 template <typename Derived>
8420 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8421   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8422   if (Cond.isInvalid())
8423     return nullptr;
8424   return getDerived().RebuildOMPIfClause(
8425       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8426       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8427 }
8428 
8429 template <typename Derived>
8430 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8431   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8432   if (Cond.isInvalid())
8433     return nullptr;
8434   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8435                                             C->getLParenLoc(), C->getEndLoc());
8436 }
8437 
8438 template <typename Derived>
8439 OMPClause *
8440 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8441   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8442   if (NumThreads.isInvalid())
8443     return nullptr;
8444   return getDerived().RebuildOMPNumThreadsClause(
8445       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8446 }
8447 
8448 template <typename Derived>
8449 OMPClause *
8450 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8451   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8452   if (E.isInvalid())
8453     return nullptr;
8454   return getDerived().RebuildOMPSafelenClause(
8455       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8456 }
8457 
8458 template <typename Derived>
8459 OMPClause *
8460 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8461   ExprResult E = getDerived().TransformExpr(C->getAllocator());
8462   if (E.isInvalid())
8463     return nullptr;
8464   return getDerived().RebuildOMPAllocatorClause(
8465       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8466 }
8467 
8468 template <typename Derived>
8469 OMPClause *
8470 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8471   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8472   if (E.isInvalid())
8473     return nullptr;
8474   return getDerived().RebuildOMPSimdlenClause(
8475       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8476 }
8477 
8478 template <typename Derived>
8479 OMPClause *
8480 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8481   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8482   if (E.isInvalid())
8483     return nullptr;
8484   return getDerived().RebuildOMPCollapseClause(
8485       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8486 }
8487 
8488 template <typename Derived>
8489 OMPClause *
8490 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8491   return getDerived().RebuildOMPDefaultClause(
8492       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8493       C->getLParenLoc(), C->getEndLoc());
8494 }
8495 
8496 template <typename Derived>
8497 OMPClause *
8498 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8499   return getDerived().RebuildOMPProcBindClause(
8500       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8501       C->getLParenLoc(), C->getEndLoc());
8502 }
8503 
8504 template <typename Derived>
8505 OMPClause *
8506 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8507   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8508   if (E.isInvalid())
8509     return nullptr;
8510   return getDerived().RebuildOMPScheduleClause(
8511       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8512       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8513       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8514       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8515 }
8516 
8517 template <typename Derived>
8518 OMPClause *
8519 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8520   ExprResult E;
8521   if (auto *Num = C->getNumForLoops()) {
8522     E = getDerived().TransformExpr(Num);
8523     if (E.isInvalid())
8524       return nullptr;
8525   }
8526   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8527                                               C->getLParenLoc(), E.get());
8528 }
8529 
8530 template <typename Derived>
8531 OMPClause *
8532 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8533   // No need to rebuild this clause, no template-dependent parameters.
8534   return C;
8535 }
8536 
8537 template <typename Derived>
8538 OMPClause *
8539 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8540   // No need to rebuild this clause, no template-dependent parameters.
8541   return C;
8542 }
8543 
8544 template <typename Derived>
8545 OMPClause *
8546 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8547   // No need to rebuild this clause, no template-dependent parameters.
8548   return C;
8549 }
8550 
8551 template <typename Derived>
8552 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8553   // No need to rebuild this clause, no template-dependent parameters.
8554   return C;
8555 }
8556 
8557 template <typename Derived>
8558 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8559   // No need to rebuild this clause, no template-dependent parameters.
8560   return C;
8561 }
8562 
8563 template <typename Derived>
8564 OMPClause *
8565 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8566   // No need to rebuild this clause, no template-dependent parameters.
8567   return C;
8568 }
8569 
8570 template <typename Derived>
8571 OMPClause *
8572 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8573   // No need to rebuild this clause, no template-dependent parameters.
8574   return C;
8575 }
8576 
8577 template <typename Derived>
8578 OMPClause *
8579 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8580   // No need to rebuild this clause, no template-dependent parameters.
8581   return C;
8582 }
8583 
8584 template <typename Derived>
8585 OMPClause *
8586 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8587   // No need to rebuild this clause, no template-dependent parameters.
8588   return C;
8589 }
8590 
8591 template <typename Derived>
8592 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8593   // No need to rebuild this clause, no template-dependent parameters.
8594   return C;
8595 }
8596 
8597 template <typename Derived>
8598 OMPClause *
8599 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8600   // No need to rebuild this clause, no template-dependent parameters.
8601   return C;
8602 }
8603 
8604 template <typename Derived>
8605 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8606     OMPUnifiedAddressClause *C) {
8607   llvm_unreachable("unified_address clause cannot appear in dependent context");
8608 }
8609 
8610 template <typename Derived>
8611 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8612     OMPUnifiedSharedMemoryClause *C) {
8613   llvm_unreachable(
8614       "unified_shared_memory clause cannot appear in dependent context");
8615 }
8616 
8617 template <typename Derived>
8618 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8619     OMPReverseOffloadClause *C) {
8620   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8621 }
8622 
8623 template <typename Derived>
8624 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8625     OMPDynamicAllocatorsClause *C) {
8626   llvm_unreachable(
8627       "dynamic_allocators clause cannot appear in dependent context");
8628 }
8629 
8630 template <typename Derived>
8631 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8632     OMPAtomicDefaultMemOrderClause *C) {
8633   llvm_unreachable(
8634       "atomic_default_mem_order clause cannot appear in dependent context");
8635 }
8636 
8637 template <typename Derived>
8638 OMPClause *
8639 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8640   llvm::SmallVector<Expr *, 16> Vars;
8641   Vars.reserve(C->varlist_size());
8642   for (auto *VE : C->varlists()) {
8643     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8644     if (EVar.isInvalid())
8645       return nullptr;
8646     Vars.push_back(EVar.get());
8647   }
8648   return getDerived().RebuildOMPPrivateClause(
8649       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8650 }
8651 
8652 template <typename Derived>
8653 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8654     OMPFirstprivateClause *C) {
8655   llvm::SmallVector<Expr *, 16> Vars;
8656   Vars.reserve(C->varlist_size());
8657   for (auto *VE : C->varlists()) {
8658     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8659     if (EVar.isInvalid())
8660       return nullptr;
8661     Vars.push_back(EVar.get());
8662   }
8663   return getDerived().RebuildOMPFirstprivateClause(
8664       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8665 }
8666 
8667 template <typename Derived>
8668 OMPClause *
8669 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8670   llvm::SmallVector<Expr *, 16> Vars;
8671   Vars.reserve(C->varlist_size());
8672   for (auto *VE : C->varlists()) {
8673     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8674     if (EVar.isInvalid())
8675       return nullptr;
8676     Vars.push_back(EVar.get());
8677   }
8678   return getDerived().RebuildOMPLastprivateClause(
8679       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8680 }
8681 
8682 template <typename Derived>
8683 OMPClause *
8684 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8685   llvm::SmallVector<Expr *, 16> Vars;
8686   Vars.reserve(C->varlist_size());
8687   for (auto *VE : C->varlists()) {
8688     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8689     if (EVar.isInvalid())
8690       return nullptr;
8691     Vars.push_back(EVar.get());
8692   }
8693   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8694                                              C->getLParenLoc(), C->getEndLoc());
8695 }
8696 
8697 template <typename Derived>
8698 OMPClause *
8699 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8700   llvm::SmallVector<Expr *, 16> Vars;
8701   Vars.reserve(C->varlist_size());
8702   for (auto *VE : C->varlists()) {
8703     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8704     if (EVar.isInvalid())
8705       return nullptr;
8706     Vars.push_back(EVar.get());
8707   }
8708   CXXScopeSpec ReductionIdScopeSpec;
8709   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8710 
8711   DeclarationNameInfo NameInfo = C->getNameInfo();
8712   if (NameInfo.getName()) {
8713     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8714     if (!NameInfo.getName())
8715       return nullptr;
8716   }
8717   // Build a list of all UDR decls with the same names ranged by the Scopes.
8718   // The Scope boundary is a duplication of the previous decl.
8719   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8720   for (auto *E : C->reduction_ops()) {
8721     // Transform all the decls.
8722     if (E) {
8723       auto *ULE = cast<UnresolvedLookupExpr>(E);
8724       UnresolvedSet<8> Decls;
8725       for (auto *D : ULE->decls()) {
8726         NamedDecl *InstD =
8727             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8728         Decls.addDecl(InstD, InstD->getAccess());
8729       }
8730       UnresolvedReductions.push_back(
8731        UnresolvedLookupExpr::Create(
8732           SemaRef.Context, /*NamingClass=*/nullptr,
8733           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8734           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8735           Decls.begin(), Decls.end()));
8736     } else
8737       UnresolvedReductions.push_back(nullptr);
8738   }
8739   return getDerived().RebuildOMPReductionClause(
8740       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8741       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8742 }
8743 
8744 template <typename Derived>
8745 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8746     OMPTaskReductionClause *C) {
8747   llvm::SmallVector<Expr *, 16> Vars;
8748   Vars.reserve(C->varlist_size());
8749   for (auto *VE : C->varlists()) {
8750     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8751     if (EVar.isInvalid())
8752       return nullptr;
8753     Vars.push_back(EVar.get());
8754   }
8755   CXXScopeSpec ReductionIdScopeSpec;
8756   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8757 
8758   DeclarationNameInfo NameInfo = C->getNameInfo();
8759   if (NameInfo.getName()) {
8760     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8761     if (!NameInfo.getName())
8762       return nullptr;
8763   }
8764   // Build a list of all UDR decls with the same names ranged by the Scopes.
8765   // The Scope boundary is a duplication of the previous decl.
8766   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8767   for (auto *E : C->reduction_ops()) {
8768     // Transform all the decls.
8769     if (E) {
8770       auto *ULE = cast<UnresolvedLookupExpr>(E);
8771       UnresolvedSet<8> Decls;
8772       for (auto *D : ULE->decls()) {
8773         NamedDecl *InstD =
8774             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8775         Decls.addDecl(InstD, InstD->getAccess());
8776       }
8777       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8778           SemaRef.Context, /*NamingClass=*/nullptr,
8779           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8780           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8781     } else
8782       UnresolvedReductions.push_back(nullptr);
8783   }
8784   return getDerived().RebuildOMPTaskReductionClause(
8785       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8786       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8787 }
8788 
8789 template <typename Derived>
8790 OMPClause *
8791 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8792   llvm::SmallVector<Expr *, 16> Vars;
8793   Vars.reserve(C->varlist_size());
8794   for (auto *VE : C->varlists()) {
8795     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8796     if (EVar.isInvalid())
8797       return nullptr;
8798     Vars.push_back(EVar.get());
8799   }
8800   CXXScopeSpec ReductionIdScopeSpec;
8801   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8802 
8803   DeclarationNameInfo NameInfo = C->getNameInfo();
8804   if (NameInfo.getName()) {
8805     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8806     if (!NameInfo.getName())
8807       return nullptr;
8808   }
8809   // Build a list of all UDR decls with the same names ranged by the Scopes.
8810   // The Scope boundary is a duplication of the previous decl.
8811   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8812   for (auto *E : C->reduction_ops()) {
8813     // Transform all the decls.
8814     if (E) {
8815       auto *ULE = cast<UnresolvedLookupExpr>(E);
8816       UnresolvedSet<8> Decls;
8817       for (auto *D : ULE->decls()) {
8818         NamedDecl *InstD =
8819             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8820         Decls.addDecl(InstD, InstD->getAccess());
8821       }
8822       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8823           SemaRef.Context, /*NamingClass=*/nullptr,
8824           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8825           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8826     } else
8827       UnresolvedReductions.push_back(nullptr);
8828   }
8829   return getDerived().RebuildOMPInReductionClause(
8830       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8831       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8832 }
8833 
8834 template <typename Derived>
8835 OMPClause *
8836 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8837   llvm::SmallVector<Expr *, 16> Vars;
8838   Vars.reserve(C->varlist_size());
8839   for (auto *VE : C->varlists()) {
8840     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8841     if (EVar.isInvalid())
8842       return nullptr;
8843     Vars.push_back(EVar.get());
8844   }
8845   ExprResult Step = getDerived().TransformExpr(C->getStep());
8846   if (Step.isInvalid())
8847     return nullptr;
8848   return getDerived().RebuildOMPLinearClause(
8849       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8850       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8851 }
8852 
8853 template <typename Derived>
8854 OMPClause *
8855 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8856   llvm::SmallVector<Expr *, 16> Vars;
8857   Vars.reserve(C->varlist_size());
8858   for (auto *VE : C->varlists()) {
8859     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8860     if (EVar.isInvalid())
8861       return nullptr;
8862     Vars.push_back(EVar.get());
8863   }
8864   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8865   if (Alignment.isInvalid())
8866     return nullptr;
8867   return getDerived().RebuildOMPAlignedClause(
8868       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8869       C->getColonLoc(), C->getEndLoc());
8870 }
8871 
8872 template <typename Derived>
8873 OMPClause *
8874 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8875   llvm::SmallVector<Expr *, 16> Vars;
8876   Vars.reserve(C->varlist_size());
8877   for (auto *VE : C->varlists()) {
8878     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8879     if (EVar.isInvalid())
8880       return nullptr;
8881     Vars.push_back(EVar.get());
8882   }
8883   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8884                                              C->getLParenLoc(), C->getEndLoc());
8885 }
8886 
8887 template <typename Derived>
8888 OMPClause *
8889 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8890   llvm::SmallVector<Expr *, 16> Vars;
8891   Vars.reserve(C->varlist_size());
8892   for (auto *VE : C->varlists()) {
8893     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8894     if (EVar.isInvalid())
8895       return nullptr;
8896     Vars.push_back(EVar.get());
8897   }
8898   return getDerived().RebuildOMPCopyprivateClause(
8899       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8900 }
8901 
8902 template <typename Derived>
8903 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8904   llvm::SmallVector<Expr *, 16> Vars;
8905   Vars.reserve(C->varlist_size());
8906   for (auto *VE : C->varlists()) {
8907     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8908     if (EVar.isInvalid())
8909       return nullptr;
8910     Vars.push_back(EVar.get());
8911   }
8912   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
8913                                             C->getLParenLoc(), C->getEndLoc());
8914 }
8915 
8916 template <typename Derived>
8917 OMPClause *
8918 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8919   llvm::SmallVector<Expr *, 16> Vars;
8920   Vars.reserve(C->varlist_size());
8921   for (auto *VE : C->varlists()) {
8922     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8923     if (EVar.isInvalid())
8924       return nullptr;
8925     Vars.push_back(EVar.get());
8926   }
8927   return getDerived().RebuildOMPDependClause(
8928       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8929       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8930 }
8931 
8932 template <typename Derived>
8933 OMPClause *
8934 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
8935   ExprResult E = getDerived().TransformExpr(C->getDevice());
8936   if (E.isInvalid())
8937     return nullptr;
8938   return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
8939                                              C->getLParenLoc(), C->getEndLoc());
8940 }
8941 
8942 template <typename Derived, class T>
8943 bool transformOMPMappableExprListClause(
8944     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
8945     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
8946     DeclarationNameInfo &MapperIdInfo,
8947     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
8948   // Transform expressions in the list.
8949   Vars.reserve(C->varlist_size());
8950   for (auto *VE : C->varlists()) {
8951     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
8952     if (EVar.isInvalid())
8953       return true;
8954     Vars.push_back(EVar.get());
8955   }
8956   // Transform mapper scope specifier and identifier.
8957   NestedNameSpecifierLoc QualifierLoc;
8958   if (C->getMapperQualifierLoc()) {
8959     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
8960         C->getMapperQualifierLoc());
8961     if (!QualifierLoc)
8962       return true;
8963   }
8964   MapperIdScopeSpec.Adopt(QualifierLoc);
8965   MapperIdInfo = C->getMapperIdInfo();
8966   if (MapperIdInfo.getName()) {
8967     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
8968     if (!MapperIdInfo.getName())
8969       return true;
8970   }
8971   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
8972   // the previous user-defined mapper lookup in dependent environment.
8973   for (auto *E : C->mapperlists()) {
8974     // Transform all the decls.
8975     if (E) {
8976       auto *ULE = cast<UnresolvedLookupExpr>(E);
8977       UnresolvedSet<8> Decls;
8978       for (auto *D : ULE->decls()) {
8979         NamedDecl *InstD =
8980             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
8981         Decls.addDecl(InstD, InstD->getAccess());
8982       }
8983       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
8984           TT.getSema().Context, /*NamingClass=*/nullptr,
8985           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
8986           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
8987           Decls.end()));
8988     } else {
8989       UnresolvedMappers.push_back(nullptr);
8990     }
8991   }
8992   return false;
8993 }
8994 
8995 template <typename Derived>
8996 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
8997   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8998   llvm::SmallVector<Expr *, 16> Vars;
8999   CXXScopeSpec MapperIdScopeSpec;
9000   DeclarationNameInfo MapperIdInfo;
9001   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9002   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9003           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9004     return nullptr;
9005   return getDerived().RebuildOMPMapClause(
9006       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9007       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9008       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9009 }
9010 
9011 template <typename Derived>
9012 OMPClause *
9013 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9014   Expr *Allocator = C->getAllocator();
9015   if (Allocator) {
9016     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9017     if (AllocatorRes.isInvalid())
9018       return nullptr;
9019     Allocator = AllocatorRes.get();
9020   }
9021   llvm::SmallVector<Expr *, 16> Vars;
9022   Vars.reserve(C->varlist_size());
9023   for (auto *VE : C->varlists()) {
9024     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9025     if (EVar.isInvalid())
9026       return nullptr;
9027     Vars.push_back(EVar.get());
9028   }
9029   return getDerived().RebuildOMPAllocateClause(
9030       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9031       C->getEndLoc());
9032 }
9033 
9034 template <typename Derived>
9035 OMPClause *
9036 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9037   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9038   if (E.isInvalid())
9039     return nullptr;
9040   return getDerived().RebuildOMPNumTeamsClause(
9041       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9042 }
9043 
9044 template <typename Derived>
9045 OMPClause *
9046 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9047   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9048   if (E.isInvalid())
9049     return nullptr;
9050   return getDerived().RebuildOMPThreadLimitClause(
9051       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9052 }
9053 
9054 template <typename Derived>
9055 OMPClause *
9056 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9057   ExprResult E = getDerived().TransformExpr(C->getPriority());
9058   if (E.isInvalid())
9059     return nullptr;
9060   return getDerived().RebuildOMPPriorityClause(
9061       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9062 }
9063 
9064 template <typename Derived>
9065 OMPClause *
9066 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9067   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9068   if (E.isInvalid())
9069     return nullptr;
9070   return getDerived().RebuildOMPGrainsizeClause(
9071       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9072 }
9073 
9074 template <typename Derived>
9075 OMPClause *
9076 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9077   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9078   if (E.isInvalid())
9079     return nullptr;
9080   return getDerived().RebuildOMPNumTasksClause(
9081       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9082 }
9083 
9084 template <typename Derived>
9085 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9086   ExprResult E = getDerived().TransformExpr(C->getHint());
9087   if (E.isInvalid())
9088     return nullptr;
9089   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9090                                            C->getLParenLoc(), C->getEndLoc());
9091 }
9092 
9093 template <typename Derived>
9094 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9095     OMPDistScheduleClause *C) {
9096   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9097   if (E.isInvalid())
9098     return nullptr;
9099   return getDerived().RebuildOMPDistScheduleClause(
9100       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9101       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9102 }
9103 
9104 template <typename Derived>
9105 OMPClause *
9106 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9107   return C;
9108 }
9109 
9110 template <typename Derived>
9111 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9112   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9113   llvm::SmallVector<Expr *, 16> Vars;
9114   CXXScopeSpec MapperIdScopeSpec;
9115   DeclarationNameInfo MapperIdInfo;
9116   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9117   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9118           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9119     return nullptr;
9120   return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9121                                          Locs, UnresolvedMappers);
9122 }
9123 
9124 template <typename Derived>
9125 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9126   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9127   llvm::SmallVector<Expr *, 16> Vars;
9128   CXXScopeSpec MapperIdScopeSpec;
9129   DeclarationNameInfo MapperIdInfo;
9130   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9131   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9132           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9133     return nullptr;
9134   return getDerived().RebuildOMPFromClause(
9135       Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9136 }
9137 
9138 template <typename Derived>
9139 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9140     OMPUseDevicePtrClause *C) {
9141   llvm::SmallVector<Expr *, 16> Vars;
9142   Vars.reserve(C->varlist_size());
9143   for (auto *VE : C->varlists()) {
9144     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9145     if (EVar.isInvalid())
9146       return nullptr;
9147     Vars.push_back(EVar.get());
9148   }
9149   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9150   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9151 }
9152 
9153 template <typename Derived>
9154 OMPClause *
9155 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9156   llvm::SmallVector<Expr *, 16> Vars;
9157   Vars.reserve(C->varlist_size());
9158   for (auto *VE : C->varlists()) {
9159     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9160     if (EVar.isInvalid())
9161       return nullptr;
9162     Vars.push_back(EVar.get());
9163   }
9164   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9165   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9166 }
9167 
9168 //===----------------------------------------------------------------------===//
9169 // Expression transformation
9170 //===----------------------------------------------------------------------===//
9171 template<typename Derived>
9172 ExprResult
9173 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9174   return TransformExpr(E->getSubExpr());
9175 }
9176 
9177 template<typename Derived>
9178 ExprResult
9179 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9180   if (!E->isTypeDependent())
9181     return E;
9182 
9183   return getDerived().RebuildPredefinedExpr(E->getLocation(),
9184                                             E->getIdentKind());
9185 }
9186 
9187 template<typename Derived>
9188 ExprResult
9189 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9190   NestedNameSpecifierLoc QualifierLoc;
9191   if (E->getQualifierLoc()) {
9192     QualifierLoc
9193       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9194     if (!QualifierLoc)
9195       return ExprError();
9196   }
9197 
9198   ValueDecl *ND
9199     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9200                                                          E->getDecl()));
9201   if (!ND)
9202     return ExprError();
9203 
9204   NamedDecl *Found = ND;
9205   if (E->getFoundDecl() != E->getDecl()) {
9206     Found = cast_or_null<NamedDecl>(
9207         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9208     if (!Found)
9209       return ExprError();
9210   }
9211 
9212   DeclarationNameInfo NameInfo = E->getNameInfo();
9213   if (NameInfo.getName()) {
9214     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9215     if (!NameInfo.getName())
9216       return ExprError();
9217   }
9218 
9219   if (!getDerived().AlwaysRebuild() &&
9220       QualifierLoc == E->getQualifierLoc() &&
9221       ND == E->getDecl() &&
9222       Found == E->getFoundDecl() &&
9223       NameInfo.getName() == E->getDecl()->getDeclName() &&
9224       !E->hasExplicitTemplateArgs()) {
9225 
9226     // Mark it referenced in the new context regardless.
9227     // FIXME: this is a bit instantiation-specific.
9228     SemaRef.MarkDeclRefReferenced(E);
9229 
9230     return E;
9231   }
9232 
9233   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9234   if (E->hasExplicitTemplateArgs()) {
9235     TemplateArgs = &TransArgs;
9236     TransArgs.setLAngleLoc(E->getLAngleLoc());
9237     TransArgs.setRAngleLoc(E->getRAngleLoc());
9238     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9239                                                 E->getNumTemplateArgs(),
9240                                                 TransArgs))
9241       return ExprError();
9242   }
9243 
9244   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9245                                          Found, TemplateArgs);
9246 }
9247 
9248 template<typename Derived>
9249 ExprResult
9250 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9251   return E;
9252 }
9253 
9254 template <typename Derived>
9255 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9256     FixedPointLiteral *E) {
9257   return E;
9258 }
9259 
9260 template<typename Derived>
9261 ExprResult
9262 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9263   return E;
9264 }
9265 
9266 template<typename Derived>
9267 ExprResult
9268 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9269   return E;
9270 }
9271 
9272 template<typename Derived>
9273 ExprResult
9274 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9275   return E;
9276 }
9277 
9278 template<typename Derived>
9279 ExprResult
9280 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9281   return E;
9282 }
9283 
9284 template<typename Derived>
9285 ExprResult
9286 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9287   if (FunctionDecl *FD = E->getDirectCallee())
9288     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9289   return SemaRef.MaybeBindToTemporary(E);
9290 }
9291 
9292 template<typename Derived>
9293 ExprResult
9294 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9295   ExprResult ControllingExpr =
9296     getDerived().TransformExpr(E->getControllingExpr());
9297   if (ControllingExpr.isInvalid())
9298     return ExprError();
9299 
9300   SmallVector<Expr *, 4> AssocExprs;
9301   SmallVector<TypeSourceInfo *, 4> AssocTypes;
9302   for (const GenericSelectionExpr::Association &Assoc : E->associations()) {
9303     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9304     if (TSI) {
9305       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9306       if (!AssocType)
9307         return ExprError();
9308       AssocTypes.push_back(AssocType);
9309     } else {
9310       AssocTypes.push_back(nullptr);
9311     }
9312 
9313     ExprResult AssocExpr =
9314         getDerived().TransformExpr(Assoc.getAssociationExpr());
9315     if (AssocExpr.isInvalid())
9316       return ExprError();
9317     AssocExprs.push_back(AssocExpr.get());
9318   }
9319 
9320   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9321                                                   E->getDefaultLoc(),
9322                                                   E->getRParenLoc(),
9323                                                   ControllingExpr.get(),
9324                                                   AssocTypes,
9325                                                   AssocExprs);
9326 }
9327 
9328 template<typename Derived>
9329 ExprResult
9330 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9331   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9332   if (SubExpr.isInvalid())
9333     return ExprError();
9334 
9335   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9336     return E;
9337 
9338   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9339                                        E->getRParen());
9340 }
9341 
9342 /// The operand of a unary address-of operator has special rules: it's
9343 /// allowed to refer to a non-static member of a class even if there's no 'this'
9344 /// object available.
9345 template<typename Derived>
9346 ExprResult
9347 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9348   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9349     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9350   else
9351     return getDerived().TransformExpr(E);
9352 }
9353 
9354 template<typename Derived>
9355 ExprResult
9356 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9357   ExprResult SubExpr;
9358   if (E->getOpcode() == UO_AddrOf)
9359     SubExpr = TransformAddressOfOperand(E->getSubExpr());
9360   else
9361     SubExpr = TransformExpr(E->getSubExpr());
9362   if (SubExpr.isInvalid())
9363     return ExprError();
9364 
9365   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9366     return E;
9367 
9368   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9369                                            E->getOpcode(),
9370                                            SubExpr.get());
9371 }
9372 
9373 template<typename Derived>
9374 ExprResult
9375 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9376   // Transform the type.
9377   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9378   if (!Type)
9379     return ExprError();
9380 
9381   // Transform all of the components into components similar to what the
9382   // parser uses.
9383   // FIXME: It would be slightly more efficient in the non-dependent case to
9384   // just map FieldDecls, rather than requiring the rebuilder to look for
9385   // the fields again. However, __builtin_offsetof is rare enough in
9386   // template code that we don't care.
9387   bool ExprChanged = false;
9388   typedef Sema::OffsetOfComponent Component;
9389   SmallVector<Component, 4> Components;
9390   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9391     const OffsetOfNode &ON = E->getComponent(I);
9392     Component Comp;
9393     Comp.isBrackets = true;
9394     Comp.LocStart = ON.getSourceRange().getBegin();
9395     Comp.LocEnd = ON.getSourceRange().getEnd();
9396     switch (ON.getKind()) {
9397     case OffsetOfNode::Array: {
9398       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9399       ExprResult Index = getDerived().TransformExpr(FromIndex);
9400       if (Index.isInvalid())
9401         return ExprError();
9402 
9403       ExprChanged = ExprChanged || Index.get() != FromIndex;
9404       Comp.isBrackets = true;
9405       Comp.U.E = Index.get();
9406       break;
9407     }
9408 
9409     case OffsetOfNode::Field:
9410     case OffsetOfNode::Identifier:
9411       Comp.isBrackets = false;
9412       Comp.U.IdentInfo = ON.getFieldName();
9413       if (!Comp.U.IdentInfo)
9414         continue;
9415 
9416       break;
9417 
9418     case OffsetOfNode::Base:
9419       // Will be recomputed during the rebuild.
9420       continue;
9421     }
9422 
9423     Components.push_back(Comp);
9424   }
9425 
9426   // If nothing changed, retain the existing expression.
9427   if (!getDerived().AlwaysRebuild() &&
9428       Type == E->getTypeSourceInfo() &&
9429       !ExprChanged)
9430     return E;
9431 
9432   // Build a new offsetof expression.
9433   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9434                                           Components, E->getRParenLoc());
9435 }
9436 
9437 template<typename Derived>
9438 ExprResult
9439 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9440   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9441          "opaque value expression requires transformation");
9442   return E;
9443 }
9444 
9445 template<typename Derived>
9446 ExprResult
9447 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9448   return E;
9449 }
9450 
9451 template<typename Derived>
9452 ExprResult
9453 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9454   // Rebuild the syntactic form.  The original syntactic form has
9455   // opaque-value expressions in it, so strip those away and rebuild
9456   // the result.  This is a really awful way of doing this, but the
9457   // better solution (rebuilding the semantic expressions and
9458   // rebinding OVEs as necessary) doesn't work; we'd need
9459   // TreeTransform to not strip away implicit conversions.
9460   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9461   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9462   if (result.isInvalid()) return ExprError();
9463 
9464   // If that gives us a pseudo-object result back, the pseudo-object
9465   // expression must have been an lvalue-to-rvalue conversion which we
9466   // should reapply.
9467   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9468     result = SemaRef.checkPseudoObjectRValue(result.get());
9469 
9470   return result;
9471 }
9472 
9473 template<typename Derived>
9474 ExprResult
9475 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9476                                                 UnaryExprOrTypeTraitExpr *E) {
9477   if (E->isArgumentType()) {
9478     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9479 
9480     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9481     if (!NewT)
9482       return ExprError();
9483 
9484     if (!getDerived().AlwaysRebuild() && OldT == NewT)
9485       return E;
9486 
9487     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9488                                                     E->getKind(),
9489                                                     E->getSourceRange());
9490   }
9491 
9492   // C++0x [expr.sizeof]p1:
9493   //   The operand is either an expression, which is an unevaluated operand
9494   //   [...]
9495   EnterExpressionEvaluationContext Unevaluated(
9496       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9497       Sema::ReuseLambdaContextDecl);
9498 
9499   // Try to recover if we have something like sizeof(T::X) where X is a type.
9500   // Notably, there must be *exactly* one set of parens if X is a type.
9501   TypeSourceInfo *RecoveryTSI = nullptr;
9502   ExprResult SubExpr;
9503   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9504   if (auto *DRE =
9505           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9506     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9507         PE, DRE, false, &RecoveryTSI);
9508   else
9509     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9510 
9511   if (RecoveryTSI) {
9512     return getDerived().RebuildUnaryExprOrTypeTrait(
9513         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9514   } else if (SubExpr.isInvalid())
9515     return ExprError();
9516 
9517   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9518     return E;
9519 
9520   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9521                                                   E->getOperatorLoc(),
9522                                                   E->getKind(),
9523                                                   E->getSourceRange());
9524 }
9525 
9526 template<typename Derived>
9527 ExprResult
9528 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9529   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9530   if (LHS.isInvalid())
9531     return ExprError();
9532 
9533   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9534   if (RHS.isInvalid())
9535     return ExprError();
9536 
9537 
9538   if (!getDerived().AlwaysRebuild() &&
9539       LHS.get() == E->getLHS() &&
9540       RHS.get() == E->getRHS())
9541     return E;
9542 
9543   return getDerived().RebuildArraySubscriptExpr(
9544       LHS.get(),
9545       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9546 }
9547 
9548 template <typename Derived>
9549 ExprResult
9550 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9551   ExprResult Base = getDerived().TransformExpr(E->getBase());
9552   if (Base.isInvalid())
9553     return ExprError();
9554 
9555   ExprResult LowerBound;
9556   if (E->getLowerBound()) {
9557     LowerBound = getDerived().TransformExpr(E->getLowerBound());
9558     if (LowerBound.isInvalid())
9559       return ExprError();
9560   }
9561 
9562   ExprResult Length;
9563   if (E->getLength()) {
9564     Length = getDerived().TransformExpr(E->getLength());
9565     if (Length.isInvalid())
9566       return ExprError();
9567   }
9568 
9569   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9570       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9571     return E;
9572 
9573   return getDerived().RebuildOMPArraySectionExpr(
9574       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9575       Length.get(), E->getRBracketLoc());
9576 }
9577 
9578 template<typename Derived>
9579 ExprResult
9580 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9581   // Transform the callee.
9582   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9583   if (Callee.isInvalid())
9584     return ExprError();
9585 
9586   // Transform arguments.
9587   bool ArgChanged = false;
9588   SmallVector<Expr*, 8> Args;
9589   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9590                                   &ArgChanged))
9591     return ExprError();
9592 
9593   if (!getDerived().AlwaysRebuild() &&
9594       Callee.get() == E->getCallee() &&
9595       !ArgChanged)
9596     return SemaRef.MaybeBindToTemporary(E);
9597 
9598   // FIXME: Wrong source location information for the '('.
9599   SourceLocation FakeLParenLoc
9600     = ((Expr *)Callee.get())->getSourceRange().getBegin();
9601   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9602                                       Args,
9603                                       E->getRParenLoc());
9604 }
9605 
9606 template<typename Derived>
9607 ExprResult
9608 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9609   ExprResult Base = getDerived().TransformExpr(E->getBase());
9610   if (Base.isInvalid())
9611     return ExprError();
9612 
9613   NestedNameSpecifierLoc QualifierLoc;
9614   if (E->hasQualifier()) {
9615     QualifierLoc
9616       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9617 
9618     if (!QualifierLoc)
9619       return ExprError();
9620   }
9621   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9622 
9623   ValueDecl *Member
9624     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9625                                                          E->getMemberDecl()));
9626   if (!Member)
9627     return ExprError();
9628 
9629   NamedDecl *FoundDecl = E->getFoundDecl();
9630   if (FoundDecl == E->getMemberDecl()) {
9631     FoundDecl = Member;
9632   } else {
9633     FoundDecl = cast_or_null<NamedDecl>(
9634                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9635     if (!FoundDecl)
9636       return ExprError();
9637   }
9638 
9639   if (!getDerived().AlwaysRebuild() &&
9640       Base.get() == E->getBase() &&
9641       QualifierLoc == E->getQualifierLoc() &&
9642       Member == E->getMemberDecl() &&
9643       FoundDecl == E->getFoundDecl() &&
9644       !E->hasExplicitTemplateArgs()) {
9645 
9646     // Mark it referenced in the new context regardless.
9647     // FIXME: this is a bit instantiation-specific.
9648     SemaRef.MarkMemberReferenced(E);
9649 
9650     return E;
9651   }
9652 
9653   TemplateArgumentListInfo TransArgs;
9654   if (E->hasExplicitTemplateArgs()) {
9655     TransArgs.setLAngleLoc(E->getLAngleLoc());
9656     TransArgs.setRAngleLoc(E->getRAngleLoc());
9657     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9658                                                 E->getNumTemplateArgs(),
9659                                                 TransArgs))
9660       return ExprError();
9661   }
9662 
9663   // FIXME: Bogus source location for the operator
9664   SourceLocation FakeOperatorLoc =
9665       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9666 
9667   // FIXME: to do this check properly, we will need to preserve the
9668   // first-qualifier-in-scope here, just in case we had a dependent
9669   // base (and therefore couldn't do the check) and a
9670   // nested-name-qualifier (and therefore could do the lookup).
9671   NamedDecl *FirstQualifierInScope = nullptr;
9672   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9673   if (MemberNameInfo.getName()) {
9674     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9675     if (!MemberNameInfo.getName())
9676       return ExprError();
9677   }
9678 
9679   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9680                                         E->isArrow(),
9681                                         QualifierLoc,
9682                                         TemplateKWLoc,
9683                                         MemberNameInfo,
9684                                         Member,
9685                                         FoundDecl,
9686                                         (E->hasExplicitTemplateArgs()
9687                                            ? &TransArgs : nullptr),
9688                                         FirstQualifierInScope);
9689 }
9690 
9691 template<typename Derived>
9692 ExprResult
9693 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9694   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9695   if (LHS.isInvalid())
9696     return ExprError();
9697 
9698   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9699   if (RHS.isInvalid())
9700     return ExprError();
9701 
9702   if (!getDerived().AlwaysRebuild() &&
9703       LHS.get() == E->getLHS() &&
9704       RHS.get() == E->getRHS())
9705     return E;
9706 
9707   Sema::FPContractStateRAII FPContractState(getSema());
9708   getSema().FPFeatures = E->getFPFeatures();
9709 
9710   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9711                                             LHS.get(), RHS.get());
9712 }
9713 
9714 template<typename Derived>
9715 ExprResult
9716 TreeTransform<Derived>::TransformCompoundAssignOperator(
9717                                                       CompoundAssignOperator *E) {
9718   return getDerived().TransformBinaryOperator(E);
9719 }
9720 
9721 template<typename Derived>
9722 ExprResult TreeTransform<Derived>::
9723 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9724   // Just rebuild the common and RHS expressions and see whether we
9725   // get any changes.
9726 
9727   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9728   if (commonExpr.isInvalid())
9729     return ExprError();
9730 
9731   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9732   if (rhs.isInvalid())
9733     return ExprError();
9734 
9735   if (!getDerived().AlwaysRebuild() &&
9736       commonExpr.get() == e->getCommon() &&
9737       rhs.get() == e->getFalseExpr())
9738     return e;
9739 
9740   return getDerived().RebuildConditionalOperator(commonExpr.get(),
9741                                                  e->getQuestionLoc(),
9742                                                  nullptr,
9743                                                  e->getColonLoc(),
9744                                                  rhs.get());
9745 }
9746 
9747 template<typename Derived>
9748 ExprResult
9749 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9750   ExprResult Cond = getDerived().TransformExpr(E->getCond());
9751   if (Cond.isInvalid())
9752     return ExprError();
9753 
9754   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9755   if (LHS.isInvalid())
9756     return ExprError();
9757 
9758   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9759   if (RHS.isInvalid())
9760     return ExprError();
9761 
9762   if (!getDerived().AlwaysRebuild() &&
9763       Cond.get() == E->getCond() &&
9764       LHS.get() == E->getLHS() &&
9765       RHS.get() == E->getRHS())
9766     return E;
9767 
9768   return getDerived().RebuildConditionalOperator(Cond.get(),
9769                                                  E->getQuestionLoc(),
9770                                                  LHS.get(),
9771                                                  E->getColonLoc(),
9772                                                  RHS.get());
9773 }
9774 
9775 template<typename Derived>
9776 ExprResult
9777 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9778   // Implicit casts are eliminated during transformation, since they
9779   // will be recomputed by semantic analysis after transformation.
9780   return getDerived().TransformExpr(E->getSubExprAsWritten());
9781 }
9782 
9783 template<typename Derived>
9784 ExprResult
9785 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9786   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9787   if (!Type)
9788     return ExprError();
9789 
9790   ExprResult SubExpr
9791     = getDerived().TransformExpr(E->getSubExprAsWritten());
9792   if (SubExpr.isInvalid())
9793     return ExprError();
9794 
9795   if (!getDerived().AlwaysRebuild() &&
9796       Type == E->getTypeInfoAsWritten() &&
9797       SubExpr.get() == E->getSubExpr())
9798     return E;
9799 
9800   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9801                                             Type,
9802                                             E->getRParenLoc(),
9803                                             SubExpr.get());
9804 }
9805 
9806 template<typename Derived>
9807 ExprResult
9808 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9809   TypeSourceInfo *OldT = E->getTypeSourceInfo();
9810   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9811   if (!NewT)
9812     return ExprError();
9813 
9814   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9815   if (Init.isInvalid())
9816     return ExprError();
9817 
9818   if (!getDerived().AlwaysRebuild() &&
9819       OldT == NewT &&
9820       Init.get() == E->getInitializer())
9821     return SemaRef.MaybeBindToTemporary(E);
9822 
9823   // Note: the expression type doesn't necessarily match the
9824   // type-as-written, but that's okay, because it should always be
9825   // derivable from the initializer.
9826 
9827   return getDerived().RebuildCompoundLiteralExpr(
9828       E->getLParenLoc(), NewT,
9829       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
9830 }
9831 
9832 template<typename Derived>
9833 ExprResult
9834 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9835   ExprResult Base = getDerived().TransformExpr(E->getBase());
9836   if (Base.isInvalid())
9837     return ExprError();
9838 
9839   if (!getDerived().AlwaysRebuild() &&
9840       Base.get() == E->getBase())
9841     return E;
9842 
9843   // FIXME: Bad source location
9844   SourceLocation FakeOperatorLoc =
9845       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
9846   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9847                                                   E->getAccessorLoc(),
9848                                                   E->getAccessor());
9849 }
9850 
9851 template<typename Derived>
9852 ExprResult
9853 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9854   if (InitListExpr *Syntactic = E->getSyntacticForm())
9855     E = Syntactic;
9856 
9857   bool InitChanged = false;
9858 
9859   EnterExpressionEvaluationContext Context(
9860       getSema(), EnterExpressionEvaluationContext::InitList);
9861 
9862   SmallVector<Expr*, 4> Inits;
9863   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9864                                   Inits, &InitChanged))
9865     return ExprError();
9866 
9867   if (!getDerived().AlwaysRebuild() && !InitChanged) {
9868     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9869     // in some cases. We can't reuse it in general, because the syntactic and
9870     // semantic forms are linked, and we can't know that semantic form will
9871     // match even if the syntactic form does.
9872   }
9873 
9874   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9875                                       E->getRBraceLoc());
9876 }
9877 
9878 template<typename Derived>
9879 ExprResult
9880 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9881   Designation Desig;
9882 
9883   // transform the initializer value
9884   ExprResult Init = getDerived().TransformExpr(E->getInit());
9885   if (Init.isInvalid())
9886     return ExprError();
9887 
9888   // transform the designators.
9889   SmallVector<Expr*, 4> ArrayExprs;
9890   bool ExprChanged = false;
9891   for (const DesignatedInitExpr::Designator &D : E->designators()) {
9892     if (D.isFieldDesignator()) {
9893       Desig.AddDesignator(Designator::getField(D.getFieldName(),
9894                                                D.getDotLoc(),
9895                                                D.getFieldLoc()));
9896       if (D.getField()) {
9897         FieldDecl *Field = cast_or_null<FieldDecl>(
9898             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
9899         if (Field != D.getField())
9900           // Rebuild the expression when the transformed FieldDecl is
9901           // different to the already assigned FieldDecl.
9902           ExprChanged = true;
9903       } else {
9904         // Ensure that the designator expression is rebuilt when there isn't
9905         // a resolved FieldDecl in the designator as we don't want to assign
9906         // a FieldDecl to a pattern designator that will be instantiated again.
9907         ExprChanged = true;
9908       }
9909       continue;
9910     }
9911 
9912     if (D.isArrayDesignator()) {
9913       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
9914       if (Index.isInvalid())
9915         return ExprError();
9916 
9917       Desig.AddDesignator(
9918           Designator::getArray(Index.get(), D.getLBracketLoc()));
9919 
9920       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
9921       ArrayExprs.push_back(Index.get());
9922       continue;
9923     }
9924 
9925     assert(D.isArrayRangeDesignator() && "New kind of designator?");
9926     ExprResult Start
9927       = getDerived().TransformExpr(E->getArrayRangeStart(D));
9928     if (Start.isInvalid())
9929       return ExprError();
9930 
9931     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
9932     if (End.isInvalid())
9933       return ExprError();
9934 
9935     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
9936                                                   End.get(),
9937                                                   D.getLBracketLoc(),
9938                                                   D.getEllipsisLoc()));
9939 
9940     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
9941                   End.get() != E->getArrayRangeEnd(D);
9942 
9943     ArrayExprs.push_back(Start.get());
9944     ArrayExprs.push_back(End.get());
9945   }
9946 
9947   if (!getDerived().AlwaysRebuild() &&
9948       Init.get() == E->getInit() &&
9949       !ExprChanged)
9950     return E;
9951 
9952   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
9953                                                 E->getEqualOrColonLoc(),
9954                                                 E->usesGNUSyntax(), Init.get());
9955 }
9956 
9957 // Seems that if TransformInitListExpr() only works on the syntactic form of an
9958 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
9959 template<typename Derived>
9960 ExprResult
9961 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
9962     DesignatedInitUpdateExpr *E) {
9963   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
9964                    "initializer");
9965   return ExprError();
9966 }
9967 
9968 template<typename Derived>
9969 ExprResult
9970 TreeTransform<Derived>::TransformNoInitExpr(
9971     NoInitExpr *E) {
9972   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
9973   return ExprError();
9974 }
9975 
9976 template<typename Derived>
9977 ExprResult
9978 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
9979   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
9980   return ExprError();
9981 }
9982 
9983 template<typename Derived>
9984 ExprResult
9985 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
9986   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
9987   return ExprError();
9988 }
9989 
9990 template<typename Derived>
9991 ExprResult
9992 TreeTransform<Derived>::TransformImplicitValueInitExpr(
9993                                                      ImplicitValueInitExpr *E) {
9994   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
9995 
9996   // FIXME: Will we ever have proper type location here? Will we actually
9997   // need to transform the type?
9998   QualType T = getDerived().TransformType(E->getType());
9999   if (T.isNull())
10000     return ExprError();
10001 
10002   if (!getDerived().AlwaysRebuild() &&
10003       T == E->getType())
10004     return E;
10005 
10006   return getDerived().RebuildImplicitValueInitExpr(T);
10007 }
10008 
10009 template<typename Derived>
10010 ExprResult
10011 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10012   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10013   if (!TInfo)
10014     return ExprError();
10015 
10016   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10017   if (SubExpr.isInvalid())
10018     return ExprError();
10019 
10020   if (!getDerived().AlwaysRebuild() &&
10021       TInfo == E->getWrittenTypeInfo() &&
10022       SubExpr.get() == E->getSubExpr())
10023     return E;
10024 
10025   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10026                                        TInfo, E->getRParenLoc());
10027 }
10028 
10029 template<typename Derived>
10030 ExprResult
10031 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10032   bool ArgumentChanged = false;
10033   SmallVector<Expr*, 4> Inits;
10034   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10035                      &ArgumentChanged))
10036     return ExprError();
10037 
10038   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10039                                            Inits,
10040                                            E->getRParenLoc());
10041 }
10042 
10043 /// Transform an address-of-label expression.
10044 ///
10045 /// By default, the transformation of an address-of-label expression always
10046 /// rebuilds the expression, so that the label identifier can be resolved to
10047 /// the corresponding label statement by semantic analysis.
10048 template<typename Derived>
10049 ExprResult
10050 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10051   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10052                                         E->getLabel());
10053   if (!LD)
10054     return ExprError();
10055 
10056   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10057                                            cast<LabelDecl>(LD));
10058 }
10059 
10060 template<typename Derived>
10061 ExprResult
10062 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10063   SemaRef.ActOnStartStmtExpr();
10064   StmtResult SubStmt
10065     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10066   if (SubStmt.isInvalid()) {
10067     SemaRef.ActOnStmtExprError();
10068     return ExprError();
10069   }
10070 
10071   if (!getDerived().AlwaysRebuild() &&
10072       SubStmt.get() == E->getSubStmt()) {
10073     // Calling this an 'error' is unintuitive, but it does the right thing.
10074     SemaRef.ActOnStmtExprError();
10075     return SemaRef.MaybeBindToTemporary(E);
10076   }
10077 
10078   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
10079                                       SubStmt.get(),
10080                                       E->getRParenLoc());
10081 }
10082 
10083 template<typename Derived>
10084 ExprResult
10085 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10086   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10087   if (Cond.isInvalid())
10088     return ExprError();
10089 
10090   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10091   if (LHS.isInvalid())
10092     return ExprError();
10093 
10094   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10095   if (RHS.isInvalid())
10096     return ExprError();
10097 
10098   if (!getDerived().AlwaysRebuild() &&
10099       Cond.get() == E->getCond() &&
10100       LHS.get() == E->getLHS() &&
10101       RHS.get() == E->getRHS())
10102     return E;
10103 
10104   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10105                                         Cond.get(), LHS.get(), RHS.get(),
10106                                         E->getRParenLoc());
10107 }
10108 
10109 template<typename Derived>
10110 ExprResult
10111 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10112   return E;
10113 }
10114 
10115 template<typename Derived>
10116 ExprResult
10117 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10118   switch (E->getOperator()) {
10119   case OO_New:
10120   case OO_Delete:
10121   case OO_Array_New:
10122   case OO_Array_Delete:
10123     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
10124 
10125   case OO_Call: {
10126     // This is a call to an object's operator().
10127     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
10128 
10129     // Transform the object itself.
10130     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10131     if (Object.isInvalid())
10132       return ExprError();
10133 
10134     // FIXME: Poor location information
10135     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10136         static_cast<Expr *>(Object.get())->getEndLoc());
10137 
10138     // Transform the call arguments.
10139     SmallVector<Expr*, 8> Args;
10140     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10141                                     Args))
10142       return ExprError();
10143 
10144     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10145                                         E->getEndLoc());
10146   }
10147 
10148 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10149   case OO_##Name:
10150 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10151 #include "clang/Basic/OperatorKinds.def"
10152   case OO_Subscript:
10153     // Handled below.
10154     break;
10155 
10156   case OO_Conditional:
10157     llvm_unreachable("conditional operator is not actually overloadable");
10158 
10159   case OO_None:
10160   case NUM_OVERLOADED_OPERATORS:
10161     llvm_unreachable("not an overloaded operator?");
10162   }
10163 
10164   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10165   if (Callee.isInvalid())
10166     return ExprError();
10167 
10168   ExprResult First;
10169   if (E->getOperator() == OO_Amp)
10170     First = getDerived().TransformAddressOfOperand(E->getArg(0));
10171   else
10172     First = getDerived().TransformExpr(E->getArg(0));
10173   if (First.isInvalid())
10174     return ExprError();
10175 
10176   ExprResult Second;
10177   if (E->getNumArgs() == 2) {
10178     Second = getDerived().TransformExpr(E->getArg(1));
10179     if (Second.isInvalid())
10180       return ExprError();
10181   }
10182 
10183   if (!getDerived().AlwaysRebuild() &&
10184       Callee.get() == E->getCallee() &&
10185       First.get() == E->getArg(0) &&
10186       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10187     return SemaRef.MaybeBindToTemporary(E);
10188 
10189   Sema::FPContractStateRAII FPContractState(getSema());
10190   getSema().FPFeatures = E->getFPFeatures();
10191 
10192   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10193                                                  E->getOperatorLoc(),
10194                                                  Callee.get(),
10195                                                  First.get(),
10196                                                  Second.get());
10197 }
10198 
10199 template<typename Derived>
10200 ExprResult
10201 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10202   return getDerived().TransformCallExpr(E);
10203 }
10204 
10205 template <typename Derived>
10206 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10207   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10208                          getSema().CurContext != E->getParentContext();
10209 
10210   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10211     return E;
10212 
10213   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10214                                            E->getEndLoc(),
10215                                            getSema().CurContext);
10216 }
10217 
10218 template<typename Derived>
10219 ExprResult
10220 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10221   // Transform the callee.
10222   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10223   if (Callee.isInvalid())
10224     return ExprError();
10225 
10226   // Transform exec config.
10227   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10228   if (EC.isInvalid())
10229     return ExprError();
10230 
10231   // Transform arguments.
10232   bool ArgChanged = false;
10233   SmallVector<Expr*, 8> Args;
10234   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10235                                   &ArgChanged))
10236     return ExprError();
10237 
10238   if (!getDerived().AlwaysRebuild() &&
10239       Callee.get() == E->getCallee() &&
10240       !ArgChanged)
10241     return SemaRef.MaybeBindToTemporary(E);
10242 
10243   // FIXME: Wrong source location information for the '('.
10244   SourceLocation FakeLParenLoc
10245     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10246   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10247                                       Args,
10248                                       E->getRParenLoc(), EC.get());
10249 }
10250 
10251 template<typename Derived>
10252 ExprResult
10253 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10254   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10255   if (!Type)
10256     return ExprError();
10257 
10258   ExprResult SubExpr
10259     = getDerived().TransformExpr(E->getSubExprAsWritten());
10260   if (SubExpr.isInvalid())
10261     return ExprError();
10262 
10263   if (!getDerived().AlwaysRebuild() &&
10264       Type == E->getTypeInfoAsWritten() &&
10265       SubExpr.get() == E->getSubExpr())
10266     return E;
10267   return getDerived().RebuildCXXNamedCastExpr(
10268       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10269       Type, E->getAngleBrackets().getEnd(),
10270       // FIXME. this should be '(' location
10271       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10272 }
10273 
10274 template<typename Derived>
10275 ExprResult
10276 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10277   TypeSourceInfo *TSI =
10278       getDerived().TransformType(BCE->getTypeInfoAsWritten());
10279   if (!TSI)
10280     return ExprError();
10281 
10282   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10283   if (Sub.isInvalid())
10284     return ExprError();
10285 
10286   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10287                                                 Sub.get(), BCE->getEndLoc());
10288 }
10289 
10290 template<typename Derived>
10291 ExprResult
10292 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10293   return getDerived().TransformCXXNamedCastExpr(E);
10294 }
10295 
10296 template<typename Derived>
10297 ExprResult
10298 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10299   return getDerived().TransformCXXNamedCastExpr(E);
10300 }
10301 
10302 template<typename Derived>
10303 ExprResult
10304 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10305                                                       CXXReinterpretCastExpr *E) {
10306   return getDerived().TransformCXXNamedCastExpr(E);
10307 }
10308 
10309 template<typename Derived>
10310 ExprResult
10311 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10312   return getDerived().TransformCXXNamedCastExpr(E);
10313 }
10314 
10315 template<typename Derived>
10316 ExprResult
10317 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10318                                                      CXXFunctionalCastExpr *E) {
10319   TypeSourceInfo *Type =
10320       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10321   if (!Type)
10322     return ExprError();
10323 
10324   ExprResult SubExpr
10325     = getDerived().TransformExpr(E->getSubExprAsWritten());
10326   if (SubExpr.isInvalid())
10327     return ExprError();
10328 
10329   if (!getDerived().AlwaysRebuild() &&
10330       Type == E->getTypeInfoAsWritten() &&
10331       SubExpr.get() == E->getSubExpr())
10332     return E;
10333 
10334   return getDerived().RebuildCXXFunctionalCastExpr(Type,
10335                                                    E->getLParenLoc(),
10336                                                    SubExpr.get(),
10337                                                    E->getRParenLoc(),
10338                                                    E->isListInitialization());
10339 }
10340 
10341 template<typename Derived>
10342 ExprResult
10343 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10344   if (E->isTypeOperand()) {
10345     TypeSourceInfo *TInfo
10346       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10347     if (!TInfo)
10348       return ExprError();
10349 
10350     if (!getDerived().AlwaysRebuild() &&
10351         TInfo == E->getTypeOperandSourceInfo())
10352       return E;
10353 
10354     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10355                                              TInfo, E->getEndLoc());
10356   }
10357 
10358   // We don't know whether the subexpression is potentially evaluated until
10359   // after we perform semantic analysis.  We speculatively assume it is
10360   // unevaluated; it will get fixed later if the subexpression is in fact
10361   // potentially evaluated.
10362   EnterExpressionEvaluationContext Unevaluated(
10363       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10364       Sema::ReuseLambdaContextDecl);
10365 
10366   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10367   if (SubExpr.isInvalid())
10368     return ExprError();
10369 
10370   if (!getDerived().AlwaysRebuild() &&
10371       SubExpr.get() == E->getExprOperand())
10372     return E;
10373 
10374   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10375                                            SubExpr.get(), E->getEndLoc());
10376 }
10377 
10378 template<typename Derived>
10379 ExprResult
10380 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10381   if (E->isTypeOperand()) {
10382     TypeSourceInfo *TInfo
10383       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10384     if (!TInfo)
10385       return ExprError();
10386 
10387     if (!getDerived().AlwaysRebuild() &&
10388         TInfo == E->getTypeOperandSourceInfo())
10389       return E;
10390 
10391     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10392                                              TInfo, E->getEndLoc());
10393   }
10394 
10395   EnterExpressionEvaluationContext Unevaluated(
10396       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10397 
10398   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10399   if (SubExpr.isInvalid())
10400     return ExprError();
10401 
10402   if (!getDerived().AlwaysRebuild() &&
10403       SubExpr.get() == E->getExprOperand())
10404     return E;
10405 
10406   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10407                                            SubExpr.get(), E->getEndLoc());
10408 }
10409 
10410 template<typename Derived>
10411 ExprResult
10412 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10413   return E;
10414 }
10415 
10416 template<typename Derived>
10417 ExprResult
10418 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10419                                                      CXXNullPtrLiteralExpr *E) {
10420   return E;
10421 }
10422 
10423 template<typename Derived>
10424 ExprResult
10425 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10426   QualType T = getSema().getCurrentThisType();
10427 
10428   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10429     // Mark it referenced in the new context regardless.
10430     // FIXME: this is a bit instantiation-specific.
10431     getSema().MarkThisReferenced(E);
10432     return E;
10433   }
10434 
10435   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10436 }
10437 
10438 template<typename Derived>
10439 ExprResult
10440 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10441   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10442   if (SubExpr.isInvalid())
10443     return ExprError();
10444 
10445   if (!getDerived().AlwaysRebuild() &&
10446       SubExpr.get() == E->getSubExpr())
10447     return E;
10448 
10449   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10450                                           E->isThrownVariableInScope());
10451 }
10452 
10453 template<typename Derived>
10454 ExprResult
10455 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10456   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10457       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10458   if (!Param)
10459     return ExprError();
10460 
10461   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10462       E->getUsedContext() == SemaRef.CurContext)
10463     return E;
10464 
10465   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10466 }
10467 
10468 template<typename Derived>
10469 ExprResult
10470 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10471   FieldDecl *Field = cast_or_null<FieldDecl>(
10472       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10473   if (!Field)
10474     return ExprError();
10475 
10476   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10477       E->getUsedContext() == SemaRef.CurContext)
10478     return E;
10479 
10480   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10481 }
10482 
10483 template<typename Derived>
10484 ExprResult
10485 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10486                                                     CXXScalarValueInitExpr *E) {
10487   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10488   if (!T)
10489     return ExprError();
10490 
10491   if (!getDerived().AlwaysRebuild() &&
10492       T == E->getTypeSourceInfo())
10493     return E;
10494 
10495   return getDerived().RebuildCXXScalarValueInitExpr(T,
10496                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
10497                                                     E->getRParenLoc());
10498 }
10499 
10500 template<typename Derived>
10501 ExprResult
10502 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10503   // Transform the type that we're allocating
10504   TypeSourceInfo *AllocTypeInfo =
10505       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10506   if (!AllocTypeInfo)
10507     return ExprError();
10508 
10509   // Transform the size of the array we're allocating (if any).
10510   Optional<Expr *> ArraySize;
10511   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10512     ExprResult NewArraySize;
10513     if (*OldArraySize) {
10514       NewArraySize = getDerived().TransformExpr(*OldArraySize);
10515       if (NewArraySize.isInvalid())
10516         return ExprError();
10517     }
10518     ArraySize = NewArraySize.get();
10519   }
10520 
10521   // Transform the placement arguments (if any).
10522   bool ArgumentChanged = false;
10523   SmallVector<Expr*, 8> PlacementArgs;
10524   if (getDerived().TransformExprs(E->getPlacementArgs(),
10525                                   E->getNumPlacementArgs(), true,
10526                                   PlacementArgs, &ArgumentChanged))
10527     return ExprError();
10528 
10529   // Transform the initializer (if any).
10530   Expr *OldInit = E->getInitializer();
10531   ExprResult NewInit;
10532   if (OldInit)
10533     NewInit = getDerived().TransformInitializer(OldInit, true);
10534   if (NewInit.isInvalid())
10535     return ExprError();
10536 
10537   // Transform new operator and delete operator.
10538   FunctionDecl *OperatorNew = nullptr;
10539   if (E->getOperatorNew()) {
10540     OperatorNew = cast_or_null<FunctionDecl>(
10541         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10542     if (!OperatorNew)
10543       return ExprError();
10544   }
10545 
10546   FunctionDecl *OperatorDelete = nullptr;
10547   if (E->getOperatorDelete()) {
10548     OperatorDelete = cast_or_null<FunctionDecl>(
10549         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10550     if (!OperatorDelete)
10551       return ExprError();
10552   }
10553 
10554   if (!getDerived().AlwaysRebuild() &&
10555       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10556       ArraySize == E->getArraySize() &&
10557       NewInit.get() == OldInit &&
10558       OperatorNew == E->getOperatorNew() &&
10559       OperatorDelete == E->getOperatorDelete() &&
10560       !ArgumentChanged) {
10561     // Mark any declarations we need as referenced.
10562     // FIXME: instantiation-specific.
10563     if (OperatorNew)
10564       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10565     if (OperatorDelete)
10566       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10567 
10568     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10569       QualType ElementType
10570         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10571       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10572         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10573         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10574           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10575         }
10576       }
10577     }
10578 
10579     return E;
10580   }
10581 
10582   QualType AllocType = AllocTypeInfo->getType();
10583   if (!ArraySize) {
10584     // If no array size was specified, but the new expression was
10585     // instantiated with an array type (e.g., "new T" where T is
10586     // instantiated with "int[4]"), extract the outer bound from the
10587     // array type as our array size. We do this with constant and
10588     // dependently-sized array types.
10589     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10590     if (!ArrayT) {
10591       // Do nothing
10592     } else if (const ConstantArrayType *ConsArrayT
10593                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
10594       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10595                                          SemaRef.Context.getSizeType(),
10596                                          /*FIXME:*/ E->getBeginLoc());
10597       AllocType = ConsArrayT->getElementType();
10598     } else if (const DependentSizedArrayType *DepArrayT
10599                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10600       if (DepArrayT->getSizeExpr()) {
10601         ArraySize = DepArrayT->getSizeExpr();
10602         AllocType = DepArrayT->getElementType();
10603       }
10604     }
10605   }
10606 
10607   return getDerived().RebuildCXXNewExpr(
10608       E->getBeginLoc(), E->isGlobalNew(),
10609       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10610       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10611       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10612 }
10613 
10614 template<typename Derived>
10615 ExprResult
10616 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10617   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10618   if (Operand.isInvalid())
10619     return ExprError();
10620 
10621   // Transform the delete operator, if known.
10622   FunctionDecl *OperatorDelete = nullptr;
10623   if (E->getOperatorDelete()) {
10624     OperatorDelete = cast_or_null<FunctionDecl>(
10625         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10626     if (!OperatorDelete)
10627       return ExprError();
10628   }
10629 
10630   if (!getDerived().AlwaysRebuild() &&
10631       Operand.get() == E->getArgument() &&
10632       OperatorDelete == E->getOperatorDelete()) {
10633     // Mark any declarations we need as referenced.
10634     // FIXME: instantiation-specific.
10635     if (OperatorDelete)
10636       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10637 
10638     if (!E->getArgument()->isTypeDependent()) {
10639       QualType Destroyed = SemaRef.Context.getBaseElementType(
10640                                                          E->getDestroyedType());
10641       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10642         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10643         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10644                                        SemaRef.LookupDestructor(Record));
10645       }
10646     }
10647 
10648     return E;
10649   }
10650 
10651   return getDerived().RebuildCXXDeleteExpr(
10652       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10653 }
10654 
10655 template<typename Derived>
10656 ExprResult
10657 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10658                                                      CXXPseudoDestructorExpr *E) {
10659   ExprResult Base = getDerived().TransformExpr(E->getBase());
10660   if (Base.isInvalid())
10661     return ExprError();
10662 
10663   ParsedType ObjectTypePtr;
10664   bool MayBePseudoDestructor = false;
10665   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10666                                               E->getOperatorLoc(),
10667                                         E->isArrow()? tok::arrow : tok::period,
10668                                               ObjectTypePtr,
10669                                               MayBePseudoDestructor);
10670   if (Base.isInvalid())
10671     return ExprError();
10672 
10673   QualType ObjectType = ObjectTypePtr.get();
10674   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10675   if (QualifierLoc) {
10676     QualifierLoc
10677       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10678     if (!QualifierLoc)
10679       return ExprError();
10680   }
10681   CXXScopeSpec SS;
10682   SS.Adopt(QualifierLoc);
10683 
10684   PseudoDestructorTypeStorage Destroyed;
10685   if (E->getDestroyedTypeInfo()) {
10686     TypeSourceInfo *DestroyedTypeInfo
10687       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10688                                                 ObjectType, nullptr, SS);
10689     if (!DestroyedTypeInfo)
10690       return ExprError();
10691     Destroyed = DestroyedTypeInfo;
10692   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10693     // We aren't likely to be able to resolve the identifier down to a type
10694     // now anyway, so just retain the identifier.
10695     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10696                                             E->getDestroyedTypeLoc());
10697   } else {
10698     // Look for a destructor known with the given name.
10699     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10700                                               *E->getDestroyedTypeIdentifier(),
10701                                                 E->getDestroyedTypeLoc(),
10702                                                 /*Scope=*/nullptr,
10703                                                 SS, ObjectTypePtr,
10704                                                 false);
10705     if (!T)
10706       return ExprError();
10707 
10708     Destroyed
10709       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10710                                                  E->getDestroyedTypeLoc());
10711   }
10712 
10713   TypeSourceInfo *ScopeTypeInfo = nullptr;
10714   if (E->getScopeTypeInfo()) {
10715     CXXScopeSpec EmptySS;
10716     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10717                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10718     if (!ScopeTypeInfo)
10719       return ExprError();
10720   }
10721 
10722   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10723                                                      E->getOperatorLoc(),
10724                                                      E->isArrow(),
10725                                                      SS,
10726                                                      ScopeTypeInfo,
10727                                                      E->getColonColonLoc(),
10728                                                      E->getTildeLoc(),
10729                                                      Destroyed);
10730 }
10731 
10732 template <typename Derived>
10733 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10734                                                         bool RequiresADL,
10735                                                         LookupResult &R) {
10736   // Transform all the decls.
10737   bool AllEmptyPacks = true;
10738   for (auto *OldD : Old->decls()) {
10739     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10740     if (!InstD) {
10741       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10742       // This can happen because of dependent hiding.
10743       if (isa<UsingShadowDecl>(OldD))
10744         continue;
10745       else {
10746         R.clear();
10747         return true;
10748       }
10749     }
10750 
10751     // Expand using pack declarations.
10752     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10753     ArrayRef<NamedDecl*> Decls = SingleDecl;
10754     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10755       Decls = UPD->expansions();
10756 
10757     // Expand using declarations.
10758     for (auto *D : Decls) {
10759       if (auto *UD = dyn_cast<UsingDecl>(D)) {
10760         for (auto *SD : UD->shadows())
10761           R.addDecl(SD);
10762       } else {
10763         R.addDecl(D);
10764       }
10765     }
10766 
10767     AllEmptyPacks &= Decls.empty();
10768   };
10769 
10770   // C++ [temp.res]/8.4.2:
10771   //   The program is ill-formed, no diagnostic required, if [...] lookup for
10772   //   a name in the template definition found a using-declaration, but the
10773   //   lookup in the corresponding scope in the instantiation odoes not find
10774   //   any declarations because the using-declaration was a pack expansion and
10775   //   the corresponding pack is empty
10776   if (AllEmptyPacks && !RequiresADL) {
10777     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10778         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10779     return true;
10780   }
10781 
10782   // Resolve a kind, but don't do any further analysis.  If it's
10783   // ambiguous, the callee needs to deal with it.
10784   R.resolveKind();
10785   return false;
10786 }
10787 
10788 template<typename Derived>
10789 ExprResult
10790 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10791                                                   UnresolvedLookupExpr *Old) {
10792   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10793                  Sema::LookupOrdinaryName);
10794 
10795   // Transform the declaration set.
10796   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10797     return ExprError();
10798 
10799   // Rebuild the nested-name qualifier, if present.
10800   CXXScopeSpec SS;
10801   if (Old->getQualifierLoc()) {
10802     NestedNameSpecifierLoc QualifierLoc
10803       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10804     if (!QualifierLoc)
10805       return ExprError();
10806 
10807     SS.Adopt(QualifierLoc);
10808   }
10809 
10810   if (Old->getNamingClass()) {
10811     CXXRecordDecl *NamingClass
10812       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10813                                                             Old->getNameLoc(),
10814                                                         Old->getNamingClass()));
10815     if (!NamingClass) {
10816       R.clear();
10817       return ExprError();
10818     }
10819 
10820     R.setNamingClass(NamingClass);
10821   }
10822 
10823   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10824 
10825   // If we have neither explicit template arguments, nor the template keyword,
10826   // it's a normal declaration name or member reference.
10827   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10828     NamedDecl *D = R.getAsSingle<NamedDecl>();
10829     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10830     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10831     // give a good diagnostic.
10832     if (D && D->isCXXInstanceMember()) {
10833       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10834                                                      /*TemplateArgs=*/nullptr,
10835                                                      /*Scope=*/nullptr);
10836     }
10837 
10838     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10839   }
10840 
10841   // If we have template arguments, rebuild them, then rebuild the
10842   // templateid expression.
10843   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10844   if (Old->hasExplicitTemplateArgs() &&
10845       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10846                                               Old->getNumTemplateArgs(),
10847                                               TransArgs)) {
10848     R.clear();
10849     return ExprError();
10850   }
10851 
10852   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10853                                             Old->requiresADL(), &TransArgs);
10854 }
10855 
10856 template<typename Derived>
10857 ExprResult
10858 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10859   bool ArgChanged = false;
10860   SmallVector<TypeSourceInfo *, 4> Args;
10861   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10862     TypeSourceInfo *From = E->getArg(I);
10863     TypeLoc FromTL = From->getTypeLoc();
10864     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10865       TypeLocBuilder TLB;
10866       TLB.reserve(FromTL.getFullDataSize());
10867       QualType To = getDerived().TransformType(TLB, FromTL);
10868       if (To.isNull())
10869         return ExprError();
10870 
10871       if (To == From->getType())
10872         Args.push_back(From);
10873       else {
10874         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10875         ArgChanged = true;
10876       }
10877       continue;
10878     }
10879 
10880     ArgChanged = true;
10881 
10882     // We have a pack expansion. Instantiate it.
10883     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10884     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10885     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10886     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
10887 
10888     // Determine whether the set of unexpanded parameter packs can and should
10889     // be expanded.
10890     bool Expand = true;
10891     bool RetainExpansion = false;
10892     Optional<unsigned> OrigNumExpansions =
10893         ExpansionTL.getTypePtr()->getNumExpansions();
10894     Optional<unsigned> NumExpansions = OrigNumExpansions;
10895     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
10896                                              PatternTL.getSourceRange(),
10897                                              Unexpanded,
10898                                              Expand, RetainExpansion,
10899                                              NumExpansions))
10900       return ExprError();
10901 
10902     if (!Expand) {
10903       // The transform has determined that we should perform a simple
10904       // transformation on the pack expansion, producing another pack
10905       // expansion.
10906       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10907 
10908       TypeLocBuilder TLB;
10909       TLB.reserve(From->getTypeLoc().getFullDataSize());
10910 
10911       QualType To = getDerived().TransformType(TLB, PatternTL);
10912       if (To.isNull())
10913         return ExprError();
10914 
10915       To = getDerived().RebuildPackExpansionType(To,
10916                                                  PatternTL.getSourceRange(),
10917                                                  ExpansionTL.getEllipsisLoc(),
10918                                                  NumExpansions);
10919       if (To.isNull())
10920         return ExprError();
10921 
10922       PackExpansionTypeLoc ToExpansionTL
10923         = TLB.push<PackExpansionTypeLoc>(To);
10924       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10925       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10926       continue;
10927     }
10928 
10929     // Expand the pack expansion by substituting for each argument in the
10930     // pack(s).
10931     for (unsigned I = 0; I != *NumExpansions; ++I) {
10932       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
10933       TypeLocBuilder TLB;
10934       TLB.reserve(PatternTL.getFullDataSize());
10935       QualType To = getDerived().TransformType(TLB, PatternTL);
10936       if (To.isNull())
10937         return ExprError();
10938 
10939       if (To->containsUnexpandedParameterPack()) {
10940         To = getDerived().RebuildPackExpansionType(To,
10941                                                    PatternTL.getSourceRange(),
10942                                                    ExpansionTL.getEllipsisLoc(),
10943                                                    NumExpansions);
10944         if (To.isNull())
10945           return ExprError();
10946 
10947         PackExpansionTypeLoc ToExpansionTL
10948           = TLB.push<PackExpansionTypeLoc>(To);
10949         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10950       }
10951 
10952       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10953     }
10954 
10955     if (!RetainExpansion)
10956       continue;
10957 
10958     // If we're supposed to retain a pack expansion, do so by temporarily
10959     // forgetting the partially-substituted parameter pack.
10960     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10961 
10962     TypeLocBuilder TLB;
10963     TLB.reserve(From->getTypeLoc().getFullDataSize());
10964 
10965     QualType To = getDerived().TransformType(TLB, PatternTL);
10966     if (To.isNull())
10967       return ExprError();
10968 
10969     To = getDerived().RebuildPackExpansionType(To,
10970                                                PatternTL.getSourceRange(),
10971                                                ExpansionTL.getEllipsisLoc(),
10972                                                NumExpansions);
10973     if (To.isNull())
10974       return ExprError();
10975 
10976     PackExpansionTypeLoc ToExpansionTL
10977       = TLB.push<PackExpansionTypeLoc>(To);
10978     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10979     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10980   }
10981 
10982   if (!getDerived().AlwaysRebuild() && !ArgChanged)
10983     return E;
10984 
10985   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
10986                                        E->getEndLoc());
10987 }
10988 
10989 template<typename Derived>
10990 ExprResult
10991 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
10992   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
10993   if (!T)
10994     return ExprError();
10995 
10996   if (!getDerived().AlwaysRebuild() &&
10997       T == E->getQueriedTypeSourceInfo())
10998     return E;
10999 
11000   ExprResult SubExpr;
11001   {
11002     EnterExpressionEvaluationContext Unevaluated(
11003         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11004     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
11005     if (SubExpr.isInvalid())
11006       return ExprError();
11007 
11008     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11009       return E;
11010   }
11011 
11012   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11013                                             SubExpr.get(), E->getEndLoc());
11014 }
11015 
11016 template<typename Derived>
11017 ExprResult
11018 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11019   ExprResult SubExpr;
11020   {
11021     EnterExpressionEvaluationContext Unevaluated(
11022         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11023     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11024     if (SubExpr.isInvalid())
11025       return ExprError();
11026 
11027     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11028       return E;
11029   }
11030 
11031   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11032                                              SubExpr.get(), E->getEndLoc());
11033 }
11034 
11035 template <typename Derived>
11036 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11037     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11038     TypeSourceInfo **RecoveryTSI) {
11039   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11040       DRE, AddrTaken, RecoveryTSI);
11041 
11042   // Propagate both errors and recovered types, which return ExprEmpty.
11043   if (!NewDRE.isUsable())
11044     return NewDRE;
11045 
11046   // We got an expr, wrap it up in parens.
11047   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11048     return PE;
11049   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11050                                        PE->getRParen());
11051 }
11052 
11053 template <typename Derived>
11054 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11055     DependentScopeDeclRefExpr *E) {
11056   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11057                                             nullptr);
11058 }
11059 
11060 template<typename Derived>
11061 ExprResult
11062 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11063                                                DependentScopeDeclRefExpr *E,
11064                                                bool IsAddressOfOperand,
11065                                                TypeSourceInfo **RecoveryTSI) {
11066   assert(E->getQualifierLoc());
11067   NestedNameSpecifierLoc QualifierLoc
11068   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11069   if (!QualifierLoc)
11070     return ExprError();
11071   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11072 
11073   // TODO: If this is a conversion-function-id, verify that the
11074   // destination type name (if present) resolves the same way after
11075   // instantiation as it did in the local scope.
11076 
11077   DeclarationNameInfo NameInfo
11078     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11079   if (!NameInfo.getName())
11080     return ExprError();
11081 
11082   if (!E->hasExplicitTemplateArgs()) {
11083     if (!getDerived().AlwaysRebuild() &&
11084         QualifierLoc == E->getQualifierLoc() &&
11085         // Note: it is sufficient to compare the Name component of NameInfo:
11086         // if name has not changed, DNLoc has not changed either.
11087         NameInfo.getName() == E->getDeclName())
11088       return E;
11089 
11090     return getDerived().RebuildDependentScopeDeclRefExpr(
11091         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11092         IsAddressOfOperand, RecoveryTSI);
11093   }
11094 
11095   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11096   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11097                                               E->getNumTemplateArgs(),
11098                                               TransArgs))
11099     return ExprError();
11100 
11101   return getDerived().RebuildDependentScopeDeclRefExpr(
11102       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11103       RecoveryTSI);
11104 }
11105 
11106 template<typename Derived>
11107 ExprResult
11108 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11109   // CXXConstructExprs other than for list-initialization and
11110   // CXXTemporaryObjectExpr are always implicit, so when we have
11111   // a 1-argument construction we just transform that argument.
11112   if ((E->getNumArgs() == 1 ||
11113        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11114       (!getDerived().DropCallArgument(E->getArg(0))) &&
11115       !E->isListInitialization())
11116     return getDerived().TransformExpr(E->getArg(0));
11117 
11118   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11119 
11120   QualType T = getDerived().TransformType(E->getType());
11121   if (T.isNull())
11122     return ExprError();
11123 
11124   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11125       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11126   if (!Constructor)
11127     return ExprError();
11128 
11129   bool ArgumentChanged = false;
11130   SmallVector<Expr*, 8> Args;
11131   {
11132     EnterExpressionEvaluationContext Context(
11133         getSema(), EnterExpressionEvaluationContext::InitList,
11134         E->isListInitialization());
11135     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11136                                     &ArgumentChanged))
11137       return ExprError();
11138   }
11139 
11140   if (!getDerived().AlwaysRebuild() &&
11141       T == E->getType() &&
11142       Constructor == E->getConstructor() &&
11143       !ArgumentChanged) {
11144     // Mark the constructor as referenced.
11145     // FIXME: Instantiation-specific
11146     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11147     return E;
11148   }
11149 
11150   return getDerived().RebuildCXXConstructExpr(
11151       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11152       E->hadMultipleCandidates(), E->isListInitialization(),
11153       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11154       E->getConstructionKind(), E->getParenOrBraceRange());
11155 }
11156 
11157 template<typename Derived>
11158 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11159     CXXInheritedCtorInitExpr *E) {
11160   QualType T = getDerived().TransformType(E->getType());
11161   if (T.isNull())
11162     return ExprError();
11163 
11164   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11165       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11166   if (!Constructor)
11167     return ExprError();
11168 
11169   if (!getDerived().AlwaysRebuild() &&
11170       T == E->getType() &&
11171       Constructor == E->getConstructor()) {
11172     // Mark the constructor as referenced.
11173     // FIXME: Instantiation-specific
11174     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11175     return E;
11176   }
11177 
11178   return getDerived().RebuildCXXInheritedCtorInitExpr(
11179       T, E->getLocation(), Constructor,
11180       E->constructsVBase(), E->inheritedFromVBase());
11181 }
11182 
11183 /// Transform a C++ temporary-binding expression.
11184 ///
11185 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11186 /// transform the subexpression and return that.
11187 template<typename Derived>
11188 ExprResult
11189 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11190   return getDerived().TransformExpr(E->getSubExpr());
11191 }
11192 
11193 /// Transform a C++ expression that contains cleanups that should
11194 /// be run after the expression is evaluated.
11195 ///
11196 /// Since ExprWithCleanups nodes are implicitly generated, we
11197 /// just transform the subexpression and return that.
11198 template<typename Derived>
11199 ExprResult
11200 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11201   return getDerived().TransformExpr(E->getSubExpr());
11202 }
11203 
11204 template<typename Derived>
11205 ExprResult
11206 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11207                                                     CXXTemporaryObjectExpr *E) {
11208   TypeSourceInfo *T =
11209       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11210   if (!T)
11211     return ExprError();
11212 
11213   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11214       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11215   if (!Constructor)
11216     return ExprError();
11217 
11218   bool ArgumentChanged = false;
11219   SmallVector<Expr*, 8> Args;
11220   Args.reserve(E->getNumArgs());
11221   {
11222     EnterExpressionEvaluationContext Context(
11223         getSema(), EnterExpressionEvaluationContext::InitList,
11224         E->isListInitialization());
11225     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11226                        &ArgumentChanged))
11227       return ExprError();
11228   }
11229 
11230   if (!getDerived().AlwaysRebuild() &&
11231       T == E->getTypeSourceInfo() &&
11232       Constructor == E->getConstructor() &&
11233       !ArgumentChanged) {
11234     // FIXME: Instantiation-specific
11235     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11236     return SemaRef.MaybeBindToTemporary(E);
11237   }
11238 
11239   // FIXME: We should just pass E->isListInitialization(), but we're not
11240   // prepared to handle list-initialization without a child InitListExpr.
11241   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11242   return getDerived().RebuildCXXTemporaryObjectExpr(
11243       T, LParenLoc, Args, E->getEndLoc(),
11244       /*ListInitialization=*/LParenLoc.isInvalid());
11245 }
11246 
11247 template<typename Derived>
11248 ExprResult
11249 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11250   // Transform any init-capture expressions before entering the scope of the
11251   // lambda body, because they are not semantically within that scope.
11252   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11253   struct TransformedInitCapture {
11254     // The location of the ... if the result is retaining a pack expansion.
11255     SourceLocation EllipsisLoc;
11256     // Zero or more expansions of the init-capture.
11257     SmallVector<InitCaptureInfoTy, 4> Expansions;
11258   };
11259   SmallVector<TransformedInitCapture, 4> InitCaptures;
11260   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11261   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11262                                     CEnd = E->capture_end();
11263        C != CEnd; ++C) {
11264     if (!E->isInitCapture(C))
11265       continue;
11266 
11267     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11268     VarDecl *OldVD = C->getCapturedVar();
11269 
11270     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11271                                 Optional<unsigned> NumExpansions) {
11272       ExprResult NewExprInitResult = getDerived().TransformInitializer(
11273           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11274 
11275       if (NewExprInitResult.isInvalid()) {
11276         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11277         return;
11278       }
11279       Expr *NewExprInit = NewExprInitResult.get();
11280 
11281       QualType NewInitCaptureType =
11282           getSema().buildLambdaInitCaptureInitialization(
11283               C->getLocation(), OldVD->getType()->isReferenceType(),
11284               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11285               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11286               NewExprInit);
11287       Result.Expansions.push_back(
11288           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11289     };
11290 
11291     // If this is an init-capture pack, consider expanding the pack now.
11292     if (OldVD->isParameterPack()) {
11293       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11294                                              ->getTypeLoc()
11295                                              .castAs<PackExpansionTypeLoc>();
11296       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11297       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11298 
11299       // Determine whether the set of unexpanded parameter packs can and should
11300       // be expanded.
11301       bool Expand = true;
11302       bool RetainExpansion = false;
11303       Optional<unsigned> OrigNumExpansions =
11304           ExpansionTL.getTypePtr()->getNumExpansions();
11305       Optional<unsigned> NumExpansions = OrigNumExpansions;
11306       if (getDerived().TryExpandParameterPacks(
11307               ExpansionTL.getEllipsisLoc(),
11308               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11309               RetainExpansion, NumExpansions))
11310         return ExprError();
11311       if (Expand) {
11312         for (unsigned I = 0; I != *NumExpansions; ++I) {
11313           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11314           SubstInitCapture(SourceLocation(), None);
11315         }
11316       }
11317       if (!Expand || RetainExpansion) {
11318         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11319         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11320         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11321       }
11322     } else {
11323       SubstInitCapture(SourceLocation(), None);
11324     }
11325   }
11326 
11327   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11328   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11329 
11330   // Transform the template parameters, and add them to the current
11331   // instantiation scope. The null case is handled correctly.
11332   auto TPL = getDerived().TransformTemplateParameterList(
11333       E->getTemplateParameterList());
11334   LSI->GLTemplateParameterList = TPL;
11335 
11336   // Transform the type of the original lambda's call operator.
11337   // The transformation MUST be done in the CurrentInstantiationScope since
11338   // it introduces a mapping of the original to the newly created
11339   // transformed parameters.
11340   TypeSourceInfo *NewCallOpTSI = nullptr;
11341   {
11342     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11343     FunctionProtoTypeLoc OldCallOpFPTL =
11344         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11345 
11346     TypeLocBuilder NewCallOpTLBuilder;
11347     SmallVector<QualType, 4> ExceptionStorage;
11348     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11349     QualType NewCallOpType = TransformFunctionProtoType(
11350         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11351         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11352           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11353                                               ExceptionStorage, Changed);
11354         });
11355     if (NewCallOpType.isNull())
11356       return ExprError();
11357     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11358                                                         NewCallOpType);
11359   }
11360 
11361   // Create the local class that will describe the lambda.
11362   CXXRecordDecl *OldClass = E->getLambdaClass();
11363   CXXRecordDecl *Class
11364     = getSema().createLambdaClosureType(E->getIntroducerRange(),
11365                                         NewCallOpTSI,
11366                                         /*KnownDependent=*/false,
11367                                         E->getCaptureDefault());
11368   getDerived().transformedLocalDecl(OldClass, {Class});
11369 
11370   Optional<std::pair<unsigned, Decl*>> Mangling;
11371   if (getDerived().ReplacingOriginal())
11372     Mangling = std::make_pair(OldClass->getLambdaManglingNumber(),
11373                               OldClass->getLambdaContextDecl());
11374 
11375   // Build the call operator.
11376   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11377       Class, E->getIntroducerRange(), NewCallOpTSI,
11378       E->getCallOperator()->getEndLoc(),
11379       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11380       E->getCallOperator()->getConstexprKind(), Mangling);
11381 
11382   LSI->CallOperator = NewCallOperator;
11383 
11384   for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11385        I != NumParams; ++I) {
11386     auto *P = NewCallOperator->getParamDecl(I);
11387     if (P->hasUninstantiatedDefaultArg()) {
11388       EnterExpressionEvaluationContext Eval(
11389           getSema(),
11390           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11391       ExprResult R = getDerived().TransformExpr(
11392           E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11393       P->setDefaultArg(R.get());
11394     }
11395   }
11396 
11397   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11398   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11399 
11400   // Introduce the context of the call operator.
11401   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11402                                  /*NewThisContext*/false);
11403 
11404   // Enter the scope of the lambda.
11405   getSema().buildLambdaScope(LSI, NewCallOperator,
11406                              E->getIntroducerRange(),
11407                              E->getCaptureDefault(),
11408                              E->getCaptureDefaultLoc(),
11409                              E->hasExplicitParameters(),
11410                              E->hasExplicitResultType(),
11411                              E->isMutable());
11412 
11413   bool Invalid = false;
11414 
11415   // Transform captures.
11416   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11417                                  CEnd = E->capture_end();
11418        C != CEnd; ++C) {
11419     // When we hit the first implicit capture, tell Sema that we've finished
11420     // the list of explicit captures.
11421     if (C->isImplicit())
11422       break;
11423 
11424     // Capturing 'this' is trivial.
11425     if (C->capturesThis()) {
11426       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11427                                     /*BuildAndDiagnose*/ true, nullptr,
11428                                     C->getCaptureKind() == LCK_StarThis);
11429       continue;
11430     }
11431     // Captured expression will be recaptured during captured variables
11432     // rebuilding.
11433     if (C->capturesVLAType())
11434       continue;
11435 
11436     // Rebuild init-captures, including the implied field declaration.
11437     if (E->isInitCapture(C)) {
11438       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11439 
11440       VarDecl *OldVD = C->getCapturedVar();
11441       llvm::SmallVector<Decl*, 4> NewVDs;
11442 
11443       for (InitCaptureInfoTy &Info : NewC.Expansions) {
11444         ExprResult Init = Info.first;
11445         QualType InitQualType = Info.second;
11446         if (Init.isInvalid() || InitQualType.isNull()) {
11447           Invalid = true;
11448           break;
11449         }
11450         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11451             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11452             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11453         if (!NewVD) {
11454           Invalid = true;
11455           break;
11456         }
11457         NewVDs.push_back(NewVD);
11458         getSema().addInitCapture(LSI, NewVD);
11459       }
11460 
11461       if (Invalid)
11462         break;
11463 
11464       getDerived().transformedLocalDecl(OldVD, NewVDs);
11465       continue;
11466     }
11467 
11468     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11469 
11470     // Determine the capture kind for Sema.
11471     Sema::TryCaptureKind Kind
11472       = C->isImplicit()? Sema::TryCapture_Implicit
11473                        : C->getCaptureKind() == LCK_ByCopy
11474                            ? Sema::TryCapture_ExplicitByVal
11475                            : Sema::TryCapture_ExplicitByRef;
11476     SourceLocation EllipsisLoc;
11477     if (C->isPackExpansion()) {
11478       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11479       bool ShouldExpand = false;
11480       bool RetainExpansion = false;
11481       Optional<unsigned> NumExpansions;
11482       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11483                                                C->getLocation(),
11484                                                Unexpanded,
11485                                                ShouldExpand, RetainExpansion,
11486                                                NumExpansions)) {
11487         Invalid = true;
11488         continue;
11489       }
11490 
11491       if (ShouldExpand) {
11492         // The transform has determined that we should perform an expansion;
11493         // transform and capture each of the arguments.
11494         // expansion of the pattern. Do so.
11495         VarDecl *Pack = C->getCapturedVar();
11496         for (unsigned I = 0; I != *NumExpansions; ++I) {
11497           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11498           VarDecl *CapturedVar
11499             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11500                                                                Pack));
11501           if (!CapturedVar) {
11502             Invalid = true;
11503             continue;
11504           }
11505 
11506           // Capture the transformed variable.
11507           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11508         }
11509 
11510         // FIXME: Retain a pack expansion if RetainExpansion is true.
11511 
11512         continue;
11513       }
11514 
11515       EllipsisLoc = C->getEllipsisLoc();
11516     }
11517 
11518     // Transform the captured variable.
11519     VarDecl *CapturedVar
11520       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11521                                                          C->getCapturedVar()));
11522     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11523       Invalid = true;
11524       continue;
11525     }
11526 
11527     // Capture the transformed variable.
11528     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11529                                  EllipsisLoc);
11530   }
11531   getSema().finishLambdaExplicitCaptures(LSI);
11532 
11533   // FIXME: Sema's lambda-building mechanism expects us to push an expression
11534   // evaluation context even if we're not transforming the function body.
11535   getSema().PushExpressionEvaluationContext(
11536       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11537 
11538   // Instantiate the body of the lambda expression.
11539   StmtResult Body =
11540       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
11541 
11542   // ActOnLambda* will pop the function scope for us.
11543   FuncScopeCleanup.disable();
11544 
11545   if (Body.isInvalid()) {
11546     SavedContext.pop();
11547     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11548                                /*IsInstantiation=*/true);
11549     return ExprError();
11550   }
11551 
11552   // Copy the LSI before ActOnFinishFunctionBody removes it.
11553   // FIXME: This is dumb. Store the lambda information somewhere that outlives
11554   // the call operator.
11555   auto LSICopy = *LSI;
11556   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11557                                     /*IsInstantiation*/ true);
11558   SavedContext.pop();
11559 
11560   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11561                                    &LSICopy);
11562 }
11563 
11564 template<typename Derived>
11565 StmtResult
11566 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
11567   return TransformStmt(S);
11568 }
11569 
11570 template<typename Derived>
11571 StmtResult
11572 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
11573   // Transform captures.
11574   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11575                                  CEnd = E->capture_end();
11576        C != CEnd; ++C) {
11577     // When we hit the first implicit capture, tell Sema that we've finished
11578     // the list of explicit captures.
11579     if (!C->isImplicit())
11580       continue;
11581 
11582     // Capturing 'this' is trivial.
11583     if (C->capturesThis()) {
11584       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11585                                     /*BuildAndDiagnose*/ true, nullptr,
11586                                     C->getCaptureKind() == LCK_StarThis);
11587       continue;
11588     }
11589     // Captured expression will be recaptured during captured variables
11590     // rebuilding.
11591     if (C->capturesVLAType())
11592       continue;
11593 
11594     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11595     assert(!E->isInitCapture(C) && "implicit init-capture?");
11596 
11597     // Transform the captured variable.
11598     VarDecl *CapturedVar = cast_or_null<VarDecl>(
11599         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
11600     if (!CapturedVar || CapturedVar->isInvalidDecl())
11601       return StmtError();
11602 
11603     // Capture the transformed variable.
11604     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
11605   }
11606 
11607   return S;
11608 }
11609 
11610 template<typename Derived>
11611 ExprResult
11612 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11613                                                   CXXUnresolvedConstructExpr *E) {
11614   TypeSourceInfo *T =
11615       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11616   if (!T)
11617     return ExprError();
11618 
11619   bool ArgumentChanged = false;
11620   SmallVector<Expr*, 8> Args;
11621   Args.reserve(E->arg_size());
11622   {
11623     EnterExpressionEvaluationContext Context(
11624         getSema(), EnterExpressionEvaluationContext::InitList,
11625         E->isListInitialization());
11626     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11627                                     &ArgumentChanged))
11628       return ExprError();
11629   }
11630 
11631   if (!getDerived().AlwaysRebuild() &&
11632       T == E->getTypeSourceInfo() &&
11633       !ArgumentChanged)
11634     return E;
11635 
11636   // FIXME: we're faking the locations of the commas
11637   return getDerived().RebuildCXXUnresolvedConstructExpr(
11638       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11639 }
11640 
11641 template<typename Derived>
11642 ExprResult
11643 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11644                                              CXXDependentScopeMemberExpr *E) {
11645   // Transform the base of the expression.
11646   ExprResult Base((Expr*) nullptr);
11647   Expr *OldBase;
11648   QualType BaseType;
11649   QualType ObjectType;
11650   if (!E->isImplicitAccess()) {
11651     OldBase = E->getBase();
11652     Base = getDerived().TransformExpr(OldBase);
11653     if (Base.isInvalid())
11654       return ExprError();
11655 
11656     // Start the member reference and compute the object's type.
11657     ParsedType ObjectTy;
11658     bool MayBePseudoDestructor = false;
11659     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11660                                                 E->getOperatorLoc(),
11661                                       E->isArrow()? tok::arrow : tok::period,
11662                                                 ObjectTy,
11663                                                 MayBePseudoDestructor);
11664     if (Base.isInvalid())
11665       return ExprError();
11666 
11667     ObjectType = ObjectTy.get();
11668     BaseType = ((Expr*) Base.get())->getType();
11669   } else {
11670     OldBase = nullptr;
11671     BaseType = getDerived().TransformType(E->getBaseType());
11672     ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
11673   }
11674 
11675   // Transform the first part of the nested-name-specifier that qualifies
11676   // the member name.
11677   NamedDecl *FirstQualifierInScope
11678     = getDerived().TransformFirstQualifierInScope(
11679                                             E->getFirstQualifierFoundInScope(),
11680                                             E->getQualifierLoc().getBeginLoc());
11681 
11682   NestedNameSpecifierLoc QualifierLoc;
11683   if (E->getQualifier()) {
11684     QualifierLoc
11685       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11686                                                      ObjectType,
11687                                                      FirstQualifierInScope);
11688     if (!QualifierLoc)
11689       return ExprError();
11690   }
11691 
11692   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11693 
11694   // TODO: If this is a conversion-function-id, verify that the
11695   // destination type name (if present) resolves the same way after
11696   // instantiation as it did in the local scope.
11697 
11698   DeclarationNameInfo NameInfo
11699     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11700   if (!NameInfo.getName())
11701     return ExprError();
11702 
11703   if (!E->hasExplicitTemplateArgs()) {
11704     // This is a reference to a member without an explicitly-specified
11705     // template argument list. Optimize for this common case.
11706     if (!getDerived().AlwaysRebuild() &&
11707         Base.get() == OldBase &&
11708         BaseType == E->getBaseType() &&
11709         QualifierLoc == E->getQualifierLoc() &&
11710         NameInfo.getName() == E->getMember() &&
11711         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11712       return E;
11713 
11714     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11715                                                        BaseType,
11716                                                        E->isArrow(),
11717                                                        E->getOperatorLoc(),
11718                                                        QualifierLoc,
11719                                                        TemplateKWLoc,
11720                                                        FirstQualifierInScope,
11721                                                        NameInfo,
11722                                                        /*TemplateArgs*/nullptr);
11723   }
11724 
11725   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11726   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11727                                               E->getNumTemplateArgs(),
11728                                               TransArgs))
11729     return ExprError();
11730 
11731   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11732                                                      BaseType,
11733                                                      E->isArrow(),
11734                                                      E->getOperatorLoc(),
11735                                                      QualifierLoc,
11736                                                      TemplateKWLoc,
11737                                                      FirstQualifierInScope,
11738                                                      NameInfo,
11739                                                      &TransArgs);
11740 }
11741 
11742 template<typename Derived>
11743 ExprResult
11744 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11745   // Transform the base of the expression.
11746   ExprResult Base((Expr*) nullptr);
11747   QualType BaseType;
11748   if (!Old->isImplicitAccess()) {
11749     Base = getDerived().TransformExpr(Old->getBase());
11750     if (Base.isInvalid())
11751       return ExprError();
11752     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11753                                                      Old->isArrow());
11754     if (Base.isInvalid())
11755       return ExprError();
11756     BaseType = Base.get()->getType();
11757   } else {
11758     BaseType = getDerived().TransformType(Old->getBaseType());
11759   }
11760 
11761   NestedNameSpecifierLoc QualifierLoc;
11762   if (Old->getQualifierLoc()) {
11763     QualifierLoc
11764     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11765     if (!QualifierLoc)
11766       return ExprError();
11767   }
11768 
11769   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11770 
11771   LookupResult R(SemaRef, Old->getMemberNameInfo(),
11772                  Sema::LookupOrdinaryName);
11773 
11774   // Transform the declaration set.
11775   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11776     return ExprError();
11777 
11778   // Determine the naming class.
11779   if (Old->getNamingClass()) {
11780     CXXRecordDecl *NamingClass
11781       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11782                                                           Old->getMemberLoc(),
11783                                                         Old->getNamingClass()));
11784     if (!NamingClass)
11785       return ExprError();
11786 
11787     R.setNamingClass(NamingClass);
11788   }
11789 
11790   TemplateArgumentListInfo TransArgs;
11791   if (Old->hasExplicitTemplateArgs()) {
11792     TransArgs.setLAngleLoc(Old->getLAngleLoc());
11793     TransArgs.setRAngleLoc(Old->getRAngleLoc());
11794     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11795                                                 Old->getNumTemplateArgs(),
11796                                                 TransArgs))
11797       return ExprError();
11798   }
11799 
11800   // FIXME: to do this check properly, we will need to preserve the
11801   // first-qualifier-in-scope here, just in case we had a dependent
11802   // base (and therefore couldn't do the check) and a
11803   // nested-name-qualifier (and therefore could do the lookup).
11804   NamedDecl *FirstQualifierInScope = nullptr;
11805 
11806   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11807                                                   BaseType,
11808                                                   Old->getOperatorLoc(),
11809                                                   Old->isArrow(),
11810                                                   QualifierLoc,
11811                                                   TemplateKWLoc,
11812                                                   FirstQualifierInScope,
11813                                                   R,
11814                                               (Old->hasExplicitTemplateArgs()
11815                                                   ? &TransArgs : nullptr));
11816 }
11817 
11818 template<typename Derived>
11819 ExprResult
11820 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11821   EnterExpressionEvaluationContext Unevaluated(
11822       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11823   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11824   if (SubExpr.isInvalid())
11825     return ExprError();
11826 
11827   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11828     return E;
11829 
11830   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11831 }
11832 
11833 template<typename Derived>
11834 ExprResult
11835 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11836   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11837   if (Pattern.isInvalid())
11838     return ExprError();
11839 
11840   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11841     return E;
11842 
11843   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11844                                            E->getNumExpansions());
11845 }
11846 
11847 template<typename Derived>
11848 ExprResult
11849 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11850   // If E is not value-dependent, then nothing will change when we transform it.
11851   // Note: This is an instantiation-centric view.
11852   if (!E->isValueDependent())
11853     return E;
11854 
11855   EnterExpressionEvaluationContext Unevaluated(
11856       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11857 
11858   ArrayRef<TemplateArgument> PackArgs;
11859   TemplateArgument ArgStorage;
11860 
11861   // Find the argument list to transform.
11862   if (E->isPartiallySubstituted()) {
11863     PackArgs = E->getPartialArguments();
11864   } else if (E->isValueDependent()) {
11865     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
11866     bool ShouldExpand = false;
11867     bool RetainExpansion = false;
11868     Optional<unsigned> NumExpansions;
11869     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
11870                                              Unexpanded,
11871                                              ShouldExpand, RetainExpansion,
11872                                              NumExpansions))
11873       return ExprError();
11874 
11875     // If we need to expand the pack, build a template argument from it and
11876     // expand that.
11877     if (ShouldExpand) {
11878       auto *Pack = E->getPack();
11879       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
11880         ArgStorage = getSema().Context.getPackExpansionType(
11881             getSema().Context.getTypeDeclType(TTPD), None);
11882       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
11883         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
11884       } else {
11885         auto *VD = cast<ValueDecl>(Pack);
11886         ExprResult DRE = getSema().BuildDeclRefExpr(
11887             VD, VD->getType().getNonLValueExprType(getSema().Context),
11888             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
11889             E->getPackLoc());
11890         if (DRE.isInvalid())
11891           return ExprError();
11892         ArgStorage = new (getSema().Context) PackExpansionExpr(
11893             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
11894       }
11895       PackArgs = ArgStorage;
11896     }
11897   }
11898 
11899   // If we're not expanding the pack, just transform the decl.
11900   if (!PackArgs.size()) {
11901     auto *Pack = cast_or_null<NamedDecl>(
11902         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
11903     if (!Pack)
11904       return ExprError();
11905     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
11906                                               E->getPackLoc(),
11907                                               E->getRParenLoc(), None, None);
11908   }
11909 
11910   // Try to compute the result without performing a partial substitution.
11911   Optional<unsigned> Result = 0;
11912   for (const TemplateArgument &Arg : PackArgs) {
11913     if (!Arg.isPackExpansion()) {
11914       Result = *Result + 1;
11915       continue;
11916     }
11917 
11918     TemplateArgumentLoc ArgLoc;
11919     InventTemplateArgumentLoc(Arg, ArgLoc);
11920 
11921     // Find the pattern of the pack expansion.
11922     SourceLocation Ellipsis;
11923     Optional<unsigned> OrigNumExpansions;
11924     TemplateArgumentLoc Pattern =
11925         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
11926                                                           OrigNumExpansions);
11927 
11928     // Substitute under the pack expansion. Do not expand the pack (yet).
11929     TemplateArgumentLoc OutPattern;
11930     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11931     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
11932                                                /*Uneval*/ true))
11933       return true;
11934 
11935     // See if we can determine the number of arguments from the result.
11936     Optional<unsigned> NumExpansions =
11937         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
11938     if (!NumExpansions) {
11939       // No: we must be in an alias template expansion, and we're going to need
11940       // to actually expand the packs.
11941       Result = None;
11942       break;
11943     }
11944 
11945     Result = *Result + *NumExpansions;
11946   }
11947 
11948   // Common case: we could determine the number of expansions without
11949   // substituting.
11950   if (Result)
11951     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11952                                               E->getPackLoc(),
11953                                               E->getRParenLoc(), *Result, None);
11954 
11955   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
11956                                                E->getPackLoc());
11957   {
11958     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
11959     typedef TemplateArgumentLocInventIterator<
11960         Derived, const TemplateArgument*> PackLocIterator;
11961     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
11962                                    PackLocIterator(*this, PackArgs.end()),
11963                                    TransformedPackArgs, /*Uneval*/true))
11964       return ExprError();
11965   }
11966 
11967   // Check whether we managed to fully-expand the pack.
11968   // FIXME: Is it possible for us to do so and not hit the early exit path?
11969   SmallVector<TemplateArgument, 8> Args;
11970   bool PartialSubstitution = false;
11971   for (auto &Loc : TransformedPackArgs.arguments()) {
11972     Args.push_back(Loc.getArgument());
11973     if (Loc.getArgument().isPackExpansion())
11974       PartialSubstitution = true;
11975   }
11976 
11977   if (PartialSubstitution)
11978     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11979                                               E->getPackLoc(),
11980                                               E->getRParenLoc(), None, Args);
11981 
11982   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11983                                             E->getPackLoc(), E->getRParenLoc(),
11984                                             Args.size(), None);
11985 }
11986 
11987 template<typename Derived>
11988 ExprResult
11989 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
11990                                           SubstNonTypeTemplateParmPackExpr *E) {
11991   // Default behavior is to do nothing with this transformation.
11992   return E;
11993 }
11994 
11995 template<typename Derived>
11996 ExprResult
11997 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
11998                                           SubstNonTypeTemplateParmExpr *E) {
11999   // Default behavior is to do nothing with this transformation.
12000   return E;
12001 }
12002 
12003 template<typename Derived>
12004 ExprResult
12005 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12006   // Default behavior is to do nothing with this transformation.
12007   return E;
12008 }
12009 
12010 template<typename Derived>
12011 ExprResult
12012 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12013                                                   MaterializeTemporaryExpr *E) {
12014   return getDerived().TransformExpr(E->GetTemporaryExpr());
12015 }
12016 
12017 template<typename Derived>
12018 ExprResult
12019 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12020   Expr *Pattern = E->getPattern();
12021 
12022   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12023   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12024   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12025 
12026   // Determine whether the set of unexpanded parameter packs can and should
12027   // be expanded.
12028   bool Expand = true;
12029   bool RetainExpansion = false;
12030   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12031                      NumExpansions = OrigNumExpansions;
12032   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12033                                            Pattern->getSourceRange(),
12034                                            Unexpanded,
12035                                            Expand, RetainExpansion,
12036                                            NumExpansions))
12037     return true;
12038 
12039   if (!Expand) {
12040     // Do not expand any packs here, just transform and rebuild a fold
12041     // expression.
12042     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12043 
12044     ExprResult LHS =
12045         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12046     if (LHS.isInvalid())
12047       return true;
12048 
12049     ExprResult RHS =
12050         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12051     if (RHS.isInvalid())
12052       return true;
12053 
12054     if (!getDerived().AlwaysRebuild() &&
12055         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12056       return E;
12057 
12058     return getDerived().RebuildCXXFoldExpr(
12059         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12060         RHS.get(), E->getEndLoc(), NumExpansions);
12061   }
12062 
12063   // The transform has determined that we should perform an elementwise
12064   // expansion of the pattern. Do so.
12065   ExprResult Result = getDerived().TransformExpr(E->getInit());
12066   if (Result.isInvalid())
12067     return true;
12068   bool LeftFold = E->isLeftFold();
12069 
12070   // If we're retaining an expansion for a right fold, it is the innermost
12071   // component and takes the init (if any).
12072   if (!LeftFold && RetainExpansion) {
12073     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12074 
12075     ExprResult Out = getDerived().TransformExpr(Pattern);
12076     if (Out.isInvalid())
12077       return true;
12078 
12079     Result = getDerived().RebuildCXXFoldExpr(
12080         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12081         Result.get(), E->getEndLoc(), OrigNumExpansions);
12082     if (Result.isInvalid())
12083       return true;
12084   }
12085 
12086   for (unsigned I = 0; I != *NumExpansions; ++I) {
12087     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12088         getSema(), LeftFold ? I : *NumExpansions - I - 1);
12089     ExprResult Out = getDerived().TransformExpr(Pattern);
12090     if (Out.isInvalid())
12091       return true;
12092 
12093     if (Out.get()->containsUnexpandedParameterPack()) {
12094       // We still have a pack; retain a pack expansion for this slice.
12095       Result = getDerived().RebuildCXXFoldExpr(
12096           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12097           E->getOperator(), E->getEllipsisLoc(),
12098           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12099           OrigNumExpansions);
12100     } else if (Result.isUsable()) {
12101       // We've got down to a single element; build a binary operator.
12102       Result = getDerived().RebuildBinaryOperator(
12103           E->getEllipsisLoc(), E->getOperator(),
12104           LeftFold ? Result.get() : Out.get(),
12105           LeftFold ? Out.get() : Result.get());
12106     } else
12107       Result = Out;
12108 
12109     if (Result.isInvalid())
12110       return true;
12111   }
12112 
12113   // If we're retaining an expansion for a left fold, it is the outermost
12114   // component and takes the complete expansion so far as its init (if any).
12115   if (LeftFold && RetainExpansion) {
12116     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12117 
12118     ExprResult Out = getDerived().TransformExpr(Pattern);
12119     if (Out.isInvalid())
12120       return true;
12121 
12122     Result = getDerived().RebuildCXXFoldExpr(
12123         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12124         Out.get(), E->getEndLoc(), OrigNumExpansions);
12125     if (Result.isInvalid())
12126       return true;
12127   }
12128 
12129   // If we had no init and an empty pack, and we're not retaining an expansion,
12130   // then produce a fallback value or error.
12131   if (Result.isUnset())
12132     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12133                                                 E->getOperator());
12134 
12135   return Result;
12136 }
12137 
12138 template<typename Derived>
12139 ExprResult
12140 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12141     CXXStdInitializerListExpr *E) {
12142   return getDerived().TransformExpr(E->getSubExpr());
12143 }
12144 
12145 template<typename Derived>
12146 ExprResult
12147 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12148   return SemaRef.MaybeBindToTemporary(E);
12149 }
12150 
12151 template<typename Derived>
12152 ExprResult
12153 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12154   return E;
12155 }
12156 
12157 template<typename Derived>
12158 ExprResult
12159 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12160   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12161   if (SubExpr.isInvalid())
12162     return ExprError();
12163 
12164   if (!getDerived().AlwaysRebuild() &&
12165       SubExpr.get() == E->getSubExpr())
12166     return E;
12167 
12168   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12169 }
12170 
12171 template<typename Derived>
12172 ExprResult
12173 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12174   // Transform each of the elements.
12175   SmallVector<Expr *, 8> Elements;
12176   bool ArgChanged = false;
12177   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12178                                   /*IsCall=*/false, Elements, &ArgChanged))
12179     return ExprError();
12180 
12181   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12182     return SemaRef.MaybeBindToTemporary(E);
12183 
12184   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12185                                               Elements.data(),
12186                                               Elements.size());
12187 }
12188 
12189 template<typename Derived>
12190 ExprResult
12191 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12192                                                     ObjCDictionaryLiteral *E) {
12193   // Transform each of the elements.
12194   SmallVector<ObjCDictionaryElement, 8> Elements;
12195   bool ArgChanged = false;
12196   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12197     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12198 
12199     if (OrigElement.isPackExpansion()) {
12200       // This key/value element is a pack expansion.
12201       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12202       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12203       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12204       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12205 
12206       // Determine whether the set of unexpanded parameter packs can
12207       // and should be expanded.
12208       bool Expand = true;
12209       bool RetainExpansion = false;
12210       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12211       Optional<unsigned> NumExpansions = OrigNumExpansions;
12212       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12213                                OrigElement.Value->getEndLoc());
12214       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12215                                                PatternRange, Unexpanded, Expand,
12216                                                RetainExpansion, NumExpansions))
12217         return ExprError();
12218 
12219       if (!Expand) {
12220         // The transform has determined that we should perform a simple
12221         // transformation on the pack expansion, producing another pack
12222         // expansion.
12223         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12224         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12225         if (Key.isInvalid())
12226           return ExprError();
12227 
12228         if (Key.get() != OrigElement.Key)
12229           ArgChanged = true;
12230 
12231         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12232         if (Value.isInvalid())
12233           return ExprError();
12234 
12235         if (Value.get() != OrigElement.Value)
12236           ArgChanged = true;
12237 
12238         ObjCDictionaryElement Expansion = {
12239           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12240         };
12241         Elements.push_back(Expansion);
12242         continue;
12243       }
12244 
12245       // Record right away that the argument was changed.  This needs
12246       // to happen even if the array expands to nothing.
12247       ArgChanged = true;
12248 
12249       // The transform has determined that we should perform an elementwise
12250       // expansion of the pattern. Do so.
12251       for (unsigned I = 0; I != *NumExpansions; ++I) {
12252         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12253         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12254         if (Key.isInvalid())
12255           return ExprError();
12256 
12257         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12258         if (Value.isInvalid())
12259           return ExprError();
12260 
12261         ObjCDictionaryElement Element = {
12262           Key.get(), Value.get(), SourceLocation(), NumExpansions
12263         };
12264 
12265         // If any unexpanded parameter packs remain, we still have a
12266         // pack expansion.
12267         // FIXME: Can this really happen?
12268         if (Key.get()->containsUnexpandedParameterPack() ||
12269             Value.get()->containsUnexpandedParameterPack())
12270           Element.EllipsisLoc = OrigElement.EllipsisLoc;
12271 
12272         Elements.push_back(Element);
12273       }
12274 
12275       // FIXME: Retain a pack expansion if RetainExpansion is true.
12276 
12277       // We've finished with this pack expansion.
12278       continue;
12279     }
12280 
12281     // Transform and check key.
12282     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12283     if (Key.isInvalid())
12284       return ExprError();
12285 
12286     if (Key.get() != OrigElement.Key)
12287       ArgChanged = true;
12288 
12289     // Transform and check value.
12290     ExprResult Value
12291       = getDerived().TransformExpr(OrigElement.Value);
12292     if (Value.isInvalid())
12293       return ExprError();
12294 
12295     if (Value.get() != OrigElement.Value)
12296       ArgChanged = true;
12297 
12298     ObjCDictionaryElement Element = {
12299       Key.get(), Value.get(), SourceLocation(), None
12300     };
12301     Elements.push_back(Element);
12302   }
12303 
12304   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12305     return SemaRef.MaybeBindToTemporary(E);
12306 
12307   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12308                                                    Elements);
12309 }
12310 
12311 template<typename Derived>
12312 ExprResult
12313 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12314   TypeSourceInfo *EncodedTypeInfo
12315     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12316   if (!EncodedTypeInfo)
12317     return ExprError();
12318 
12319   if (!getDerived().AlwaysRebuild() &&
12320       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12321     return E;
12322 
12323   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12324                                             EncodedTypeInfo,
12325                                             E->getRParenLoc());
12326 }
12327 
12328 template<typename Derived>
12329 ExprResult TreeTransform<Derived>::
12330 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12331   // This is a kind of implicit conversion, and it needs to get dropped
12332   // and recomputed for the same general reasons that ImplicitCastExprs
12333   // do, as well a more specific one: this expression is only valid when
12334   // it appears *immediately* as an argument expression.
12335   return getDerived().TransformExpr(E->getSubExpr());
12336 }
12337 
12338 template<typename Derived>
12339 ExprResult TreeTransform<Derived>::
12340 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12341   TypeSourceInfo *TSInfo
12342     = getDerived().TransformType(E->getTypeInfoAsWritten());
12343   if (!TSInfo)
12344     return ExprError();
12345 
12346   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12347   if (Result.isInvalid())
12348     return ExprError();
12349 
12350   if (!getDerived().AlwaysRebuild() &&
12351       TSInfo == E->getTypeInfoAsWritten() &&
12352       Result.get() == E->getSubExpr())
12353     return E;
12354 
12355   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12356                                       E->getBridgeKeywordLoc(), TSInfo,
12357                                       Result.get());
12358 }
12359 
12360 template <typename Derived>
12361 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12362     ObjCAvailabilityCheckExpr *E) {
12363   return E;
12364 }
12365 
12366 template<typename Derived>
12367 ExprResult
12368 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12369   // Transform arguments.
12370   bool ArgChanged = false;
12371   SmallVector<Expr*, 8> Args;
12372   Args.reserve(E->getNumArgs());
12373   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12374                                   &ArgChanged))
12375     return ExprError();
12376 
12377   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12378     // Class message: transform the receiver type.
12379     TypeSourceInfo *ReceiverTypeInfo
12380       = getDerived().TransformType(E->getClassReceiverTypeInfo());
12381     if (!ReceiverTypeInfo)
12382       return ExprError();
12383 
12384     // If nothing changed, just retain the existing message send.
12385     if (!getDerived().AlwaysRebuild() &&
12386         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12387       return SemaRef.MaybeBindToTemporary(E);
12388 
12389     // Build a new class message send.
12390     SmallVector<SourceLocation, 16> SelLocs;
12391     E->getSelectorLocs(SelLocs);
12392     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12393                                                E->getSelector(),
12394                                                SelLocs,
12395                                                E->getMethodDecl(),
12396                                                E->getLeftLoc(),
12397                                                Args,
12398                                                E->getRightLoc());
12399   }
12400   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12401            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12402     if (!E->getMethodDecl())
12403       return ExprError();
12404 
12405     // Build a new class message send to 'super'.
12406     SmallVector<SourceLocation, 16> SelLocs;
12407     E->getSelectorLocs(SelLocs);
12408     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12409                                                E->getSelector(),
12410                                                SelLocs,
12411                                                E->getReceiverType(),
12412                                                E->getMethodDecl(),
12413                                                E->getLeftLoc(),
12414                                                Args,
12415                                                E->getRightLoc());
12416   }
12417 
12418   // Instance message: transform the receiver
12419   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12420          "Only class and instance messages may be instantiated");
12421   ExprResult Receiver
12422     = getDerived().TransformExpr(E->getInstanceReceiver());
12423   if (Receiver.isInvalid())
12424     return ExprError();
12425 
12426   // If nothing changed, just retain the existing message send.
12427   if (!getDerived().AlwaysRebuild() &&
12428       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12429     return SemaRef.MaybeBindToTemporary(E);
12430 
12431   // Build a new instance message send.
12432   SmallVector<SourceLocation, 16> SelLocs;
12433   E->getSelectorLocs(SelLocs);
12434   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12435                                              E->getSelector(),
12436                                              SelLocs,
12437                                              E->getMethodDecl(),
12438                                              E->getLeftLoc(),
12439                                              Args,
12440                                              E->getRightLoc());
12441 }
12442 
12443 template<typename Derived>
12444 ExprResult
12445 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12446   return E;
12447 }
12448 
12449 template<typename Derived>
12450 ExprResult
12451 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12452   return E;
12453 }
12454 
12455 template<typename Derived>
12456 ExprResult
12457 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12458   // Transform the base expression.
12459   ExprResult Base = getDerived().TransformExpr(E->getBase());
12460   if (Base.isInvalid())
12461     return ExprError();
12462 
12463   // We don't need to transform the ivar; it will never change.
12464 
12465   // If nothing changed, just retain the existing expression.
12466   if (!getDerived().AlwaysRebuild() &&
12467       Base.get() == E->getBase())
12468     return E;
12469 
12470   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12471                                              E->getLocation(),
12472                                              E->isArrow(), E->isFreeIvar());
12473 }
12474 
12475 template<typename Derived>
12476 ExprResult
12477 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12478   // 'super' and types never change. Property never changes. Just
12479   // retain the existing expression.
12480   if (!E->isObjectReceiver())
12481     return E;
12482 
12483   // Transform the base expression.
12484   ExprResult Base = getDerived().TransformExpr(E->getBase());
12485   if (Base.isInvalid())
12486     return ExprError();
12487 
12488   // We don't need to transform the property; it will never change.
12489 
12490   // If nothing changed, just retain the existing expression.
12491   if (!getDerived().AlwaysRebuild() &&
12492       Base.get() == E->getBase())
12493     return E;
12494 
12495   if (E->isExplicitProperty())
12496     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12497                                                    E->getExplicitProperty(),
12498                                                    E->getLocation());
12499 
12500   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12501                                                  SemaRef.Context.PseudoObjectTy,
12502                                                  E->getImplicitPropertyGetter(),
12503                                                  E->getImplicitPropertySetter(),
12504                                                  E->getLocation());
12505 }
12506 
12507 template<typename Derived>
12508 ExprResult
12509 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12510   // Transform the base expression.
12511   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12512   if (Base.isInvalid())
12513     return ExprError();
12514 
12515   // Transform the key expression.
12516   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12517   if (Key.isInvalid())
12518     return ExprError();
12519 
12520   // If nothing changed, just retain the existing expression.
12521   if (!getDerived().AlwaysRebuild() &&
12522       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12523     return E;
12524 
12525   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12526                                                   Base.get(), Key.get(),
12527                                                   E->getAtIndexMethodDecl(),
12528                                                   E->setAtIndexMethodDecl());
12529 }
12530 
12531 template<typename Derived>
12532 ExprResult
12533 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12534   // Transform the base expression.
12535   ExprResult Base = getDerived().TransformExpr(E->getBase());
12536   if (Base.isInvalid())
12537     return ExprError();
12538 
12539   // If nothing changed, just retain the existing expression.
12540   if (!getDerived().AlwaysRebuild() &&
12541       Base.get() == E->getBase())
12542     return E;
12543 
12544   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12545                                          E->getOpLoc(),
12546                                          E->isArrow());
12547 }
12548 
12549 template<typename Derived>
12550 ExprResult
12551 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12552   bool ArgumentChanged = false;
12553   SmallVector<Expr*, 8> SubExprs;
12554   SubExprs.reserve(E->getNumSubExprs());
12555   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12556                                   SubExprs, &ArgumentChanged))
12557     return ExprError();
12558 
12559   if (!getDerived().AlwaysRebuild() &&
12560       !ArgumentChanged)
12561     return E;
12562 
12563   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12564                                                SubExprs,
12565                                                E->getRParenLoc());
12566 }
12567 
12568 template<typename Derived>
12569 ExprResult
12570 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12571   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12572   if (SrcExpr.isInvalid())
12573     return ExprError();
12574 
12575   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12576   if (!Type)
12577     return ExprError();
12578 
12579   if (!getDerived().AlwaysRebuild() &&
12580       Type == E->getTypeSourceInfo() &&
12581       SrcExpr.get() == E->getSrcExpr())
12582     return E;
12583 
12584   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12585                                                SrcExpr.get(), Type,
12586                                                E->getRParenLoc());
12587 }
12588 
12589 template<typename Derived>
12590 ExprResult
12591 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12592   BlockDecl *oldBlock = E->getBlockDecl();
12593 
12594   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12595   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12596 
12597   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12598   blockScope->TheDecl->setBlockMissingReturnType(
12599                          oldBlock->blockMissingReturnType());
12600 
12601   SmallVector<ParmVarDecl*, 4> params;
12602   SmallVector<QualType, 4> paramTypes;
12603 
12604   const FunctionProtoType *exprFunctionType = E->getFunctionType();
12605 
12606   // Parameter substitution.
12607   Sema::ExtParameterInfoBuilder extParamInfos;
12608   if (getDerived().TransformFunctionTypeParams(
12609           E->getCaretLocation(), oldBlock->parameters(), nullptr,
12610           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
12611           extParamInfos)) {
12612     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12613     return ExprError();
12614   }
12615 
12616   QualType exprResultType =
12617       getDerived().TransformType(exprFunctionType->getReturnType());
12618 
12619   auto epi = exprFunctionType->getExtProtoInfo();
12620   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12621 
12622   QualType functionType =
12623     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12624   blockScope->FunctionType = functionType;
12625 
12626   // Set the parameters on the block decl.
12627   if (!params.empty())
12628     blockScope->TheDecl->setParams(params);
12629 
12630   if (!oldBlock->blockMissingReturnType()) {
12631     blockScope->HasImplicitReturnType = false;
12632     blockScope->ReturnType = exprResultType;
12633   }
12634 
12635   // Transform the body
12636   StmtResult body = getDerived().TransformStmt(E->getBody());
12637   if (body.isInvalid()) {
12638     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12639     return ExprError();
12640   }
12641 
12642 #ifndef NDEBUG
12643   // In builds with assertions, make sure that we captured everything we
12644   // captured before.
12645   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12646     for (const auto &I : oldBlock->captures()) {
12647       VarDecl *oldCapture = I.getVariable();
12648 
12649       // Ignore parameter packs.
12650       if (oldCapture->isParameterPack())
12651         continue;
12652 
12653       VarDecl *newCapture =
12654         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12655                                                  oldCapture));
12656       assert(blockScope->CaptureMap.count(newCapture));
12657     }
12658     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12659   }
12660 #endif
12661 
12662   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12663                                     /*Scope=*/nullptr);
12664 }
12665 
12666 template<typename Derived>
12667 ExprResult
12668 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12669   llvm_unreachable("Cannot transform asType expressions yet");
12670 }
12671 
12672 template<typename Derived>
12673 ExprResult
12674 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12675   bool ArgumentChanged = false;
12676   SmallVector<Expr*, 8> SubExprs;
12677   SubExprs.reserve(E->getNumSubExprs());
12678   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12679                                   SubExprs, &ArgumentChanged))
12680     return ExprError();
12681 
12682   if (!getDerived().AlwaysRebuild() &&
12683       !ArgumentChanged)
12684     return E;
12685 
12686   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12687                                         E->getOp(), E->getRParenLoc());
12688 }
12689 
12690 //===----------------------------------------------------------------------===//
12691 // Type reconstruction
12692 //===----------------------------------------------------------------------===//
12693 
12694 template<typename Derived>
12695 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12696                                                     SourceLocation Star) {
12697   return SemaRef.BuildPointerType(PointeeType, Star,
12698                                   getDerived().getBaseEntity());
12699 }
12700 
12701 template<typename Derived>
12702 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12703                                                          SourceLocation Star) {
12704   return SemaRef.BuildBlockPointerType(PointeeType, Star,
12705                                        getDerived().getBaseEntity());
12706 }
12707 
12708 template<typename Derived>
12709 QualType
12710 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12711                                              bool WrittenAsLValue,
12712                                              SourceLocation Sigil) {
12713   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12714                                     Sigil, getDerived().getBaseEntity());
12715 }
12716 
12717 template<typename Derived>
12718 QualType
12719 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12720                                                  QualType ClassType,
12721                                                  SourceLocation Sigil) {
12722   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12723                                         getDerived().getBaseEntity());
12724 }
12725 
12726 template<typename Derived>
12727 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12728            const ObjCTypeParamDecl *Decl,
12729            SourceLocation ProtocolLAngleLoc,
12730            ArrayRef<ObjCProtocolDecl *> Protocols,
12731            ArrayRef<SourceLocation> ProtocolLocs,
12732            SourceLocation ProtocolRAngleLoc) {
12733   return SemaRef.BuildObjCTypeParamType(Decl,
12734                                         ProtocolLAngleLoc, Protocols,
12735                                         ProtocolLocs, ProtocolRAngleLoc,
12736                                         /*FailOnError=*/true);
12737 }
12738 
12739 template<typename Derived>
12740 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12741            QualType BaseType,
12742            SourceLocation Loc,
12743            SourceLocation TypeArgsLAngleLoc,
12744            ArrayRef<TypeSourceInfo *> TypeArgs,
12745            SourceLocation TypeArgsRAngleLoc,
12746            SourceLocation ProtocolLAngleLoc,
12747            ArrayRef<ObjCProtocolDecl *> Protocols,
12748            ArrayRef<SourceLocation> ProtocolLocs,
12749            SourceLocation ProtocolRAngleLoc) {
12750   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12751                                      TypeArgs, TypeArgsRAngleLoc,
12752                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
12753                                      ProtocolRAngleLoc,
12754                                      /*FailOnError=*/true);
12755 }
12756 
12757 template<typename Derived>
12758 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12759            QualType PointeeType,
12760            SourceLocation Star) {
12761   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12762 }
12763 
12764 template<typename Derived>
12765 QualType
12766 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12767                                          ArrayType::ArraySizeModifier SizeMod,
12768                                          const llvm::APInt *Size,
12769                                          Expr *SizeExpr,
12770                                          unsigned IndexTypeQuals,
12771                                          SourceRange BracketsRange) {
12772   if (SizeExpr || !Size)
12773     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12774                                   IndexTypeQuals, BracketsRange,
12775                                   getDerived().getBaseEntity());
12776 
12777   QualType Types[] = {
12778     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12779     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12780     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12781   };
12782   const unsigned NumTypes = llvm::array_lengthof(Types);
12783   QualType SizeType;
12784   for (unsigned I = 0; I != NumTypes; ++I)
12785     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12786       SizeType = Types[I];
12787       break;
12788     }
12789 
12790   // Note that we can return a VariableArrayType here in the case where
12791   // the element type was a dependent VariableArrayType.
12792   IntegerLiteral *ArraySize
12793       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12794                                /*FIXME*/BracketsRange.getBegin());
12795   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12796                                 IndexTypeQuals, BracketsRange,
12797                                 getDerived().getBaseEntity());
12798 }
12799 
12800 template<typename Derived>
12801 QualType
12802 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12803                                                  ArrayType::ArraySizeModifier SizeMod,
12804                                                  const llvm::APInt &Size,
12805                                                  unsigned IndexTypeQuals,
12806                                                  SourceRange BracketsRange) {
12807   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
12808                                         IndexTypeQuals, BracketsRange);
12809 }
12810 
12811 template<typename Derived>
12812 QualType
12813 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12814                                           ArrayType::ArraySizeModifier SizeMod,
12815                                                  unsigned IndexTypeQuals,
12816                                                    SourceRange BracketsRange) {
12817   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12818                                        IndexTypeQuals, BracketsRange);
12819 }
12820 
12821 template<typename Derived>
12822 QualType
12823 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12824                                           ArrayType::ArraySizeModifier SizeMod,
12825                                                  Expr *SizeExpr,
12826                                                  unsigned IndexTypeQuals,
12827                                                  SourceRange BracketsRange) {
12828   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12829                                        SizeExpr,
12830                                        IndexTypeQuals, BracketsRange);
12831 }
12832 
12833 template<typename Derived>
12834 QualType
12835 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12836                                           ArrayType::ArraySizeModifier SizeMod,
12837                                                        Expr *SizeExpr,
12838                                                        unsigned IndexTypeQuals,
12839                                                    SourceRange BracketsRange) {
12840   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12841                                        SizeExpr,
12842                                        IndexTypeQuals, BracketsRange);
12843 }
12844 
12845 template <typename Derived>
12846 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
12847     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
12848   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
12849                                           AttributeLoc);
12850 }
12851 
12852 template <typename Derived>
12853 QualType
12854 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12855                                           unsigned NumElements,
12856                                           VectorType::VectorKind VecKind) {
12857   // FIXME: semantic checking!
12858   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12859 }
12860 
12861 template <typename Derived>
12862 QualType TreeTransform<Derived>::RebuildDependentVectorType(
12863     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
12864     VectorType::VectorKind VecKind) {
12865   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
12866 }
12867 
12868 template<typename Derived>
12869 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
12870                                                       unsigned NumElements,
12871                                                  SourceLocation AttributeLoc) {
12872   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
12873                           NumElements, true);
12874   IntegerLiteral *VectorSize
12875     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
12876                              AttributeLoc);
12877   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
12878 }
12879 
12880 template<typename Derived>
12881 QualType
12882 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
12883                                                            Expr *SizeExpr,
12884                                                   SourceLocation AttributeLoc) {
12885   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
12886 }
12887 
12888 template<typename Derived>
12889 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
12890     QualType T,
12891     MutableArrayRef<QualType> ParamTypes,
12892     const FunctionProtoType::ExtProtoInfo &EPI) {
12893   return SemaRef.BuildFunctionType(T, ParamTypes,
12894                                    getDerived().getBaseLocation(),
12895                                    getDerived().getBaseEntity(),
12896                                    EPI);
12897 }
12898 
12899 template<typename Derived>
12900 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
12901   return SemaRef.Context.getFunctionNoProtoType(T);
12902 }
12903 
12904 template<typename Derived>
12905 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
12906                                                             Decl *D) {
12907   assert(D && "no decl found");
12908   if (D->isInvalidDecl()) return QualType();
12909 
12910   // FIXME: Doesn't account for ObjCInterfaceDecl!
12911   TypeDecl *Ty;
12912   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
12913     // A valid resolved using typename pack expansion decl can have multiple
12914     // UsingDecls, but they must each have exactly one type, and it must be
12915     // the same type in every case. But we must have at least one expansion!
12916     if (UPD->expansions().empty()) {
12917       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
12918           << UPD->isCXXClassMember() << UPD;
12919       return QualType();
12920     }
12921 
12922     // We might still have some unresolved types. Try to pick a resolved type
12923     // if we can. The final instantiation will check that the remaining
12924     // unresolved types instantiate to the type we pick.
12925     QualType FallbackT;
12926     QualType T;
12927     for (auto *E : UPD->expansions()) {
12928       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
12929       if (ThisT.isNull())
12930         continue;
12931       else if (ThisT->getAs<UnresolvedUsingType>())
12932         FallbackT = ThisT;
12933       else if (T.isNull())
12934         T = ThisT;
12935       else
12936         assert(getSema().Context.hasSameType(ThisT, T) &&
12937                "mismatched resolved types in using pack expansion");
12938     }
12939     return T.isNull() ? FallbackT : T;
12940   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
12941     assert(Using->hasTypename() &&
12942            "UnresolvedUsingTypenameDecl transformed to non-typename using");
12943 
12944     // A valid resolved using typename decl points to exactly one type decl.
12945     assert(++Using->shadow_begin() == Using->shadow_end());
12946     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
12947   } else {
12948     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
12949            "UnresolvedUsingTypenameDecl transformed to non-using decl");
12950     Ty = cast<UnresolvedUsingTypenameDecl>(D);
12951   }
12952 
12953   return SemaRef.Context.getTypeDeclType(Ty);
12954 }
12955 
12956 template<typename Derived>
12957 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
12958                                                        SourceLocation Loc) {
12959   return SemaRef.BuildTypeofExprType(E, Loc);
12960 }
12961 
12962 template<typename Derived>
12963 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
12964   return SemaRef.Context.getTypeOfType(Underlying);
12965 }
12966 
12967 template<typename Derived>
12968 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
12969                                                      SourceLocation Loc) {
12970   return SemaRef.BuildDecltypeType(E, Loc);
12971 }
12972 
12973 template<typename Derived>
12974 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
12975                                             UnaryTransformType::UTTKind UKind,
12976                                             SourceLocation Loc) {
12977   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
12978 }
12979 
12980 template<typename Derived>
12981 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
12982                                                       TemplateName Template,
12983                                              SourceLocation TemplateNameLoc,
12984                                      TemplateArgumentListInfo &TemplateArgs) {
12985   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
12986 }
12987 
12988 template<typename Derived>
12989 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
12990                                                    SourceLocation KWLoc) {
12991   return SemaRef.BuildAtomicType(ValueType, KWLoc);
12992 }
12993 
12994 template<typename Derived>
12995 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
12996                                                  SourceLocation KWLoc,
12997                                                  bool isReadPipe) {
12998   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
12999                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
13000 }
13001 
13002 template<typename Derived>
13003 TemplateName
13004 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13005                                             bool TemplateKW,
13006                                             TemplateDecl *Template) {
13007   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13008                                                   Template);
13009 }
13010 
13011 template<typename Derived>
13012 TemplateName
13013 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13014                                             SourceLocation TemplateKWLoc,
13015                                             const IdentifierInfo &Name,
13016                                             SourceLocation NameLoc,
13017                                             QualType ObjectType,
13018                                             NamedDecl *FirstQualifierInScope,
13019                                             bool AllowInjectedClassName) {
13020   UnqualifiedId TemplateName;
13021   TemplateName.setIdentifier(&Name, NameLoc);
13022   Sema::TemplateTy Template;
13023   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13024                                        SS, TemplateKWLoc, TemplateName,
13025                                        ParsedType::make(ObjectType),
13026                                        /*EnteringContext=*/false,
13027                                        Template, AllowInjectedClassName);
13028   return Template.get();
13029 }
13030 
13031 template<typename Derived>
13032 TemplateName
13033 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13034                                             SourceLocation TemplateKWLoc,
13035                                             OverloadedOperatorKind Operator,
13036                                             SourceLocation NameLoc,
13037                                             QualType ObjectType,
13038                                             bool AllowInjectedClassName) {
13039   UnqualifiedId Name;
13040   // FIXME: Bogus location information.
13041   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13042   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13043   Sema::TemplateTy Template;
13044   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13045                                        SS, TemplateKWLoc, Name,
13046                                        ParsedType::make(ObjectType),
13047                                        /*EnteringContext=*/false,
13048                                        Template, AllowInjectedClassName);
13049   return Template.get();
13050 }
13051 
13052 template<typename Derived>
13053 ExprResult
13054 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13055                                                    SourceLocation OpLoc,
13056                                                    Expr *OrigCallee,
13057                                                    Expr *First,
13058                                                    Expr *Second) {
13059   Expr *Callee = OrigCallee->IgnoreParenCasts();
13060   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13061 
13062   if (First->getObjectKind() == OK_ObjCProperty) {
13063     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13064     if (BinaryOperator::isAssignmentOp(Opc))
13065       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13066                                                  First, Second);
13067     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13068     if (Result.isInvalid())
13069       return ExprError();
13070     First = Result.get();
13071   }
13072 
13073   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13074     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13075     if (Result.isInvalid())
13076       return ExprError();
13077     Second = Result.get();
13078   }
13079 
13080   // Determine whether this should be a builtin operation.
13081   if (Op == OO_Subscript) {
13082     if (!First->getType()->isOverloadableType() &&
13083         !Second->getType()->isOverloadableType())
13084       return getSema().CreateBuiltinArraySubscriptExpr(
13085           First, Callee->getBeginLoc(), Second, OpLoc);
13086   } else if (Op == OO_Arrow) {
13087     // -> is never a builtin operation.
13088     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13089   } else if (Second == nullptr || isPostIncDec) {
13090     if (!First->getType()->isOverloadableType() ||
13091         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13092       // The argument is not of overloadable type, or this is an expression
13093       // of the form &Class::member, so try to create a built-in unary
13094       // operation.
13095       UnaryOperatorKind Opc
13096         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13097 
13098       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13099     }
13100   } else {
13101     if (!First->getType()->isOverloadableType() &&
13102         !Second->getType()->isOverloadableType()) {
13103       // Neither of the arguments is an overloadable type, so try to
13104       // create a built-in binary operation.
13105       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13106       ExprResult Result
13107         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13108       if (Result.isInvalid())
13109         return ExprError();
13110 
13111       return Result;
13112     }
13113   }
13114 
13115   // Compute the transformed set of functions (and function templates) to be
13116   // used during overload resolution.
13117   UnresolvedSet<16> Functions;
13118   bool RequiresADL;
13119 
13120   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13121     Functions.append(ULE->decls_begin(), ULE->decls_end());
13122     // If the overload could not be resolved in the template definition
13123     // (because we had a dependent argument), ADL is performed as part of
13124     // template instantiation.
13125     RequiresADL = ULE->requiresADL();
13126   } else {
13127     // If we've resolved this to a particular non-member function, just call
13128     // that function. If we resolved it to a member function,
13129     // CreateOverloaded* will find that function for us.
13130     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13131     if (!isa<CXXMethodDecl>(ND))
13132       Functions.addDecl(ND);
13133     RequiresADL = false;
13134   }
13135 
13136   // Add any functions found via argument-dependent lookup.
13137   Expr *Args[2] = { First, Second };
13138   unsigned NumArgs = 1 + (Second != nullptr);
13139 
13140   // Create the overloaded operator invocation for unary operators.
13141   if (NumArgs == 1 || isPostIncDec) {
13142     UnaryOperatorKind Opc
13143       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13144     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13145                                            RequiresADL);
13146   }
13147 
13148   if (Op == OO_Subscript) {
13149     SourceLocation LBrace;
13150     SourceLocation RBrace;
13151 
13152     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13153         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13154         LBrace = SourceLocation::getFromRawEncoding(
13155                     NameLoc.CXXOperatorName.BeginOpNameLoc);
13156         RBrace = SourceLocation::getFromRawEncoding(
13157                     NameLoc.CXXOperatorName.EndOpNameLoc);
13158     } else {
13159       LBrace = Callee->getBeginLoc();
13160       RBrace = OpLoc;
13161     }
13162 
13163     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13164                                                       First, Second);
13165   }
13166 
13167   // Create the overloaded operator invocation for binary operators.
13168   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13169   ExprResult Result = SemaRef.CreateOverloadedBinOp(
13170       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13171   if (Result.isInvalid())
13172     return ExprError();
13173 
13174   return Result;
13175 }
13176 
13177 template<typename Derived>
13178 ExprResult
13179 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13180                                                      SourceLocation OperatorLoc,
13181                                                        bool isArrow,
13182                                                        CXXScopeSpec &SS,
13183                                                      TypeSourceInfo *ScopeType,
13184                                                        SourceLocation CCLoc,
13185                                                        SourceLocation TildeLoc,
13186                                         PseudoDestructorTypeStorage Destroyed) {
13187   QualType BaseType = Base->getType();
13188   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13189       (!isArrow && !BaseType->getAs<RecordType>()) ||
13190       (isArrow && BaseType->getAs<PointerType>() &&
13191        !BaseType->getAs<PointerType>()->getPointeeType()
13192                                               ->template getAs<RecordType>())){
13193     // This pseudo-destructor expression is still a pseudo-destructor.
13194     return SemaRef.BuildPseudoDestructorExpr(
13195         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13196         CCLoc, TildeLoc, Destroyed);
13197   }
13198 
13199   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13200   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13201                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13202   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13203   NameInfo.setNamedTypeInfo(DestroyedType);
13204 
13205   // The scope type is now known to be a valid nested name specifier
13206   // component. Tack it on to the end of the nested name specifier.
13207   if (ScopeType) {
13208     if (!ScopeType->getType()->getAs<TagType>()) {
13209       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13210                      diag::err_expected_class_or_namespace)
13211           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13212       return ExprError();
13213     }
13214     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13215               CCLoc);
13216   }
13217 
13218   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13219   return getSema().BuildMemberReferenceExpr(Base, BaseType,
13220                                             OperatorLoc, isArrow,
13221                                             SS, TemplateKWLoc,
13222                                             /*FIXME: FirstQualifier*/ nullptr,
13223                                             NameInfo,
13224                                             /*TemplateArgs*/ nullptr,
13225                                             /*S*/nullptr);
13226 }
13227 
13228 template<typename Derived>
13229 StmtResult
13230 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13231   SourceLocation Loc = S->getBeginLoc();
13232   CapturedDecl *CD = S->getCapturedDecl();
13233   unsigned NumParams = CD->getNumParams();
13234   unsigned ContextParamPos = CD->getContextParamPosition();
13235   SmallVector<Sema::CapturedParamNameType, 4> Params;
13236   for (unsigned I = 0; I < NumParams; ++I) {
13237     if (I != ContextParamPos) {
13238       Params.push_back(
13239              std::make_pair(
13240                   CD->getParam(I)->getName(),
13241                   getDerived().TransformType(CD->getParam(I)->getType())));
13242     } else {
13243       Params.push_back(std::make_pair(StringRef(), QualType()));
13244     }
13245   }
13246   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13247                                      S->getCapturedRegionKind(), Params);
13248   StmtResult Body;
13249   {
13250     Sema::CompoundScopeRAII CompoundScope(getSema());
13251     Body = getDerived().TransformStmt(S->getCapturedStmt());
13252   }
13253 
13254   if (Body.isInvalid()) {
13255     getSema().ActOnCapturedRegionError();
13256     return StmtError();
13257   }
13258 
13259   return getSema().ActOnCapturedRegionEnd(Body.get());
13260 }
13261 
13262 } // end namespace clang
13263 
13264 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
13265