xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 2f513db72b034fd5ef7f080b11be5c711c15186a)
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                                 TemplateArgumentListInfo *TemplateArgs) {
2171     CXXScopeSpec SS;
2172     SS.Adopt(QualifierLoc);
2173 
2174     // FIXME: loses template args.
2175 
2176     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
2177   }
2178 
2179   /// Build a new expression in parentheses.
2180   ///
2181   /// By default, performs semantic analysis to build the new expression.
2182   /// Subclasses may override this routine to provide different behavior.
2183   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2184                                     SourceLocation RParen) {
2185     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2186   }
2187 
2188   /// Build a new pseudo-destructor expression.
2189   ///
2190   /// By default, performs semantic analysis to build the new expression.
2191   /// Subclasses may override this routine to provide different behavior.
2192   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2193                                             SourceLocation OperatorLoc,
2194                                             bool isArrow,
2195                                             CXXScopeSpec &SS,
2196                                             TypeSourceInfo *ScopeType,
2197                                             SourceLocation CCLoc,
2198                                             SourceLocation TildeLoc,
2199                                         PseudoDestructorTypeStorage Destroyed);
2200 
2201   /// Build a new unary operator expression.
2202   ///
2203   /// By default, performs semantic analysis to build the new expression.
2204   /// Subclasses may override this routine to provide different behavior.
2205   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2206                                         UnaryOperatorKind Opc,
2207                                         Expr *SubExpr) {
2208     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2209   }
2210 
2211   /// Build a new builtin offsetof expression.
2212   ///
2213   /// By default, performs semantic analysis to build the new expression.
2214   /// Subclasses may override this routine to provide different behavior.
2215   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2216                                  TypeSourceInfo *Type,
2217                                  ArrayRef<Sema::OffsetOfComponent> Components,
2218                                  SourceLocation RParenLoc) {
2219     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2220                                           RParenLoc);
2221   }
2222 
2223   /// Build a new sizeof, alignof or vec_step expression with a
2224   /// type argument.
2225   ///
2226   /// By default, performs semantic analysis to build the new expression.
2227   /// Subclasses may override this routine to provide different behavior.
2228   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2229                                          SourceLocation OpLoc,
2230                                          UnaryExprOrTypeTrait ExprKind,
2231                                          SourceRange R) {
2232     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2233   }
2234 
2235   /// Build a new sizeof, alignof or vec step expression with an
2236   /// expression argument.
2237   ///
2238   /// By default, performs semantic analysis to build the new expression.
2239   /// Subclasses may override this routine to provide different behavior.
2240   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2241                                          UnaryExprOrTypeTrait ExprKind,
2242                                          SourceRange R) {
2243     ExprResult Result
2244       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2245     if (Result.isInvalid())
2246       return ExprError();
2247 
2248     return Result;
2249   }
2250 
2251   /// Build a new array subscript expression.
2252   ///
2253   /// By default, performs semantic analysis to build the new expression.
2254   /// Subclasses may override this routine to provide different behavior.
2255   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2256                                              SourceLocation LBracketLoc,
2257                                              Expr *RHS,
2258                                              SourceLocation RBracketLoc) {
2259     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2260                                              LBracketLoc, RHS,
2261                                              RBracketLoc);
2262   }
2263 
2264   /// Build a new array section expression.
2265   ///
2266   /// By default, performs semantic analysis to build the new expression.
2267   /// Subclasses may override this routine to provide different behavior.
2268   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2269                                         Expr *LowerBound,
2270                                         SourceLocation ColonLoc, Expr *Length,
2271                                         SourceLocation RBracketLoc) {
2272     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2273                                               ColonLoc, Length, RBracketLoc);
2274   }
2275 
2276   /// Build a new call expression.
2277   ///
2278   /// By default, performs semantic analysis to build the new expression.
2279   /// Subclasses may override this routine to provide different behavior.
2280   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2281                                    MultiExprArg Args,
2282                                    SourceLocation RParenLoc,
2283                                    Expr *ExecConfig = nullptr) {
2284     return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2285                                    RParenLoc, ExecConfig);
2286   }
2287 
2288   /// Build a new member access expression.
2289   ///
2290   /// By default, performs semantic analysis to build the new expression.
2291   /// Subclasses may override this routine to provide different behavior.
2292   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2293                                bool isArrow,
2294                                NestedNameSpecifierLoc QualifierLoc,
2295                                SourceLocation TemplateKWLoc,
2296                                const DeclarationNameInfo &MemberNameInfo,
2297                                ValueDecl *Member,
2298                                NamedDecl *FoundDecl,
2299                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2300                                NamedDecl *FirstQualifierInScope) {
2301     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2302                                                                       isArrow);
2303     if (!Member->getDeclName()) {
2304       // We have a reference to an unnamed field.  This is always the
2305       // base of an anonymous struct/union member access, i.e. the
2306       // field is always of record type.
2307       assert(Member->getType()->isRecordType() &&
2308              "unnamed member not of record type?");
2309 
2310       BaseResult =
2311         getSema().PerformObjectMemberConversion(BaseResult.get(),
2312                                                 QualifierLoc.getNestedNameSpecifier(),
2313                                                 FoundDecl, Member);
2314       if (BaseResult.isInvalid())
2315         return ExprError();
2316       Base = BaseResult.get();
2317 
2318       CXXScopeSpec EmptySS;
2319       return getSema().BuildFieldReferenceExpr(
2320           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2321           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2322     }
2323 
2324     CXXScopeSpec SS;
2325     SS.Adopt(QualifierLoc);
2326 
2327     Base = BaseResult.get();
2328     QualType BaseType = Base->getType();
2329 
2330     if (isArrow && !BaseType->isPointerType())
2331       return ExprError();
2332 
2333     // FIXME: this involves duplicating earlier analysis in a lot of
2334     // cases; we should avoid this when possible.
2335     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2336     R.addDecl(FoundDecl);
2337     R.resolveKind();
2338 
2339     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2340                                               SS, TemplateKWLoc,
2341                                               FirstQualifierInScope,
2342                                               R, ExplicitTemplateArgs,
2343                                               /*S*/nullptr);
2344   }
2345 
2346   /// Build a new binary operator expression.
2347   ///
2348   /// By default, performs semantic analysis to build the new expression.
2349   /// Subclasses may override this routine to provide different behavior.
2350   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2351                                          BinaryOperatorKind Opc,
2352                                          Expr *LHS, Expr *RHS) {
2353     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2354   }
2355 
2356   /// Build a new conditional operator expression.
2357   ///
2358   /// By default, performs semantic analysis to build the new expression.
2359   /// Subclasses may override this routine to provide different behavior.
2360   ExprResult RebuildConditionalOperator(Expr *Cond,
2361                                         SourceLocation QuestionLoc,
2362                                         Expr *LHS,
2363                                         SourceLocation ColonLoc,
2364                                         Expr *RHS) {
2365     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2366                                         LHS, RHS);
2367   }
2368 
2369   /// Build a new C-style cast expression.
2370   ///
2371   /// By default, performs semantic analysis to build the new expression.
2372   /// Subclasses may override this routine to provide different behavior.
2373   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2374                                          TypeSourceInfo *TInfo,
2375                                          SourceLocation RParenLoc,
2376                                          Expr *SubExpr) {
2377     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2378                                          SubExpr);
2379   }
2380 
2381   /// Build a new compound literal expression.
2382   ///
2383   /// By default, performs semantic analysis to build the new expression.
2384   /// Subclasses may override this routine to provide different behavior.
2385   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2386                                               TypeSourceInfo *TInfo,
2387                                               SourceLocation RParenLoc,
2388                                               Expr *Init) {
2389     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2390                                               Init);
2391   }
2392 
2393   /// Build a new extended vector element access expression.
2394   ///
2395   /// By default, performs semantic analysis to build the new expression.
2396   /// Subclasses may override this routine to provide different behavior.
2397   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2398                                                SourceLocation OpLoc,
2399                                                SourceLocation AccessorLoc,
2400                                                IdentifierInfo &Accessor) {
2401 
2402     CXXScopeSpec SS;
2403     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2404     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2405                                               OpLoc, /*IsArrow*/ false,
2406                                               SS, SourceLocation(),
2407                                               /*FirstQualifierInScope*/ nullptr,
2408                                               NameInfo,
2409                                               /* TemplateArgs */ nullptr,
2410                                               /*S*/ nullptr);
2411   }
2412 
2413   /// Build a new initializer list expression.
2414   ///
2415   /// By default, performs semantic analysis to build the new expression.
2416   /// Subclasses may override this routine to provide different behavior.
2417   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2418                              MultiExprArg Inits,
2419                              SourceLocation RBraceLoc) {
2420     return SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
2421   }
2422 
2423   /// Build a new designated initializer expression.
2424   ///
2425   /// By default, performs semantic analysis to build the new expression.
2426   /// Subclasses may override this routine to provide different behavior.
2427   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2428                                              MultiExprArg ArrayExprs,
2429                                              SourceLocation EqualOrColonLoc,
2430                                              bool GNUSyntax,
2431                                              Expr *Init) {
2432     ExprResult Result
2433       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2434                                            Init);
2435     if (Result.isInvalid())
2436       return ExprError();
2437 
2438     return Result;
2439   }
2440 
2441   /// Build a new value-initialized expression.
2442   ///
2443   /// By default, builds the implicit value initialization without performing
2444   /// any semantic analysis. Subclasses may override this routine to provide
2445   /// different behavior.
2446   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2447     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2448   }
2449 
2450   /// Build a new \c va_arg expression.
2451   ///
2452   /// By default, performs semantic analysis to build the new expression.
2453   /// Subclasses may override this routine to provide different behavior.
2454   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2455                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2456                                     SourceLocation RParenLoc) {
2457     return getSema().BuildVAArgExpr(BuiltinLoc,
2458                                     SubExpr, TInfo,
2459                                     RParenLoc);
2460   }
2461 
2462   /// Build a new expression list in parentheses.
2463   ///
2464   /// By default, performs semantic analysis to build the new expression.
2465   /// Subclasses may override this routine to provide different behavior.
2466   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2467                                   MultiExprArg SubExprs,
2468                                   SourceLocation RParenLoc) {
2469     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2470   }
2471 
2472   /// Build a new address-of-label expression.
2473   ///
2474   /// By default, performs semantic analysis, using the name of the label
2475   /// rather than attempting to map the label statement itself.
2476   /// Subclasses may override this routine to provide different behavior.
2477   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2478                                   SourceLocation LabelLoc, LabelDecl *Label) {
2479     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2480   }
2481 
2482   /// Build a new GNU statement expression.
2483   ///
2484   /// By default, performs semantic analysis to build the new expression.
2485   /// Subclasses may override this routine to provide different behavior.
2486   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2487                                    Stmt *SubStmt,
2488                                    SourceLocation RParenLoc) {
2489     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2490   }
2491 
2492   /// Build a new __builtin_choose_expr expression.
2493   ///
2494   /// By default, performs semantic analysis to build the new expression.
2495   /// Subclasses may override this routine to provide different behavior.
2496   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2497                                      Expr *Cond, Expr *LHS, Expr *RHS,
2498                                      SourceLocation RParenLoc) {
2499     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2500                                    Cond, LHS, RHS,
2501                                    RParenLoc);
2502   }
2503 
2504   /// Build a new generic selection expression.
2505   ///
2506   /// By default, performs semantic analysis to build the new expression.
2507   /// Subclasses may override this routine to provide different behavior.
2508   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2509                                          SourceLocation DefaultLoc,
2510                                          SourceLocation RParenLoc,
2511                                          Expr *ControllingExpr,
2512                                          ArrayRef<TypeSourceInfo *> Types,
2513                                          ArrayRef<Expr *> Exprs) {
2514     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2515                                                 ControllingExpr, Types, Exprs);
2516   }
2517 
2518   /// Build a new overloaded operator call expression.
2519   ///
2520   /// By default, performs semantic analysis to build the new expression.
2521   /// The semantic analysis provides the behavior of template instantiation,
2522   /// copying with transformations that turn what looks like an overloaded
2523   /// operator call into a use of a builtin operator, performing
2524   /// argument-dependent lookup, etc. Subclasses may override this routine to
2525   /// provide different behavior.
2526   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2527                                               SourceLocation OpLoc,
2528                                               Expr *Callee,
2529                                               Expr *First,
2530                                               Expr *Second);
2531 
2532   /// Build a new C++ "named" cast expression, such as static_cast or
2533   /// reinterpret_cast.
2534   ///
2535   /// By default, this routine dispatches to one of the more-specific routines
2536   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2537   /// Subclasses may override this routine to provide different behavior.
2538   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2539                                            Stmt::StmtClass Class,
2540                                            SourceLocation LAngleLoc,
2541                                            TypeSourceInfo *TInfo,
2542                                            SourceLocation RAngleLoc,
2543                                            SourceLocation LParenLoc,
2544                                            Expr *SubExpr,
2545                                            SourceLocation RParenLoc) {
2546     switch (Class) {
2547     case Stmt::CXXStaticCastExprClass:
2548       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2549                                                    RAngleLoc, LParenLoc,
2550                                                    SubExpr, RParenLoc);
2551 
2552     case Stmt::CXXDynamicCastExprClass:
2553       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2554                                                     RAngleLoc, LParenLoc,
2555                                                     SubExpr, RParenLoc);
2556 
2557     case Stmt::CXXReinterpretCastExprClass:
2558       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2559                                                         RAngleLoc, LParenLoc,
2560                                                         SubExpr,
2561                                                         RParenLoc);
2562 
2563     case Stmt::CXXConstCastExprClass:
2564       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2565                                                    RAngleLoc, LParenLoc,
2566                                                    SubExpr, RParenLoc);
2567 
2568     default:
2569       llvm_unreachable("Invalid C++ named cast");
2570     }
2571   }
2572 
2573   /// Build a new C++ static_cast expression.
2574   ///
2575   /// By default, performs semantic analysis to build the new expression.
2576   /// Subclasses may override this routine to provide different behavior.
2577   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2578                                             SourceLocation LAngleLoc,
2579                                             TypeSourceInfo *TInfo,
2580                                             SourceLocation RAngleLoc,
2581                                             SourceLocation LParenLoc,
2582                                             Expr *SubExpr,
2583                                             SourceLocation RParenLoc) {
2584     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2585                                        TInfo, SubExpr,
2586                                        SourceRange(LAngleLoc, RAngleLoc),
2587                                        SourceRange(LParenLoc, RParenLoc));
2588   }
2589 
2590   /// Build a new C++ dynamic_cast expression.
2591   ///
2592   /// By default, performs semantic analysis to build the new expression.
2593   /// Subclasses may override this routine to provide different behavior.
2594   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2595                                              SourceLocation LAngleLoc,
2596                                              TypeSourceInfo *TInfo,
2597                                              SourceLocation RAngleLoc,
2598                                              SourceLocation LParenLoc,
2599                                              Expr *SubExpr,
2600                                              SourceLocation RParenLoc) {
2601     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2602                                        TInfo, SubExpr,
2603                                        SourceRange(LAngleLoc, RAngleLoc),
2604                                        SourceRange(LParenLoc, RParenLoc));
2605   }
2606 
2607   /// Build a new C++ reinterpret_cast expression.
2608   ///
2609   /// By default, performs semantic analysis to build the new expression.
2610   /// Subclasses may override this routine to provide different behavior.
2611   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2612                                                  SourceLocation LAngleLoc,
2613                                                  TypeSourceInfo *TInfo,
2614                                                  SourceLocation RAngleLoc,
2615                                                  SourceLocation LParenLoc,
2616                                                  Expr *SubExpr,
2617                                                  SourceLocation RParenLoc) {
2618     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2619                                        TInfo, SubExpr,
2620                                        SourceRange(LAngleLoc, RAngleLoc),
2621                                        SourceRange(LParenLoc, RParenLoc));
2622   }
2623 
2624   /// Build a new C++ const_cast expression.
2625   ///
2626   /// By default, performs semantic analysis to build the new expression.
2627   /// Subclasses may override this routine to provide different behavior.
2628   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2629                                            SourceLocation LAngleLoc,
2630                                            TypeSourceInfo *TInfo,
2631                                            SourceLocation RAngleLoc,
2632                                            SourceLocation LParenLoc,
2633                                            Expr *SubExpr,
2634                                            SourceLocation RParenLoc) {
2635     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2636                                        TInfo, SubExpr,
2637                                        SourceRange(LAngleLoc, RAngleLoc),
2638                                        SourceRange(LParenLoc, RParenLoc));
2639   }
2640 
2641   /// Build a new C++ functional-style cast expression.
2642   ///
2643   /// By default, performs semantic analysis to build the new expression.
2644   /// Subclasses may override this routine to provide different behavior.
2645   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2646                                           SourceLocation LParenLoc,
2647                                           Expr *Sub,
2648                                           SourceLocation RParenLoc,
2649                                           bool ListInitialization) {
2650     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2651                                                MultiExprArg(&Sub, 1), RParenLoc,
2652                                                ListInitialization);
2653   }
2654 
2655   /// Build a new C++ __builtin_bit_cast expression.
2656   ///
2657   /// By default, performs semantic analysis to build the new expression.
2658   /// Subclasses may override this routine to provide different behavior.
2659   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2660                                        TypeSourceInfo *TSI, Expr *Sub,
2661                                        SourceLocation RParenLoc) {
2662     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2663   }
2664 
2665   /// Build a new C++ typeid(type) expression.
2666   ///
2667   /// By default, performs semantic analysis to build the new expression.
2668   /// Subclasses may override this routine to provide different behavior.
2669   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2670                                         SourceLocation TypeidLoc,
2671                                         TypeSourceInfo *Operand,
2672                                         SourceLocation RParenLoc) {
2673     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2674                                     RParenLoc);
2675   }
2676 
2677 
2678   /// Build a new C++ typeid(expr) expression.
2679   ///
2680   /// By default, performs semantic analysis to build the new expression.
2681   /// Subclasses may override this routine to provide different behavior.
2682   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2683                                         SourceLocation TypeidLoc,
2684                                         Expr *Operand,
2685                                         SourceLocation RParenLoc) {
2686     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2687                                     RParenLoc);
2688   }
2689 
2690   /// Build a new C++ __uuidof(type) expression.
2691   ///
2692   /// By default, performs semantic analysis to build the new expression.
2693   /// Subclasses may override this routine to provide different behavior.
2694   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2695                                         SourceLocation TypeidLoc,
2696                                         TypeSourceInfo *Operand,
2697                                         SourceLocation RParenLoc) {
2698     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2699                                     RParenLoc);
2700   }
2701 
2702   /// Build a new C++ __uuidof(expr) expression.
2703   ///
2704   /// By default, performs semantic analysis to build the new expression.
2705   /// Subclasses may override this routine to provide different behavior.
2706   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2707                                         SourceLocation TypeidLoc,
2708                                         Expr *Operand,
2709                                         SourceLocation RParenLoc) {
2710     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2711                                     RParenLoc);
2712   }
2713 
2714   /// Build a new C++ "this" expression.
2715   ///
2716   /// By default, builds a new "this" expression without performing any
2717   /// semantic analysis. Subclasses may override this routine to provide
2718   /// different behavior.
2719   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2720                                 QualType ThisType,
2721                                 bool isImplicit) {
2722     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2723   }
2724 
2725   /// Build a new C++ throw expression.
2726   ///
2727   /// By default, performs semantic analysis to build the new expression.
2728   /// Subclasses may override this routine to provide different behavior.
2729   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2730                                  bool IsThrownVariableInScope) {
2731     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2732   }
2733 
2734   /// Build a new C++ default-argument expression.
2735   ///
2736   /// By default, builds a new default-argument expression, which does not
2737   /// require any semantic analysis. Subclasses may override this routine to
2738   /// provide different behavior.
2739   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2740     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2741                                      getSema().CurContext);
2742   }
2743 
2744   /// Build a new C++11 default-initialization expression.
2745   ///
2746   /// By default, builds a new default field initialization expression, which
2747   /// does not require any semantic analysis. Subclasses may override this
2748   /// routine to provide different behavior.
2749   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2750                                        FieldDecl *Field) {
2751     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2752                                       getSema().CurContext);
2753   }
2754 
2755   /// Build a new C++ zero-initialization expression.
2756   ///
2757   /// By default, performs semantic analysis to build the new expression.
2758   /// Subclasses may override this routine to provide different behavior.
2759   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2760                                            SourceLocation LParenLoc,
2761                                            SourceLocation RParenLoc) {
2762     return getSema().BuildCXXTypeConstructExpr(
2763         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2764   }
2765 
2766   /// Build a new C++ "new" expression.
2767   ///
2768   /// By default, performs semantic analysis to build the new expression.
2769   /// Subclasses may override this routine to provide different behavior.
2770   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2771                                bool UseGlobal,
2772                                SourceLocation PlacementLParen,
2773                                MultiExprArg PlacementArgs,
2774                                SourceLocation PlacementRParen,
2775                                SourceRange TypeIdParens,
2776                                QualType AllocatedType,
2777                                TypeSourceInfo *AllocatedTypeInfo,
2778                                Optional<Expr *> ArraySize,
2779                                SourceRange DirectInitRange,
2780                                Expr *Initializer) {
2781     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2782                                  PlacementLParen,
2783                                  PlacementArgs,
2784                                  PlacementRParen,
2785                                  TypeIdParens,
2786                                  AllocatedType,
2787                                  AllocatedTypeInfo,
2788                                  ArraySize,
2789                                  DirectInitRange,
2790                                  Initializer);
2791   }
2792 
2793   /// Build a new C++ "delete" expression.
2794   ///
2795   /// By default, performs semantic analysis to build the new expression.
2796   /// Subclasses may override this routine to provide different behavior.
2797   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2798                                         bool IsGlobalDelete,
2799                                         bool IsArrayForm,
2800                                         Expr *Operand) {
2801     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2802                                     Operand);
2803   }
2804 
2805   /// Build a new type trait expression.
2806   ///
2807   /// By default, performs semantic analysis to build the new expression.
2808   /// Subclasses may override this routine to provide different behavior.
2809   ExprResult RebuildTypeTrait(TypeTrait Trait,
2810                               SourceLocation StartLoc,
2811                               ArrayRef<TypeSourceInfo *> Args,
2812                               SourceLocation RParenLoc) {
2813     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2814   }
2815 
2816   /// Build a new array type trait expression.
2817   ///
2818   /// By default, performs semantic analysis to build the new expression.
2819   /// Subclasses may override this routine to provide different behavior.
2820   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2821                                    SourceLocation StartLoc,
2822                                    TypeSourceInfo *TSInfo,
2823                                    Expr *DimExpr,
2824                                    SourceLocation RParenLoc) {
2825     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2826   }
2827 
2828   /// Build a new expression trait expression.
2829   ///
2830   /// By default, performs semantic analysis to build the new expression.
2831   /// Subclasses may override this routine to provide different behavior.
2832   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2833                                    SourceLocation StartLoc,
2834                                    Expr *Queried,
2835                                    SourceLocation RParenLoc) {
2836     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2837   }
2838 
2839   /// Build a new (previously unresolved) declaration reference
2840   /// expression.
2841   ///
2842   /// By default, performs semantic analysis to build the new expression.
2843   /// Subclasses may override this routine to provide different behavior.
2844   ExprResult RebuildDependentScopeDeclRefExpr(
2845                                           NestedNameSpecifierLoc QualifierLoc,
2846                                           SourceLocation TemplateKWLoc,
2847                                        const DeclarationNameInfo &NameInfo,
2848                               const TemplateArgumentListInfo *TemplateArgs,
2849                                           bool IsAddressOfOperand,
2850                                           TypeSourceInfo **RecoveryTSI) {
2851     CXXScopeSpec SS;
2852     SS.Adopt(QualifierLoc);
2853 
2854     if (TemplateArgs || TemplateKWLoc.isValid())
2855       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2856                                                     TemplateArgs);
2857 
2858     return getSema().BuildQualifiedDeclarationNameExpr(
2859         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2860   }
2861 
2862   /// Build a new template-id expression.
2863   ///
2864   /// By default, performs semantic analysis to build the new expression.
2865   /// Subclasses may override this routine to provide different behavior.
2866   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2867                                    SourceLocation TemplateKWLoc,
2868                                    LookupResult &R,
2869                                    bool RequiresADL,
2870                               const TemplateArgumentListInfo *TemplateArgs) {
2871     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2872                                          TemplateArgs);
2873   }
2874 
2875   /// Build a new object-construction expression.
2876   ///
2877   /// By default, performs semantic analysis to build the new expression.
2878   /// Subclasses may override this routine to provide different behavior.
2879   ExprResult RebuildCXXConstructExpr(QualType T,
2880                                      SourceLocation Loc,
2881                                      CXXConstructorDecl *Constructor,
2882                                      bool IsElidable,
2883                                      MultiExprArg Args,
2884                                      bool HadMultipleCandidates,
2885                                      bool ListInitialization,
2886                                      bool StdInitListInitialization,
2887                                      bool RequiresZeroInit,
2888                              CXXConstructExpr::ConstructionKind ConstructKind,
2889                                      SourceRange ParenRange) {
2890     SmallVector<Expr*, 8> ConvertedArgs;
2891     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2892                                           ConvertedArgs))
2893       return ExprError();
2894 
2895     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2896                                            IsElidable,
2897                                            ConvertedArgs,
2898                                            HadMultipleCandidates,
2899                                            ListInitialization,
2900                                            StdInitListInitialization,
2901                                            RequiresZeroInit, ConstructKind,
2902                                            ParenRange);
2903   }
2904 
2905   /// Build a new implicit construction via inherited constructor
2906   /// expression.
2907   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2908                                              CXXConstructorDecl *Constructor,
2909                                              bool ConstructsVBase,
2910                                              bool InheritedFromVBase) {
2911     return new (getSema().Context) CXXInheritedCtorInitExpr(
2912         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2913   }
2914 
2915   /// Build a new object-construction expression.
2916   ///
2917   /// By default, performs semantic analysis to build the new expression.
2918   /// Subclasses may override this routine to provide different behavior.
2919   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2920                                            SourceLocation LParenOrBraceLoc,
2921                                            MultiExprArg Args,
2922                                            SourceLocation RParenOrBraceLoc,
2923                                            bool ListInitialization) {
2924     return getSema().BuildCXXTypeConstructExpr(
2925         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2926   }
2927 
2928   /// Build a new object-construction expression.
2929   ///
2930   /// By default, performs semantic analysis to build the new expression.
2931   /// Subclasses may override this routine to provide different behavior.
2932   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2933                                                SourceLocation LParenLoc,
2934                                                MultiExprArg Args,
2935                                                SourceLocation RParenLoc,
2936                                                bool ListInitialization) {
2937     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2938                                                RParenLoc, ListInitialization);
2939   }
2940 
2941   /// Build a new member reference expression.
2942   ///
2943   /// By default, performs semantic analysis to build the new expression.
2944   /// Subclasses may override this routine to provide different behavior.
2945   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2946                                                 QualType BaseType,
2947                                                 bool IsArrow,
2948                                                 SourceLocation OperatorLoc,
2949                                           NestedNameSpecifierLoc QualifierLoc,
2950                                                 SourceLocation TemplateKWLoc,
2951                                             NamedDecl *FirstQualifierInScope,
2952                                    const DeclarationNameInfo &MemberNameInfo,
2953                               const TemplateArgumentListInfo *TemplateArgs) {
2954     CXXScopeSpec SS;
2955     SS.Adopt(QualifierLoc);
2956 
2957     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2958                                             OperatorLoc, IsArrow,
2959                                             SS, TemplateKWLoc,
2960                                             FirstQualifierInScope,
2961                                             MemberNameInfo,
2962                                             TemplateArgs, /*S*/nullptr);
2963   }
2964 
2965   /// Build a new member reference expression.
2966   ///
2967   /// By default, performs semantic analysis to build the new expression.
2968   /// Subclasses may override this routine to provide different behavior.
2969   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2970                                          SourceLocation OperatorLoc,
2971                                          bool IsArrow,
2972                                          NestedNameSpecifierLoc QualifierLoc,
2973                                          SourceLocation TemplateKWLoc,
2974                                          NamedDecl *FirstQualifierInScope,
2975                                          LookupResult &R,
2976                                 const TemplateArgumentListInfo *TemplateArgs) {
2977     CXXScopeSpec SS;
2978     SS.Adopt(QualifierLoc);
2979 
2980     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2981                                             OperatorLoc, IsArrow,
2982                                             SS, TemplateKWLoc,
2983                                             FirstQualifierInScope,
2984                                             R, TemplateArgs, /*S*/nullptr);
2985   }
2986 
2987   /// Build a new noexcept expression.
2988   ///
2989   /// By default, performs semantic analysis to build the new expression.
2990   /// Subclasses may override this routine to provide different behavior.
2991   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2992     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2993   }
2994 
2995   /// Build a new expression to compute the length of a parameter pack.
2996   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
2997                                    NamedDecl *Pack,
2998                                    SourceLocation PackLoc,
2999                                    SourceLocation RParenLoc,
3000                                    Optional<unsigned> Length,
3001                                    ArrayRef<TemplateArgument> PartialArgs) {
3002     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3003                                   RParenLoc, Length, PartialArgs);
3004   }
3005 
3006   /// Build a new expression representing a call to a source location
3007   ///  builtin.
3008   ///
3009   /// By default, performs semantic analysis to build the new expression.
3010   /// Subclasses may override this routine to provide different behavior.
3011   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3012                                   SourceLocation BuiltinLoc,
3013                                   SourceLocation RPLoc,
3014                                   DeclContext *ParentContext) {
3015     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3016   }
3017 
3018   /// Build a new Objective-C boxed expression.
3019   ///
3020   /// By default, performs semantic analysis to build the new expression.
3021   /// Subclasses may override this routine to provide different behavior.
3022   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3023     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3024   }
3025 
3026   /// Build a new Objective-C array literal.
3027   ///
3028   /// By default, performs semantic analysis to build the new expression.
3029   /// Subclasses may override this routine to provide different behavior.
3030   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3031                                      Expr **Elements, unsigned NumElements) {
3032     return getSema().BuildObjCArrayLiteral(Range,
3033                                            MultiExprArg(Elements, NumElements));
3034   }
3035 
3036   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3037                                          Expr *Base, Expr *Key,
3038                                          ObjCMethodDecl *getterMethod,
3039                                          ObjCMethodDecl *setterMethod) {
3040     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3041                                                    getterMethod, setterMethod);
3042   }
3043 
3044   /// Build a new Objective-C dictionary literal.
3045   ///
3046   /// By default, performs semantic analysis to build the new expression.
3047   /// Subclasses may override this routine to provide different behavior.
3048   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3049                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3050     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3051   }
3052 
3053   /// Build a new Objective-C \@encode expression.
3054   ///
3055   /// By default, performs semantic analysis to build the new expression.
3056   /// Subclasses may override this routine to provide different behavior.
3057   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3058                                          TypeSourceInfo *EncodeTypeInfo,
3059                                          SourceLocation RParenLoc) {
3060     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3061   }
3062 
3063   /// Build a new Objective-C class message.
3064   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3065                                           Selector Sel,
3066                                           ArrayRef<SourceLocation> SelectorLocs,
3067                                           ObjCMethodDecl *Method,
3068                                           SourceLocation LBracLoc,
3069                                           MultiExprArg Args,
3070                                           SourceLocation RBracLoc) {
3071     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3072                                      ReceiverTypeInfo->getType(),
3073                                      /*SuperLoc=*/SourceLocation(),
3074                                      Sel, Method, LBracLoc, SelectorLocs,
3075                                      RBracLoc, Args);
3076   }
3077 
3078   /// Build a new Objective-C instance message.
3079   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3080                                           Selector Sel,
3081                                           ArrayRef<SourceLocation> SelectorLocs,
3082                                           ObjCMethodDecl *Method,
3083                                           SourceLocation LBracLoc,
3084                                           MultiExprArg Args,
3085                                           SourceLocation RBracLoc) {
3086     return SemaRef.BuildInstanceMessage(Receiver,
3087                                         Receiver->getType(),
3088                                         /*SuperLoc=*/SourceLocation(),
3089                                         Sel, Method, LBracLoc, SelectorLocs,
3090                                         RBracLoc, Args);
3091   }
3092 
3093   /// Build a new Objective-C instance/class message to 'super'.
3094   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3095                                     Selector Sel,
3096                                     ArrayRef<SourceLocation> SelectorLocs,
3097                                     QualType SuperType,
3098                                     ObjCMethodDecl *Method,
3099                                     SourceLocation LBracLoc,
3100                                     MultiExprArg Args,
3101                                     SourceLocation RBracLoc) {
3102     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3103                                           SuperType,
3104                                           SuperLoc,
3105                                           Sel, Method, LBracLoc, SelectorLocs,
3106                                           RBracLoc, Args)
3107                                       : SemaRef.BuildClassMessage(nullptr,
3108                                           SuperType,
3109                                           SuperLoc,
3110                                           Sel, Method, LBracLoc, SelectorLocs,
3111                                           RBracLoc, Args);
3112 
3113 
3114   }
3115 
3116   /// Build a new Objective-C ivar reference expression.
3117   ///
3118   /// By default, performs semantic analysis to build the new expression.
3119   /// Subclasses may override this routine to provide different behavior.
3120   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3121                                           SourceLocation IvarLoc,
3122                                           bool IsArrow, bool IsFreeIvar) {
3123     CXXScopeSpec SS;
3124     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3125     ExprResult Result = getSema().BuildMemberReferenceExpr(
3126         BaseArg, BaseArg->getType(),
3127         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3128         /*FirstQualifierInScope=*/nullptr, NameInfo,
3129         /*TemplateArgs=*/nullptr,
3130         /*S=*/nullptr);
3131     if (IsFreeIvar && Result.isUsable())
3132       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3133     return Result;
3134   }
3135 
3136   /// Build a new Objective-C property reference expression.
3137   ///
3138   /// By default, performs semantic analysis to build the new expression.
3139   /// Subclasses may override this routine to provide different behavior.
3140   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3141                                         ObjCPropertyDecl *Property,
3142                                         SourceLocation PropertyLoc) {
3143     CXXScopeSpec SS;
3144     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3145     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3146                                               /*FIXME:*/PropertyLoc,
3147                                               /*IsArrow=*/false,
3148                                               SS, SourceLocation(),
3149                                               /*FirstQualifierInScope=*/nullptr,
3150                                               NameInfo,
3151                                               /*TemplateArgs=*/nullptr,
3152                                               /*S=*/nullptr);
3153   }
3154 
3155   /// Build a new Objective-C property reference expression.
3156   ///
3157   /// By default, performs semantic analysis to build the new expression.
3158   /// Subclasses may override this routine to provide different behavior.
3159   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3160                                         ObjCMethodDecl *Getter,
3161                                         ObjCMethodDecl *Setter,
3162                                         SourceLocation PropertyLoc) {
3163     // Since these expressions can only be value-dependent, we do not
3164     // need to perform semantic analysis again.
3165     return Owned(
3166       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3167                                                   VK_LValue, OK_ObjCProperty,
3168                                                   PropertyLoc, Base));
3169   }
3170 
3171   /// Build a new Objective-C "isa" expression.
3172   ///
3173   /// By default, performs semantic analysis to build the new expression.
3174   /// Subclasses may override this routine to provide different behavior.
3175   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3176                                 SourceLocation OpLoc, bool IsArrow) {
3177     CXXScopeSpec SS;
3178     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3179     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3180                                               OpLoc, IsArrow,
3181                                               SS, SourceLocation(),
3182                                               /*FirstQualifierInScope=*/nullptr,
3183                                               NameInfo,
3184                                               /*TemplateArgs=*/nullptr,
3185                                               /*S=*/nullptr);
3186   }
3187 
3188   /// Build a new shuffle vector expression.
3189   ///
3190   /// By default, performs semantic analysis to build the new expression.
3191   /// Subclasses may override this routine to provide different behavior.
3192   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3193                                       MultiExprArg SubExprs,
3194                                       SourceLocation RParenLoc) {
3195     // Find the declaration for __builtin_shufflevector
3196     const IdentifierInfo &Name
3197       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3198     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3199     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3200     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3201 
3202     // Build a reference to the __builtin_shufflevector builtin
3203     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3204     Expr *Callee = new (SemaRef.Context)
3205         DeclRefExpr(SemaRef.Context, Builtin, false,
3206                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3207     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3208     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3209                                        CK_BuiltinFnToFnPtr).get();
3210 
3211     // Build the CallExpr
3212     ExprResult TheCall = CallExpr::Create(
3213         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3214         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3215 
3216     // Type-check the __builtin_shufflevector expression.
3217     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3218   }
3219 
3220   /// Build a new convert vector expression.
3221   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3222                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3223                                       SourceLocation RParenLoc) {
3224     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3225                                          BuiltinLoc, RParenLoc);
3226   }
3227 
3228   /// Build a new template argument pack expansion.
3229   ///
3230   /// By default, performs semantic analysis to build a new pack expansion
3231   /// for a template argument. Subclasses may override this routine to provide
3232   /// different behavior.
3233   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3234                                            SourceLocation EllipsisLoc,
3235                                            Optional<unsigned> NumExpansions) {
3236     switch (Pattern.getArgument().getKind()) {
3237     case TemplateArgument::Expression: {
3238       ExprResult Result
3239         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3240                                        EllipsisLoc, NumExpansions);
3241       if (Result.isInvalid())
3242         return TemplateArgumentLoc();
3243 
3244       return TemplateArgumentLoc(Result.get(), Result.get());
3245     }
3246 
3247     case TemplateArgument::Template:
3248       return TemplateArgumentLoc(TemplateArgument(
3249                                           Pattern.getArgument().getAsTemplate(),
3250                                                   NumExpansions),
3251                                  Pattern.getTemplateQualifierLoc(),
3252                                  Pattern.getTemplateNameLoc(),
3253                                  EllipsisLoc);
3254 
3255     case TemplateArgument::Null:
3256     case TemplateArgument::Integral:
3257     case TemplateArgument::Declaration:
3258     case TemplateArgument::Pack:
3259     case TemplateArgument::TemplateExpansion:
3260     case TemplateArgument::NullPtr:
3261       llvm_unreachable("Pack expansion pattern has no parameter packs");
3262 
3263     case TemplateArgument::Type:
3264       if (TypeSourceInfo *Expansion
3265             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3266                                            EllipsisLoc,
3267                                            NumExpansions))
3268         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3269                                    Expansion);
3270       break;
3271     }
3272 
3273     return TemplateArgumentLoc();
3274   }
3275 
3276   /// Build a new expression pack expansion.
3277   ///
3278   /// By default, performs semantic analysis to build a new pack expansion
3279   /// for an expression. Subclasses may override this routine to provide
3280   /// different behavior.
3281   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3282                                   Optional<unsigned> NumExpansions) {
3283     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3284   }
3285 
3286   /// Build a new C++1z fold-expression.
3287   ///
3288   /// By default, performs semantic analysis in order to build a new fold
3289   /// expression.
3290   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3291                                 BinaryOperatorKind Operator,
3292                                 SourceLocation EllipsisLoc, Expr *RHS,
3293                                 SourceLocation RParenLoc,
3294                                 Optional<unsigned> NumExpansions) {
3295     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3296                                       RHS, RParenLoc, NumExpansions);
3297   }
3298 
3299   /// Build an empty C++1z fold-expression with the given operator.
3300   ///
3301   /// By default, produces the fallback value for the fold-expression, or
3302   /// produce an error if there is no fallback value.
3303   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3304                                      BinaryOperatorKind Operator) {
3305     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3306   }
3307 
3308   /// Build a new atomic operation expression.
3309   ///
3310   /// By default, performs semantic analysis to build the new expression.
3311   /// Subclasses may override this routine to provide different behavior.
3312   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
3313                                MultiExprArg SubExprs,
3314                                QualType RetTy,
3315                                AtomicExpr::AtomicOp Op,
3316                                SourceLocation RParenLoc) {
3317     // Just create the expression; there is not any interesting semantic
3318     // analysis here because we can't actually build an AtomicExpr until
3319     // we are sure it is semantically sound.
3320     return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
3321                                             RParenLoc);
3322   }
3323 
3324 private:
3325   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3326                                      QualType ObjectType,
3327                                      NamedDecl *FirstQualifierInScope,
3328                                      CXXScopeSpec &SS);
3329 
3330   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3331                                              QualType ObjectType,
3332                                              NamedDecl *FirstQualifierInScope,
3333                                              CXXScopeSpec &SS);
3334 
3335   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3336                                             NamedDecl *FirstQualifierInScope,
3337                                             CXXScopeSpec &SS);
3338 
3339   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3340                                       DependentNameTypeLoc TL,
3341                                       bool DeducibleTSTContext);
3342 };
3343 
3344 template <typename Derived>
3345 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3346   if (!S)
3347     return S;
3348 
3349   switch (S->getStmtClass()) {
3350   case Stmt::NoStmtClass: break;
3351 
3352   // Transform individual statement nodes
3353   // Pass SDK into statements that can produce a value
3354 #define STMT(Node, Parent)                                              \
3355   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3356 #define VALUESTMT(Node, Parent)                                         \
3357   case Stmt::Node##Class:                                               \
3358     return getDerived().Transform##Node(cast<Node>(S), SDK);
3359 #define ABSTRACT_STMT(Node)
3360 #define EXPR(Node, Parent)
3361 #include "clang/AST/StmtNodes.inc"
3362 
3363   // Transform expressions by calling TransformExpr.
3364 #define STMT(Node, Parent)
3365 #define ABSTRACT_STMT(Stmt)
3366 #define EXPR(Node, Parent) case Stmt::Node##Class:
3367 #include "clang/AST/StmtNodes.inc"
3368     {
3369       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3370 
3371       if (SDK == SDK_StmtExprResult)
3372         E = getSema().ActOnStmtExprResult(E);
3373       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3374     }
3375   }
3376 
3377   return S;
3378 }
3379 
3380 template<typename Derived>
3381 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3382   if (!S)
3383     return S;
3384 
3385   switch (S->getClauseKind()) {
3386   default: break;
3387   // Transform individual clause nodes
3388 #define OPENMP_CLAUSE(Name, Class)                                             \
3389   case OMPC_ ## Name :                                                         \
3390     return getDerived().Transform ## Class(cast<Class>(S));
3391 #include "clang/Basic/OpenMPKinds.def"
3392   }
3393 
3394   return S;
3395 }
3396 
3397 
3398 template<typename Derived>
3399 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3400   if (!E)
3401     return E;
3402 
3403   switch (E->getStmtClass()) {
3404     case Stmt::NoStmtClass: break;
3405 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3406 #define ABSTRACT_STMT(Stmt)
3407 #define EXPR(Node, Parent)                                              \
3408     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3409 #include "clang/AST/StmtNodes.inc"
3410   }
3411 
3412   return E;
3413 }
3414 
3415 template<typename Derived>
3416 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3417                                                         bool NotCopyInit) {
3418   // Initializers are instantiated like expressions, except that various outer
3419   // layers are stripped.
3420   if (!Init)
3421     return Init;
3422 
3423   if (auto *FE = dyn_cast<FullExpr>(Init))
3424     Init = FE->getSubExpr();
3425 
3426   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3427     Init = AIL->getCommonExpr();
3428 
3429   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3430     Init = MTE->GetTemporaryExpr();
3431 
3432   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3433     Init = Binder->getSubExpr();
3434 
3435   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3436     Init = ICE->getSubExprAsWritten();
3437 
3438   if (CXXStdInitializerListExpr *ILE =
3439           dyn_cast<CXXStdInitializerListExpr>(Init))
3440     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3441 
3442   // If this is copy-initialization, we only need to reconstruct
3443   // InitListExprs. Other forms of copy-initialization will be a no-op if
3444   // the initializer is already the right type.
3445   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3446   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3447     return getDerived().TransformExpr(Init);
3448 
3449   // Revert value-initialization back to empty parens.
3450   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3451     SourceRange Parens = VIE->getSourceRange();
3452     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3453                                              Parens.getEnd());
3454   }
3455 
3456   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3457   if (isa<ImplicitValueInitExpr>(Init))
3458     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3459                                              SourceLocation());
3460 
3461   // Revert initialization by constructor back to a parenthesized or braced list
3462   // of expressions. Any other form of initializer can just be reused directly.
3463   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3464     return getDerived().TransformExpr(Init);
3465 
3466   // If the initialization implicitly converted an initializer list to a
3467   // std::initializer_list object, unwrap the std::initializer_list too.
3468   if (Construct && Construct->isStdInitListInitialization())
3469     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3470 
3471   // Enter a list-init context if this was list initialization.
3472   EnterExpressionEvaluationContext Context(
3473       getSema(), EnterExpressionEvaluationContext::InitList,
3474       Construct->isListInitialization());
3475 
3476   SmallVector<Expr*, 8> NewArgs;
3477   bool ArgChanged = false;
3478   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3479                                   /*IsCall*/true, NewArgs, &ArgChanged))
3480     return ExprError();
3481 
3482   // If this was list initialization, revert to syntactic list form.
3483   if (Construct->isListInitialization())
3484     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3485                                         Construct->getEndLoc());
3486 
3487   // Build a ParenListExpr to represent anything else.
3488   SourceRange Parens = Construct->getParenOrBraceRange();
3489   if (Parens.isInvalid()) {
3490     // This was a variable declaration's initialization for which no initializer
3491     // was specified.
3492     assert(NewArgs.empty() &&
3493            "no parens or braces but have direct init with arguments?");
3494     return ExprEmpty();
3495   }
3496   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3497                                            Parens.getEnd());
3498 }
3499 
3500 template<typename Derived>
3501 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3502                                             unsigned NumInputs,
3503                                             bool IsCall,
3504                                       SmallVectorImpl<Expr *> &Outputs,
3505                                             bool *ArgChanged) {
3506   for (unsigned I = 0; I != NumInputs; ++I) {
3507     // If requested, drop call arguments that need to be dropped.
3508     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3509       if (ArgChanged)
3510         *ArgChanged = true;
3511 
3512       break;
3513     }
3514 
3515     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3516       Expr *Pattern = Expansion->getPattern();
3517 
3518       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3519       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3520       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3521 
3522       // Determine whether the set of unexpanded parameter packs can and should
3523       // be expanded.
3524       bool Expand = true;
3525       bool RetainExpansion = false;
3526       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3527       Optional<unsigned> NumExpansions = OrigNumExpansions;
3528       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3529                                                Pattern->getSourceRange(),
3530                                                Unexpanded,
3531                                                Expand, RetainExpansion,
3532                                                NumExpansions))
3533         return true;
3534 
3535       if (!Expand) {
3536         // The transform has determined that we should perform a simple
3537         // transformation on the pack expansion, producing another pack
3538         // expansion.
3539         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3540         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3541         if (OutPattern.isInvalid())
3542           return true;
3543 
3544         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3545                                                 Expansion->getEllipsisLoc(),
3546                                                            NumExpansions);
3547         if (Out.isInvalid())
3548           return true;
3549 
3550         if (ArgChanged)
3551           *ArgChanged = true;
3552         Outputs.push_back(Out.get());
3553         continue;
3554       }
3555 
3556       // Record right away that the argument was changed.  This needs
3557       // to happen even if the array expands to nothing.
3558       if (ArgChanged) *ArgChanged = true;
3559 
3560       // The transform has determined that we should perform an elementwise
3561       // expansion of the pattern. Do so.
3562       for (unsigned I = 0; I != *NumExpansions; ++I) {
3563         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3564         ExprResult Out = getDerived().TransformExpr(Pattern);
3565         if (Out.isInvalid())
3566           return true;
3567 
3568         if (Out.get()->containsUnexpandedParameterPack()) {
3569           Out = getDerived().RebuildPackExpansion(
3570               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3571           if (Out.isInvalid())
3572             return true;
3573         }
3574 
3575         Outputs.push_back(Out.get());
3576       }
3577 
3578       // If we're supposed to retain a pack expansion, do so by temporarily
3579       // forgetting the partially-substituted parameter pack.
3580       if (RetainExpansion) {
3581         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3582 
3583         ExprResult Out = getDerived().TransformExpr(Pattern);
3584         if (Out.isInvalid())
3585           return true;
3586 
3587         Out = getDerived().RebuildPackExpansion(
3588             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3589         if (Out.isInvalid())
3590           return true;
3591 
3592         Outputs.push_back(Out.get());
3593       }
3594 
3595       continue;
3596     }
3597 
3598     ExprResult Result =
3599       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3600              : getDerived().TransformExpr(Inputs[I]);
3601     if (Result.isInvalid())
3602       return true;
3603 
3604     if (Result.get() != Inputs[I] && ArgChanged)
3605       *ArgChanged = true;
3606 
3607     Outputs.push_back(Result.get());
3608   }
3609 
3610   return false;
3611 }
3612 
3613 template <typename Derived>
3614 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3615     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3616   if (Var) {
3617     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3618         getDerived().TransformDefinition(Var->getLocation(), Var));
3619 
3620     if (!ConditionVar)
3621       return Sema::ConditionError();
3622 
3623     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3624   }
3625 
3626   if (Expr) {
3627     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3628 
3629     if (CondExpr.isInvalid())
3630       return Sema::ConditionError();
3631 
3632     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3633   }
3634 
3635   return Sema::ConditionResult();
3636 }
3637 
3638 template<typename Derived>
3639 NestedNameSpecifierLoc
3640 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3641                                                     NestedNameSpecifierLoc NNS,
3642                                                      QualType ObjectType,
3643                                              NamedDecl *FirstQualifierInScope) {
3644   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3645   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3646        Qualifier = Qualifier.getPrefix())
3647     Qualifiers.push_back(Qualifier);
3648 
3649   CXXScopeSpec SS;
3650   while (!Qualifiers.empty()) {
3651     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3652     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3653 
3654     switch (QNNS->getKind()) {
3655     case NestedNameSpecifier::Identifier: {
3656       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3657                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3658       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3659                                               SS, FirstQualifierInScope, false))
3660         return NestedNameSpecifierLoc();
3661     }
3662       break;
3663 
3664     case NestedNameSpecifier::Namespace: {
3665       NamespaceDecl *NS
3666         = cast_or_null<NamespaceDecl>(
3667                                     getDerived().TransformDecl(
3668                                                           Q.getLocalBeginLoc(),
3669                                                        QNNS->getAsNamespace()));
3670       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3671       break;
3672     }
3673 
3674     case NestedNameSpecifier::NamespaceAlias: {
3675       NamespaceAliasDecl *Alias
3676         = cast_or_null<NamespaceAliasDecl>(
3677                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3678                                                  QNNS->getAsNamespaceAlias()));
3679       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3680                 Q.getLocalEndLoc());
3681       break;
3682     }
3683 
3684     case NestedNameSpecifier::Global:
3685       // There is no meaningful transformation that one could perform on the
3686       // global scope.
3687       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3688       break;
3689 
3690     case NestedNameSpecifier::Super: {
3691       CXXRecordDecl *RD =
3692           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3693               SourceLocation(), QNNS->getAsRecordDecl()));
3694       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3695       break;
3696     }
3697 
3698     case NestedNameSpecifier::TypeSpecWithTemplate:
3699     case NestedNameSpecifier::TypeSpec: {
3700       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3701                                               FirstQualifierInScope, SS);
3702 
3703       if (!TL)
3704         return NestedNameSpecifierLoc();
3705 
3706       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3707           (SemaRef.getLangOpts().CPlusPlus11 &&
3708            TL.getType()->isEnumeralType())) {
3709         assert(!TL.getType().hasLocalQualifiers() &&
3710                "Can't get cv-qualifiers here");
3711         if (TL.getType()->isEnumeralType())
3712           SemaRef.Diag(TL.getBeginLoc(),
3713                        diag::warn_cxx98_compat_enum_nested_name_spec);
3714         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3715                   Q.getLocalEndLoc());
3716         break;
3717       }
3718       // If the nested-name-specifier is an invalid type def, don't emit an
3719       // error because a previous error should have already been emitted.
3720       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3721       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3722         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3723           << TL.getType() << SS.getRange();
3724       }
3725       return NestedNameSpecifierLoc();
3726     }
3727     }
3728 
3729     // The qualifier-in-scope and object type only apply to the leftmost entity.
3730     FirstQualifierInScope = nullptr;
3731     ObjectType = QualType();
3732   }
3733 
3734   // Don't rebuild the nested-name-specifier if we don't have to.
3735   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3736       !getDerived().AlwaysRebuild())
3737     return NNS;
3738 
3739   // If we can re-use the source-location data from the original
3740   // nested-name-specifier, do so.
3741   if (SS.location_size() == NNS.getDataLength() &&
3742       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3743     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3744 
3745   // Allocate new nested-name-specifier location information.
3746   return SS.getWithLocInContext(SemaRef.Context);
3747 }
3748 
3749 template<typename Derived>
3750 DeclarationNameInfo
3751 TreeTransform<Derived>
3752 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3753   DeclarationName Name = NameInfo.getName();
3754   if (!Name)
3755     return DeclarationNameInfo();
3756 
3757   switch (Name.getNameKind()) {
3758   case DeclarationName::Identifier:
3759   case DeclarationName::ObjCZeroArgSelector:
3760   case DeclarationName::ObjCOneArgSelector:
3761   case DeclarationName::ObjCMultiArgSelector:
3762   case DeclarationName::CXXOperatorName:
3763   case DeclarationName::CXXLiteralOperatorName:
3764   case DeclarationName::CXXUsingDirective:
3765     return NameInfo;
3766 
3767   case DeclarationName::CXXDeductionGuideName: {
3768     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3769     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3770         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3771     if (!NewTemplate)
3772       return DeclarationNameInfo();
3773 
3774     DeclarationNameInfo NewNameInfo(NameInfo);
3775     NewNameInfo.setName(
3776         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3777     return NewNameInfo;
3778   }
3779 
3780   case DeclarationName::CXXConstructorName:
3781   case DeclarationName::CXXDestructorName:
3782   case DeclarationName::CXXConversionFunctionName: {
3783     TypeSourceInfo *NewTInfo;
3784     CanQualType NewCanTy;
3785     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3786       NewTInfo = getDerived().TransformType(OldTInfo);
3787       if (!NewTInfo)
3788         return DeclarationNameInfo();
3789       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3790     }
3791     else {
3792       NewTInfo = nullptr;
3793       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3794       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3795       if (NewT.isNull())
3796         return DeclarationNameInfo();
3797       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3798     }
3799 
3800     DeclarationName NewName
3801       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3802                                                            NewCanTy);
3803     DeclarationNameInfo NewNameInfo(NameInfo);
3804     NewNameInfo.setName(NewName);
3805     NewNameInfo.setNamedTypeInfo(NewTInfo);
3806     return NewNameInfo;
3807   }
3808   }
3809 
3810   llvm_unreachable("Unknown name kind.");
3811 }
3812 
3813 template<typename Derived>
3814 TemplateName
3815 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3816                                               TemplateName Name,
3817                                               SourceLocation NameLoc,
3818                                               QualType ObjectType,
3819                                               NamedDecl *FirstQualifierInScope,
3820                                               bool AllowInjectedClassName) {
3821   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3822     TemplateDecl *Template = QTN->getTemplateDecl();
3823     assert(Template && "qualified template name must refer to a template");
3824 
3825     TemplateDecl *TransTemplate
3826       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3827                                                               Template));
3828     if (!TransTemplate)
3829       return TemplateName();
3830 
3831     if (!getDerived().AlwaysRebuild() &&
3832         SS.getScopeRep() == QTN->getQualifier() &&
3833         TransTemplate == Template)
3834       return Name;
3835 
3836     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3837                                             TransTemplate);
3838   }
3839 
3840   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3841     if (SS.getScopeRep()) {
3842       // These apply to the scope specifier, not the template.
3843       ObjectType = QualType();
3844       FirstQualifierInScope = nullptr;
3845     }
3846 
3847     if (!getDerived().AlwaysRebuild() &&
3848         SS.getScopeRep() == DTN->getQualifier() &&
3849         ObjectType.isNull())
3850       return Name;
3851 
3852     // FIXME: Preserve the location of the "template" keyword.
3853     SourceLocation TemplateKWLoc = NameLoc;
3854 
3855     if (DTN->isIdentifier()) {
3856       return getDerived().RebuildTemplateName(SS,
3857                                               TemplateKWLoc,
3858                                               *DTN->getIdentifier(),
3859                                               NameLoc,
3860                                               ObjectType,
3861                                               FirstQualifierInScope,
3862                                               AllowInjectedClassName);
3863     }
3864 
3865     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3866                                             DTN->getOperator(), NameLoc,
3867                                             ObjectType, AllowInjectedClassName);
3868   }
3869 
3870   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3871     TemplateDecl *TransTemplate
3872       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3873                                                               Template));
3874     if (!TransTemplate)
3875       return TemplateName();
3876 
3877     if (!getDerived().AlwaysRebuild() &&
3878         TransTemplate == Template)
3879       return Name;
3880 
3881     return TemplateName(TransTemplate);
3882   }
3883 
3884   if (SubstTemplateTemplateParmPackStorage *SubstPack
3885       = Name.getAsSubstTemplateTemplateParmPack()) {
3886     TemplateTemplateParmDecl *TransParam
3887     = cast_or_null<TemplateTemplateParmDecl>(
3888             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3889     if (!TransParam)
3890       return TemplateName();
3891 
3892     if (!getDerived().AlwaysRebuild() &&
3893         TransParam == SubstPack->getParameterPack())
3894       return Name;
3895 
3896     return getDerived().RebuildTemplateName(TransParam,
3897                                             SubstPack->getArgumentPack());
3898   }
3899 
3900   // These should be getting filtered out before they reach the AST.
3901   llvm_unreachable("overloaded function decl survived to here");
3902 }
3903 
3904 template<typename Derived>
3905 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3906                                          const TemplateArgument &Arg,
3907                                          TemplateArgumentLoc &Output) {
3908   SourceLocation Loc = getDerived().getBaseLocation();
3909   switch (Arg.getKind()) {
3910   case TemplateArgument::Null:
3911     llvm_unreachable("null template argument in TreeTransform");
3912     break;
3913 
3914   case TemplateArgument::Type:
3915     Output = TemplateArgumentLoc(Arg,
3916                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3917 
3918     break;
3919 
3920   case TemplateArgument::Template:
3921   case TemplateArgument::TemplateExpansion: {
3922     NestedNameSpecifierLocBuilder Builder;
3923     TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3924     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3925       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3926     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3927       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3928 
3929     if (Arg.getKind() == TemplateArgument::Template)
3930       Output = TemplateArgumentLoc(Arg,
3931                                    Builder.getWithLocInContext(SemaRef.Context),
3932                                    Loc);
3933     else
3934       Output = TemplateArgumentLoc(Arg,
3935                                    Builder.getWithLocInContext(SemaRef.Context),
3936                                    Loc, Loc);
3937 
3938     break;
3939   }
3940 
3941   case TemplateArgument::Expression:
3942     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3943     break;
3944 
3945   case TemplateArgument::Declaration:
3946   case TemplateArgument::Integral:
3947   case TemplateArgument::Pack:
3948   case TemplateArgument::NullPtr:
3949     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3950     break;
3951   }
3952 }
3953 
3954 template<typename Derived>
3955 bool TreeTransform<Derived>::TransformTemplateArgument(
3956                                          const TemplateArgumentLoc &Input,
3957                                          TemplateArgumentLoc &Output, bool Uneval) {
3958   const TemplateArgument &Arg = Input.getArgument();
3959   switch (Arg.getKind()) {
3960   case TemplateArgument::Null:
3961   case TemplateArgument::Integral:
3962   case TemplateArgument::Pack:
3963   case TemplateArgument::Declaration:
3964   case TemplateArgument::NullPtr:
3965     llvm_unreachable("Unexpected TemplateArgument");
3966 
3967   case TemplateArgument::Type: {
3968     TypeSourceInfo *DI = Input.getTypeSourceInfo();
3969     if (!DI)
3970       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3971 
3972     DI = getDerived().TransformType(DI);
3973     if (!DI) return true;
3974 
3975     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3976     return false;
3977   }
3978 
3979   case TemplateArgument::Template: {
3980     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3981     if (QualifierLoc) {
3982       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3983       if (!QualifierLoc)
3984         return true;
3985     }
3986 
3987     CXXScopeSpec SS;
3988     SS.Adopt(QualifierLoc);
3989     TemplateName Template
3990       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3991                                            Input.getTemplateNameLoc());
3992     if (Template.isNull())
3993       return true;
3994 
3995     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3996                                  Input.getTemplateNameLoc());
3997     return false;
3998   }
3999 
4000   case TemplateArgument::TemplateExpansion:
4001     llvm_unreachable("Caller should expand pack expansions");
4002 
4003   case TemplateArgument::Expression: {
4004     // Template argument expressions are constant expressions.
4005     EnterExpressionEvaluationContext Unevaluated(
4006         getSema(),
4007         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4008                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4009         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4010         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4011 
4012     Expr *InputExpr = Input.getSourceExpression();
4013     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4014 
4015     ExprResult E = getDerived().TransformExpr(InputExpr);
4016     E = SemaRef.ActOnConstantExpression(E);
4017     if (E.isInvalid()) return true;
4018     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4019     return false;
4020   }
4021   }
4022 
4023   // Work around bogus GCC warning
4024   return true;
4025 }
4026 
4027 /// Iterator adaptor that invents template argument location information
4028 /// for each of the template arguments in its underlying iterator.
4029 template<typename Derived, typename InputIterator>
4030 class TemplateArgumentLocInventIterator {
4031   TreeTransform<Derived> &Self;
4032   InputIterator Iter;
4033 
4034 public:
4035   typedef TemplateArgumentLoc value_type;
4036   typedef TemplateArgumentLoc reference;
4037   typedef typename std::iterator_traits<InputIterator>::difference_type
4038     difference_type;
4039   typedef std::input_iterator_tag iterator_category;
4040 
4041   class pointer {
4042     TemplateArgumentLoc Arg;
4043 
4044   public:
4045     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4046 
4047     const TemplateArgumentLoc *operator->() const { return &Arg; }
4048   };
4049 
4050   TemplateArgumentLocInventIterator() { }
4051 
4052   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4053                                              InputIterator Iter)
4054     : Self(Self), Iter(Iter) { }
4055 
4056   TemplateArgumentLocInventIterator &operator++() {
4057     ++Iter;
4058     return *this;
4059   }
4060 
4061   TemplateArgumentLocInventIterator operator++(int) {
4062     TemplateArgumentLocInventIterator Old(*this);
4063     ++(*this);
4064     return Old;
4065   }
4066 
4067   reference operator*() const {
4068     TemplateArgumentLoc Result;
4069     Self.InventTemplateArgumentLoc(*Iter, Result);
4070     return Result;
4071   }
4072 
4073   pointer operator->() const { return pointer(**this); }
4074 
4075   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4076                          const TemplateArgumentLocInventIterator &Y) {
4077     return X.Iter == Y.Iter;
4078   }
4079 
4080   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4081                          const TemplateArgumentLocInventIterator &Y) {
4082     return X.Iter != Y.Iter;
4083   }
4084 };
4085 
4086 template<typename Derived>
4087 template<typename InputIterator>
4088 bool TreeTransform<Derived>::TransformTemplateArguments(
4089     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4090     bool Uneval) {
4091   for (; First != Last; ++First) {
4092     TemplateArgumentLoc Out;
4093     TemplateArgumentLoc In = *First;
4094 
4095     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4096       // Unpack argument packs, which we translate them into separate
4097       // arguments.
4098       // FIXME: We could do much better if we could guarantee that the
4099       // TemplateArgumentLocInfo for the pack expansion would be usable for
4100       // all of the template arguments in the argument pack.
4101       typedef TemplateArgumentLocInventIterator<Derived,
4102                                                 TemplateArgument::pack_iterator>
4103         PackLocIterator;
4104       if (TransformTemplateArguments(PackLocIterator(*this,
4105                                                  In.getArgument().pack_begin()),
4106                                      PackLocIterator(*this,
4107                                                    In.getArgument().pack_end()),
4108                                      Outputs, Uneval))
4109         return true;
4110 
4111       continue;
4112     }
4113 
4114     if (In.getArgument().isPackExpansion()) {
4115       // We have a pack expansion, for which we will be substituting into
4116       // the pattern.
4117       SourceLocation Ellipsis;
4118       Optional<unsigned> OrigNumExpansions;
4119       TemplateArgumentLoc Pattern
4120         = getSema().getTemplateArgumentPackExpansionPattern(
4121               In, Ellipsis, OrigNumExpansions);
4122 
4123       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4124       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4125       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4126 
4127       // Determine whether the set of unexpanded parameter packs can and should
4128       // be expanded.
4129       bool Expand = true;
4130       bool RetainExpansion = false;
4131       Optional<unsigned> NumExpansions = OrigNumExpansions;
4132       if (getDerived().TryExpandParameterPacks(Ellipsis,
4133                                                Pattern.getSourceRange(),
4134                                                Unexpanded,
4135                                                Expand,
4136                                                RetainExpansion,
4137                                                NumExpansions))
4138         return true;
4139 
4140       if (!Expand) {
4141         // The transform has determined that we should perform a simple
4142         // transformation on the pack expansion, producing another pack
4143         // expansion.
4144         TemplateArgumentLoc OutPattern;
4145         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4146         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4147           return true;
4148 
4149         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4150                                                 NumExpansions);
4151         if (Out.getArgument().isNull())
4152           return true;
4153 
4154         Outputs.addArgument(Out);
4155         continue;
4156       }
4157 
4158       // The transform has determined that we should perform an elementwise
4159       // expansion of the pattern. Do so.
4160       for (unsigned I = 0; I != *NumExpansions; ++I) {
4161         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4162 
4163         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4164           return true;
4165 
4166         if (Out.getArgument().containsUnexpandedParameterPack()) {
4167           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4168                                                   OrigNumExpansions);
4169           if (Out.getArgument().isNull())
4170             return true;
4171         }
4172 
4173         Outputs.addArgument(Out);
4174       }
4175 
4176       // If we're supposed to retain a pack expansion, do so by temporarily
4177       // forgetting the partially-substituted parameter pack.
4178       if (RetainExpansion) {
4179         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4180 
4181         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4182           return true;
4183 
4184         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4185                                                 OrigNumExpansions);
4186         if (Out.getArgument().isNull())
4187           return true;
4188 
4189         Outputs.addArgument(Out);
4190       }
4191 
4192       continue;
4193     }
4194 
4195     // The simple case:
4196     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4197       return true;
4198 
4199     Outputs.addArgument(Out);
4200   }
4201 
4202   return false;
4203 
4204 }
4205 
4206 //===----------------------------------------------------------------------===//
4207 // Type transformation
4208 //===----------------------------------------------------------------------===//
4209 
4210 template<typename Derived>
4211 QualType TreeTransform<Derived>::TransformType(QualType T) {
4212   if (getDerived().AlreadyTransformed(T))
4213     return T;
4214 
4215   // Temporary workaround.  All of these transformations should
4216   // eventually turn into transformations on TypeLocs.
4217   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4218                                                 getDerived().getBaseLocation());
4219 
4220   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4221 
4222   if (!NewDI)
4223     return QualType();
4224 
4225   return NewDI->getType();
4226 }
4227 
4228 template<typename Derived>
4229 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4230   // Refine the base location to the type's location.
4231   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4232                        getDerived().getBaseEntity());
4233   if (getDerived().AlreadyTransformed(DI->getType()))
4234     return DI;
4235 
4236   TypeLocBuilder TLB;
4237 
4238   TypeLoc TL = DI->getTypeLoc();
4239   TLB.reserve(TL.getFullDataSize());
4240 
4241   QualType Result = getDerived().TransformType(TLB, TL);
4242   if (Result.isNull())
4243     return nullptr;
4244 
4245   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4246 }
4247 
4248 template<typename Derived>
4249 QualType
4250 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4251   switch (T.getTypeLocClass()) {
4252 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4253 #define TYPELOC(CLASS, PARENT)                                                 \
4254   case TypeLoc::CLASS:                                                         \
4255     return getDerived().Transform##CLASS##Type(TLB,                            \
4256                                                T.castAs<CLASS##TypeLoc>());
4257 #include "clang/AST/TypeLocNodes.def"
4258   }
4259 
4260   llvm_unreachable("unhandled type loc!");
4261 }
4262 
4263 template<typename Derived>
4264 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4265   if (!isa<DependentNameType>(T))
4266     return TransformType(T);
4267 
4268   if (getDerived().AlreadyTransformed(T))
4269     return T;
4270   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4271                                                 getDerived().getBaseLocation());
4272   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4273   return NewDI ? NewDI->getType() : QualType();
4274 }
4275 
4276 template<typename Derived>
4277 TypeSourceInfo *
4278 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4279   if (!isa<DependentNameType>(DI->getType()))
4280     return TransformType(DI);
4281 
4282   // Refine the base location to the type's location.
4283   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4284                        getDerived().getBaseEntity());
4285   if (getDerived().AlreadyTransformed(DI->getType()))
4286     return DI;
4287 
4288   TypeLocBuilder TLB;
4289 
4290   TypeLoc TL = DI->getTypeLoc();
4291   TLB.reserve(TL.getFullDataSize());
4292 
4293   auto QTL = TL.getAs<QualifiedTypeLoc>();
4294   if (QTL)
4295     TL = QTL.getUnqualifiedLoc();
4296 
4297   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4298 
4299   QualType Result = getDerived().TransformDependentNameType(
4300       TLB, DNTL, /*DeducedTSTContext*/true);
4301   if (Result.isNull())
4302     return nullptr;
4303 
4304   if (QTL) {
4305     Result = getDerived().RebuildQualifiedType(Result, QTL);
4306     if (Result.isNull())
4307       return nullptr;
4308     TLB.TypeWasModifiedSafely(Result);
4309   }
4310 
4311   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4312 }
4313 
4314 template<typename Derived>
4315 QualType
4316 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4317                                                QualifiedTypeLoc T) {
4318   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4319   if (Result.isNull())
4320     return QualType();
4321 
4322   Result = getDerived().RebuildQualifiedType(Result, T);
4323 
4324   if (Result.isNull())
4325     return QualType();
4326 
4327   // RebuildQualifiedType might have updated the type, but not in a way
4328   // that invalidates the TypeLoc. (There's no location information for
4329   // qualifiers.)
4330   TLB.TypeWasModifiedSafely(Result);
4331 
4332   return Result;
4333 }
4334 
4335 template <typename Derived>
4336 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4337                                                       QualifiedTypeLoc TL) {
4338 
4339   SourceLocation Loc = TL.getBeginLoc();
4340   Qualifiers Quals = TL.getType().getLocalQualifiers();
4341 
4342   if (((T.getAddressSpace() != LangAS::Default &&
4343         Quals.getAddressSpace() != LangAS::Default)) &&
4344       T.getAddressSpace() != Quals.getAddressSpace()) {
4345     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4346         << TL.getType() << T;
4347     return QualType();
4348   }
4349 
4350   // C++ [dcl.fct]p7:
4351   //   [When] adding cv-qualifications on top of the function type [...] the
4352   //   cv-qualifiers are ignored.
4353   if (T->isFunctionType()) {
4354     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4355                                                      Quals.getAddressSpace());
4356     return T;
4357   }
4358 
4359   // C++ [dcl.ref]p1:
4360   //   when the cv-qualifiers are introduced through the use of a typedef-name
4361   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4362   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4363   // applied to a reference type.
4364   if (T->isReferenceType()) {
4365     // The only qualifier that applies to a reference type is restrict.
4366     if (!Quals.hasRestrict())
4367       return T;
4368     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4369   }
4370 
4371   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4372   // resulting type.
4373   if (Quals.hasObjCLifetime()) {
4374     if (!T->isObjCLifetimeType() && !T->isDependentType())
4375       Quals.removeObjCLifetime();
4376     else if (T.getObjCLifetime()) {
4377       // Objective-C ARC:
4378       //   A lifetime qualifier applied to a substituted template parameter
4379       //   overrides the lifetime qualifier from the template argument.
4380       const AutoType *AutoTy;
4381       if (const SubstTemplateTypeParmType *SubstTypeParam
4382                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4383         QualType Replacement = SubstTypeParam->getReplacementType();
4384         Qualifiers Qs = Replacement.getQualifiers();
4385         Qs.removeObjCLifetime();
4386         Replacement = SemaRef.Context.getQualifiedType(
4387             Replacement.getUnqualifiedType(), Qs);
4388         T = SemaRef.Context.getSubstTemplateTypeParmType(
4389             SubstTypeParam->getReplacedParameter(), Replacement);
4390       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4391         // 'auto' types behave the same way as template parameters.
4392         QualType Deduced = AutoTy->getDeducedType();
4393         Qualifiers Qs = Deduced.getQualifiers();
4394         Qs.removeObjCLifetime();
4395         Deduced =
4396             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4397         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4398                                         AutoTy->isDependentType());
4399       } else {
4400         // Otherwise, complain about the addition of a qualifier to an
4401         // already-qualified type.
4402         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4403         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4404         Quals.removeObjCLifetime();
4405       }
4406     }
4407   }
4408 
4409   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4410 }
4411 
4412 template<typename Derived>
4413 TypeLoc
4414 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4415                                                    QualType ObjectType,
4416                                                    NamedDecl *UnqualLookup,
4417                                                    CXXScopeSpec &SS) {
4418   if (getDerived().AlreadyTransformed(TL.getType()))
4419     return TL;
4420 
4421   TypeSourceInfo *TSI =
4422       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4423   if (TSI)
4424     return TSI->getTypeLoc();
4425   return TypeLoc();
4426 }
4427 
4428 template<typename Derived>
4429 TypeSourceInfo *
4430 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4431                                                    QualType ObjectType,
4432                                                    NamedDecl *UnqualLookup,
4433                                                    CXXScopeSpec &SS) {
4434   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4435     return TSInfo;
4436 
4437   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4438                                    UnqualLookup, SS);
4439 }
4440 
4441 template <typename Derived>
4442 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4443     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4444     CXXScopeSpec &SS) {
4445   QualType T = TL.getType();
4446   assert(!getDerived().AlreadyTransformed(T));
4447 
4448   TypeLocBuilder TLB;
4449   QualType Result;
4450 
4451   if (isa<TemplateSpecializationType>(T)) {
4452     TemplateSpecializationTypeLoc SpecTL =
4453         TL.castAs<TemplateSpecializationTypeLoc>();
4454 
4455     TemplateName Template = getDerived().TransformTemplateName(
4456         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4457         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4458     if (Template.isNull())
4459       return nullptr;
4460 
4461     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4462                                                               Template);
4463   } else if (isa<DependentTemplateSpecializationType>(T)) {
4464     DependentTemplateSpecializationTypeLoc SpecTL =
4465         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4466 
4467     TemplateName Template
4468       = getDerived().RebuildTemplateName(SS,
4469                                          SpecTL.getTemplateKeywordLoc(),
4470                                          *SpecTL.getTypePtr()->getIdentifier(),
4471                                          SpecTL.getTemplateNameLoc(),
4472                                          ObjectType, UnqualLookup,
4473                                          /*AllowInjectedClassName*/true);
4474     if (Template.isNull())
4475       return nullptr;
4476 
4477     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4478                                                                        SpecTL,
4479                                                                        Template,
4480                                                                        SS);
4481   } else {
4482     // Nothing special needs to be done for these.
4483     Result = getDerived().TransformType(TLB, TL);
4484   }
4485 
4486   if (Result.isNull())
4487     return nullptr;
4488 
4489   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4490 }
4491 
4492 template <class TyLoc> static inline
4493 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4494   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4495   NewT.setNameLoc(T.getNameLoc());
4496   return T.getType();
4497 }
4498 
4499 template<typename Derived>
4500 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4501                                                       BuiltinTypeLoc T) {
4502   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4503   NewT.setBuiltinLoc(T.getBuiltinLoc());
4504   if (T.needsExtraLocalData())
4505     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4506   return T.getType();
4507 }
4508 
4509 template<typename Derived>
4510 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4511                                                       ComplexTypeLoc T) {
4512   // FIXME: recurse?
4513   return TransformTypeSpecType(TLB, T);
4514 }
4515 
4516 template <typename Derived>
4517 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4518                                                        AdjustedTypeLoc TL) {
4519   // Adjustments applied during transformation are handled elsewhere.
4520   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4521 }
4522 
4523 template<typename Derived>
4524 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4525                                                       DecayedTypeLoc TL) {
4526   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4527   if (OriginalType.isNull())
4528     return QualType();
4529 
4530   QualType Result = TL.getType();
4531   if (getDerived().AlwaysRebuild() ||
4532       OriginalType != TL.getOriginalLoc().getType())
4533     Result = SemaRef.Context.getDecayedType(OriginalType);
4534   TLB.push<DecayedTypeLoc>(Result);
4535   // Nothing to set for DecayedTypeLoc.
4536   return Result;
4537 }
4538 
4539 /// Helper to deduce addr space of a pointee type in OpenCL mode.
4540 /// If the type is updated it will be overwritten in PointeeType param.
4541 static void deduceOpenCLPointeeAddrSpace(Sema &SemaRef, QualType &PointeeType) {
4542   if (PointeeType.getAddressSpace() == LangAS::Default)
4543     PointeeType = SemaRef.Context.getAddrSpaceQualType(PointeeType,
4544                                                        LangAS::opencl_generic);
4545 }
4546 
4547 template<typename Derived>
4548 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4549                                                       PointerTypeLoc TL) {
4550   QualType PointeeType
4551     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4552   if (PointeeType.isNull())
4553     return QualType();
4554 
4555   if (SemaRef.getLangOpts().OpenCL)
4556     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4557 
4558   QualType Result = TL.getType();
4559   if (PointeeType->getAs<ObjCObjectType>()) {
4560     // A dependent pointer type 'T *' has is being transformed such
4561     // that an Objective-C class type is being replaced for 'T'. The
4562     // resulting pointer type is an ObjCObjectPointerType, not a
4563     // PointerType.
4564     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4565 
4566     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4567     NewT.setStarLoc(TL.getStarLoc());
4568     return Result;
4569   }
4570 
4571   if (getDerived().AlwaysRebuild() ||
4572       PointeeType != TL.getPointeeLoc().getType()) {
4573     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4574     if (Result.isNull())
4575       return QualType();
4576   }
4577 
4578   // Objective-C ARC can add lifetime qualifiers to the type that we're
4579   // pointing to.
4580   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4581 
4582   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4583   NewT.setSigilLoc(TL.getSigilLoc());
4584   return Result;
4585 }
4586 
4587 template<typename Derived>
4588 QualType
4589 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4590                                                   BlockPointerTypeLoc TL) {
4591   QualType PointeeType
4592     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4593   if (PointeeType.isNull())
4594     return QualType();
4595 
4596   if (SemaRef.getLangOpts().OpenCL)
4597     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4598 
4599   QualType Result = TL.getType();
4600   if (getDerived().AlwaysRebuild() ||
4601       PointeeType != TL.getPointeeLoc().getType()) {
4602     Result = getDerived().RebuildBlockPointerType(PointeeType,
4603                                                   TL.getSigilLoc());
4604     if (Result.isNull())
4605       return QualType();
4606   }
4607 
4608   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4609   NewT.setSigilLoc(TL.getSigilLoc());
4610   return Result;
4611 }
4612 
4613 /// Transforms a reference type.  Note that somewhat paradoxically we
4614 /// don't care whether the type itself is an l-value type or an r-value
4615 /// type;  we only care if the type was *written* as an l-value type
4616 /// or an r-value type.
4617 template<typename Derived>
4618 QualType
4619 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4620                                                ReferenceTypeLoc TL) {
4621   const ReferenceType *T = TL.getTypePtr();
4622 
4623   // Note that this works with the pointee-as-written.
4624   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4625   if (PointeeType.isNull())
4626     return QualType();
4627 
4628   if (SemaRef.getLangOpts().OpenCL)
4629     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4630 
4631   QualType Result = TL.getType();
4632   if (getDerived().AlwaysRebuild() ||
4633       PointeeType != T->getPointeeTypeAsWritten()) {
4634     Result = getDerived().RebuildReferenceType(PointeeType,
4635                                                T->isSpelledAsLValue(),
4636                                                TL.getSigilLoc());
4637     if (Result.isNull())
4638       return QualType();
4639   }
4640 
4641   // Objective-C ARC can add lifetime qualifiers to the type that we're
4642   // referring to.
4643   TLB.TypeWasModifiedSafely(
4644                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4645 
4646   // r-value references can be rebuilt as l-value references.
4647   ReferenceTypeLoc NewTL;
4648   if (isa<LValueReferenceType>(Result))
4649     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4650   else
4651     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4652   NewTL.setSigilLoc(TL.getSigilLoc());
4653 
4654   return Result;
4655 }
4656 
4657 template<typename Derived>
4658 QualType
4659 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4660                                                  LValueReferenceTypeLoc TL) {
4661   return TransformReferenceType(TLB, TL);
4662 }
4663 
4664 template<typename Derived>
4665 QualType
4666 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4667                                                  RValueReferenceTypeLoc TL) {
4668   return TransformReferenceType(TLB, TL);
4669 }
4670 
4671 template<typename Derived>
4672 QualType
4673 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4674                                                    MemberPointerTypeLoc TL) {
4675   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4676   if (PointeeType.isNull())
4677     return QualType();
4678 
4679   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4680   TypeSourceInfo *NewClsTInfo = nullptr;
4681   if (OldClsTInfo) {
4682     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4683     if (!NewClsTInfo)
4684       return QualType();
4685   }
4686 
4687   const MemberPointerType *T = TL.getTypePtr();
4688   QualType OldClsType = QualType(T->getClass(), 0);
4689   QualType NewClsType;
4690   if (NewClsTInfo)
4691     NewClsType = NewClsTInfo->getType();
4692   else {
4693     NewClsType = getDerived().TransformType(OldClsType);
4694     if (NewClsType.isNull())
4695       return QualType();
4696   }
4697 
4698   QualType Result = TL.getType();
4699   if (getDerived().AlwaysRebuild() ||
4700       PointeeType != T->getPointeeType() ||
4701       NewClsType != OldClsType) {
4702     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4703                                                    TL.getStarLoc());
4704     if (Result.isNull())
4705       return QualType();
4706   }
4707 
4708   // If we had to adjust the pointee type when building a member pointer, make
4709   // sure to push TypeLoc info for it.
4710   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4711   if (MPT && PointeeType != MPT->getPointeeType()) {
4712     assert(isa<AdjustedType>(MPT->getPointeeType()));
4713     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4714   }
4715 
4716   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4717   NewTL.setSigilLoc(TL.getSigilLoc());
4718   NewTL.setClassTInfo(NewClsTInfo);
4719 
4720   return Result;
4721 }
4722 
4723 template<typename Derived>
4724 QualType
4725 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4726                                                    ConstantArrayTypeLoc TL) {
4727   const ConstantArrayType *T = TL.getTypePtr();
4728   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4729   if (ElementType.isNull())
4730     return QualType();
4731 
4732   QualType Result = TL.getType();
4733   if (getDerived().AlwaysRebuild() ||
4734       ElementType != T->getElementType()) {
4735     Result = getDerived().RebuildConstantArrayType(ElementType,
4736                                                    T->getSizeModifier(),
4737                                                    T->getSize(),
4738                                              T->getIndexTypeCVRQualifiers(),
4739                                                    TL.getBracketsRange());
4740     if (Result.isNull())
4741       return QualType();
4742   }
4743 
4744   // We might have either a ConstantArrayType or a VariableArrayType now:
4745   // a ConstantArrayType is allowed to have an element type which is a
4746   // VariableArrayType if the type is dependent.  Fortunately, all array
4747   // types have the same location layout.
4748   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4749   NewTL.setLBracketLoc(TL.getLBracketLoc());
4750   NewTL.setRBracketLoc(TL.getRBracketLoc());
4751 
4752   Expr *Size = TL.getSizeExpr();
4753   if (Size) {
4754     EnterExpressionEvaluationContext Unevaluated(
4755         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4756     Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4757     Size = SemaRef.ActOnConstantExpression(Size).get();
4758   }
4759   NewTL.setSizeExpr(Size);
4760 
4761   return Result;
4762 }
4763 
4764 template<typename Derived>
4765 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4766                                               TypeLocBuilder &TLB,
4767                                               IncompleteArrayTypeLoc TL) {
4768   const IncompleteArrayType *T = TL.getTypePtr();
4769   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4770   if (ElementType.isNull())
4771     return QualType();
4772 
4773   QualType Result = TL.getType();
4774   if (getDerived().AlwaysRebuild() ||
4775       ElementType != T->getElementType()) {
4776     Result = getDerived().RebuildIncompleteArrayType(ElementType,
4777                                                      T->getSizeModifier(),
4778                                            T->getIndexTypeCVRQualifiers(),
4779                                                      TL.getBracketsRange());
4780     if (Result.isNull())
4781       return QualType();
4782   }
4783 
4784   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4785   NewTL.setLBracketLoc(TL.getLBracketLoc());
4786   NewTL.setRBracketLoc(TL.getRBracketLoc());
4787   NewTL.setSizeExpr(nullptr);
4788 
4789   return Result;
4790 }
4791 
4792 template<typename Derived>
4793 QualType
4794 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4795                                                    VariableArrayTypeLoc TL) {
4796   const VariableArrayType *T = TL.getTypePtr();
4797   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4798   if (ElementType.isNull())
4799     return QualType();
4800 
4801   ExprResult SizeResult;
4802   {
4803     EnterExpressionEvaluationContext Context(
4804         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4805     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4806   }
4807   if (SizeResult.isInvalid())
4808     return QualType();
4809   SizeResult =
4810       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
4811   if (SizeResult.isInvalid())
4812     return QualType();
4813 
4814   Expr *Size = SizeResult.get();
4815 
4816   QualType Result = TL.getType();
4817   if (getDerived().AlwaysRebuild() ||
4818       ElementType != T->getElementType() ||
4819       Size != T->getSizeExpr()) {
4820     Result = getDerived().RebuildVariableArrayType(ElementType,
4821                                                    T->getSizeModifier(),
4822                                                    Size,
4823                                              T->getIndexTypeCVRQualifiers(),
4824                                                    TL.getBracketsRange());
4825     if (Result.isNull())
4826       return QualType();
4827   }
4828 
4829   // We might have constant size array now, but fortunately it has the same
4830   // location layout.
4831   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4832   NewTL.setLBracketLoc(TL.getLBracketLoc());
4833   NewTL.setRBracketLoc(TL.getRBracketLoc());
4834   NewTL.setSizeExpr(Size);
4835 
4836   return Result;
4837 }
4838 
4839 template<typename Derived>
4840 QualType
4841 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4842                                              DependentSizedArrayTypeLoc TL) {
4843   const DependentSizedArrayType *T = TL.getTypePtr();
4844   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4845   if (ElementType.isNull())
4846     return QualType();
4847 
4848   // Array bounds are constant expressions.
4849   EnterExpressionEvaluationContext Unevaluated(
4850       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4851 
4852   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4853   Expr *origSize = TL.getSizeExpr();
4854   if (!origSize) origSize = T->getSizeExpr();
4855 
4856   ExprResult sizeResult
4857     = getDerived().TransformExpr(origSize);
4858   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4859   if (sizeResult.isInvalid())
4860     return QualType();
4861 
4862   Expr *size = sizeResult.get();
4863 
4864   QualType Result = TL.getType();
4865   if (getDerived().AlwaysRebuild() ||
4866       ElementType != T->getElementType() ||
4867       size != origSize) {
4868     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4869                                                          T->getSizeModifier(),
4870                                                          size,
4871                                                 T->getIndexTypeCVRQualifiers(),
4872                                                         TL.getBracketsRange());
4873     if (Result.isNull())
4874       return QualType();
4875   }
4876 
4877   // We might have any sort of array type now, but fortunately they
4878   // all have the same location layout.
4879   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4880   NewTL.setLBracketLoc(TL.getLBracketLoc());
4881   NewTL.setRBracketLoc(TL.getRBracketLoc());
4882   NewTL.setSizeExpr(size);
4883 
4884   return Result;
4885 }
4886 
4887 template <typename Derived>
4888 QualType TreeTransform<Derived>::TransformDependentVectorType(
4889     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4890   const DependentVectorType *T = TL.getTypePtr();
4891   QualType ElementType = getDerived().TransformType(T->getElementType());
4892   if (ElementType.isNull())
4893     return QualType();
4894 
4895   EnterExpressionEvaluationContext Unevaluated(
4896       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4897 
4898   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4899   Size = SemaRef.ActOnConstantExpression(Size);
4900   if (Size.isInvalid())
4901     return QualType();
4902 
4903   QualType Result = TL.getType();
4904   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
4905       Size.get() != T->getSizeExpr()) {
4906     Result = getDerived().RebuildDependentVectorType(
4907         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
4908     if (Result.isNull())
4909       return QualType();
4910   }
4911 
4912   // Result might be dependent or not.
4913   if (isa<DependentVectorType>(Result)) {
4914     DependentVectorTypeLoc NewTL =
4915         TLB.push<DependentVectorTypeLoc>(Result);
4916     NewTL.setNameLoc(TL.getNameLoc());
4917   } else {
4918     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4919     NewTL.setNameLoc(TL.getNameLoc());
4920   }
4921 
4922   return Result;
4923 }
4924 
4925 template<typename Derived>
4926 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4927                                       TypeLocBuilder &TLB,
4928                                       DependentSizedExtVectorTypeLoc TL) {
4929   const DependentSizedExtVectorType *T = TL.getTypePtr();
4930 
4931   // FIXME: ext vector locs should be nested
4932   QualType ElementType = getDerived().TransformType(T->getElementType());
4933   if (ElementType.isNull())
4934     return QualType();
4935 
4936   // Vector sizes are constant expressions.
4937   EnterExpressionEvaluationContext Unevaluated(
4938       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4939 
4940   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4941   Size = SemaRef.ActOnConstantExpression(Size);
4942   if (Size.isInvalid())
4943     return QualType();
4944 
4945   QualType Result = TL.getType();
4946   if (getDerived().AlwaysRebuild() ||
4947       ElementType != T->getElementType() ||
4948       Size.get() != T->getSizeExpr()) {
4949     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4950                                                              Size.get(),
4951                                                          T->getAttributeLoc());
4952     if (Result.isNull())
4953       return QualType();
4954   }
4955 
4956   // Result might be dependent or not.
4957   if (isa<DependentSizedExtVectorType>(Result)) {
4958     DependentSizedExtVectorTypeLoc NewTL
4959       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4960     NewTL.setNameLoc(TL.getNameLoc());
4961   } else {
4962     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4963     NewTL.setNameLoc(TL.getNameLoc());
4964   }
4965 
4966   return Result;
4967 }
4968 
4969 template <typename Derived>
4970 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
4971     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
4972   const DependentAddressSpaceType *T = TL.getTypePtr();
4973 
4974   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
4975 
4976   if (pointeeType.isNull())
4977     return QualType();
4978 
4979   // Address spaces are constant expressions.
4980   EnterExpressionEvaluationContext Unevaluated(
4981       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4982 
4983   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
4984   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
4985   if (AddrSpace.isInvalid())
4986     return QualType();
4987 
4988   QualType Result = TL.getType();
4989   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
4990       AddrSpace.get() != T->getAddrSpaceExpr()) {
4991     Result = getDerived().RebuildDependentAddressSpaceType(
4992         pointeeType, AddrSpace.get(), T->getAttributeLoc());
4993     if (Result.isNull())
4994       return QualType();
4995   }
4996 
4997   // Result might be dependent or not.
4998   if (isa<DependentAddressSpaceType>(Result)) {
4999     DependentAddressSpaceTypeLoc NewTL =
5000         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5001 
5002     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5003     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5004     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5005 
5006   } else {
5007     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5008         Result, getDerived().getBaseLocation());
5009     TransformType(TLB, DI->getTypeLoc());
5010   }
5011 
5012   return Result;
5013 }
5014 
5015 template <typename Derived>
5016 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5017                                                      VectorTypeLoc TL) {
5018   const VectorType *T = TL.getTypePtr();
5019   QualType ElementType = getDerived().TransformType(T->getElementType());
5020   if (ElementType.isNull())
5021     return QualType();
5022 
5023   QualType Result = TL.getType();
5024   if (getDerived().AlwaysRebuild() ||
5025       ElementType != T->getElementType()) {
5026     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5027                                             T->getVectorKind());
5028     if (Result.isNull())
5029       return QualType();
5030   }
5031 
5032   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5033   NewTL.setNameLoc(TL.getNameLoc());
5034 
5035   return Result;
5036 }
5037 
5038 template<typename Derived>
5039 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5040                                                         ExtVectorTypeLoc TL) {
5041   const VectorType *T = TL.getTypePtr();
5042   QualType ElementType = getDerived().TransformType(T->getElementType());
5043   if (ElementType.isNull())
5044     return QualType();
5045 
5046   QualType Result = TL.getType();
5047   if (getDerived().AlwaysRebuild() ||
5048       ElementType != T->getElementType()) {
5049     Result = getDerived().RebuildExtVectorType(ElementType,
5050                                                T->getNumElements(),
5051                                                /*FIXME*/ SourceLocation());
5052     if (Result.isNull())
5053       return QualType();
5054   }
5055 
5056   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5057   NewTL.setNameLoc(TL.getNameLoc());
5058 
5059   return Result;
5060 }
5061 
5062 template <typename Derived>
5063 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5064     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5065     bool ExpectParameterPack) {
5066   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5067   TypeSourceInfo *NewDI = nullptr;
5068 
5069   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5070     // If we're substituting into a pack expansion type and we know the
5071     // length we want to expand to, just substitute for the pattern.
5072     TypeLoc OldTL = OldDI->getTypeLoc();
5073     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5074 
5075     TypeLocBuilder TLB;
5076     TypeLoc NewTL = OldDI->getTypeLoc();
5077     TLB.reserve(NewTL.getFullDataSize());
5078 
5079     QualType Result = getDerived().TransformType(TLB,
5080                                                OldExpansionTL.getPatternLoc());
5081     if (Result.isNull())
5082       return nullptr;
5083 
5084     Result = RebuildPackExpansionType(Result,
5085                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5086                                       OldExpansionTL.getEllipsisLoc(),
5087                                       NumExpansions);
5088     if (Result.isNull())
5089       return nullptr;
5090 
5091     PackExpansionTypeLoc NewExpansionTL
5092       = TLB.push<PackExpansionTypeLoc>(Result);
5093     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5094     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5095   } else
5096     NewDI = getDerived().TransformType(OldDI);
5097   if (!NewDI)
5098     return nullptr;
5099 
5100   if (NewDI == OldDI && indexAdjustment == 0)
5101     return OldParm;
5102 
5103   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5104                                              OldParm->getDeclContext(),
5105                                              OldParm->getInnerLocStart(),
5106                                              OldParm->getLocation(),
5107                                              OldParm->getIdentifier(),
5108                                              NewDI->getType(),
5109                                              NewDI,
5110                                              OldParm->getStorageClass(),
5111                                              /* DefArg */ nullptr);
5112   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5113                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5114   return newParm;
5115 }
5116 
5117 template <typename Derived>
5118 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5119     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5120     const QualType *ParamTypes,
5121     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5122     SmallVectorImpl<QualType> &OutParamTypes,
5123     SmallVectorImpl<ParmVarDecl *> *PVars,
5124     Sema::ExtParameterInfoBuilder &PInfos) {
5125   int indexAdjustment = 0;
5126 
5127   unsigned NumParams = Params.size();
5128   for (unsigned i = 0; i != NumParams; ++i) {
5129     if (ParmVarDecl *OldParm = Params[i]) {
5130       assert(OldParm->getFunctionScopeIndex() == i);
5131 
5132       Optional<unsigned> NumExpansions;
5133       ParmVarDecl *NewParm = nullptr;
5134       if (OldParm->isParameterPack()) {
5135         // We have a function parameter pack that may need to be expanded.
5136         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5137 
5138         // Find the parameter packs that could be expanded.
5139         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5140         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5141         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5142         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5143         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
5144 
5145         // Determine whether we should expand the parameter packs.
5146         bool ShouldExpand = false;
5147         bool RetainExpansion = false;
5148         Optional<unsigned> OrigNumExpansions =
5149             ExpansionTL.getTypePtr()->getNumExpansions();
5150         NumExpansions = OrigNumExpansions;
5151         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5152                                                  Pattern.getSourceRange(),
5153                                                  Unexpanded,
5154                                                  ShouldExpand,
5155                                                  RetainExpansion,
5156                                                  NumExpansions)) {
5157           return true;
5158         }
5159 
5160         if (ShouldExpand) {
5161           // Expand the function parameter pack into multiple, separate
5162           // parameters.
5163           getDerived().ExpandingFunctionParameterPack(OldParm);
5164           for (unsigned I = 0; I != *NumExpansions; ++I) {
5165             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5166             ParmVarDecl *NewParm
5167               = getDerived().TransformFunctionTypeParam(OldParm,
5168                                                         indexAdjustment++,
5169                                                         OrigNumExpansions,
5170                                                 /*ExpectParameterPack=*/false);
5171             if (!NewParm)
5172               return true;
5173 
5174             if (ParamInfos)
5175               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5176             OutParamTypes.push_back(NewParm->getType());
5177             if (PVars)
5178               PVars->push_back(NewParm);
5179           }
5180 
5181           // If we're supposed to retain a pack expansion, do so by temporarily
5182           // forgetting the partially-substituted parameter pack.
5183           if (RetainExpansion) {
5184             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5185             ParmVarDecl *NewParm
5186               = getDerived().TransformFunctionTypeParam(OldParm,
5187                                                         indexAdjustment++,
5188                                                         OrigNumExpansions,
5189                                                 /*ExpectParameterPack=*/false);
5190             if (!NewParm)
5191               return true;
5192 
5193             if (ParamInfos)
5194               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5195             OutParamTypes.push_back(NewParm->getType());
5196             if (PVars)
5197               PVars->push_back(NewParm);
5198           }
5199 
5200           // The next parameter should have the same adjustment as the
5201           // last thing we pushed, but we post-incremented indexAdjustment
5202           // on every push.  Also, if we push nothing, the adjustment should
5203           // go down by one.
5204           indexAdjustment--;
5205 
5206           // We're done with the pack expansion.
5207           continue;
5208         }
5209 
5210         // We'll substitute the parameter now without expanding the pack
5211         // expansion.
5212         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5213         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5214                                                           indexAdjustment,
5215                                                           NumExpansions,
5216                                                   /*ExpectParameterPack=*/true);
5217       } else {
5218         NewParm = getDerived().TransformFunctionTypeParam(
5219             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5220       }
5221 
5222       if (!NewParm)
5223         return true;
5224 
5225       if (ParamInfos)
5226         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5227       OutParamTypes.push_back(NewParm->getType());
5228       if (PVars)
5229         PVars->push_back(NewParm);
5230       continue;
5231     }
5232 
5233     // Deal with the possibility that we don't have a parameter
5234     // declaration for this parameter.
5235     QualType OldType = ParamTypes[i];
5236     bool IsPackExpansion = false;
5237     Optional<unsigned> NumExpansions;
5238     QualType NewType;
5239     if (const PackExpansionType *Expansion
5240                                        = dyn_cast<PackExpansionType>(OldType)) {
5241       // We have a function parameter pack that may need to be expanded.
5242       QualType Pattern = Expansion->getPattern();
5243       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5244       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5245 
5246       // Determine whether we should expand the parameter packs.
5247       bool ShouldExpand = false;
5248       bool RetainExpansion = false;
5249       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5250                                                Unexpanded,
5251                                                ShouldExpand,
5252                                                RetainExpansion,
5253                                                NumExpansions)) {
5254         return true;
5255       }
5256 
5257       if (ShouldExpand) {
5258         // Expand the function parameter pack into multiple, separate
5259         // parameters.
5260         for (unsigned I = 0; I != *NumExpansions; ++I) {
5261           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5262           QualType NewType = getDerived().TransformType(Pattern);
5263           if (NewType.isNull())
5264             return true;
5265 
5266           if (NewType->containsUnexpandedParameterPack()) {
5267             NewType =
5268                 getSema().getASTContext().getPackExpansionType(NewType, None);
5269 
5270             if (NewType.isNull())
5271               return true;
5272           }
5273 
5274           if (ParamInfos)
5275             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5276           OutParamTypes.push_back(NewType);
5277           if (PVars)
5278             PVars->push_back(nullptr);
5279         }
5280 
5281         // We're done with the pack expansion.
5282         continue;
5283       }
5284 
5285       // If we're supposed to retain a pack expansion, do so by temporarily
5286       // forgetting the partially-substituted parameter pack.
5287       if (RetainExpansion) {
5288         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5289         QualType NewType = getDerived().TransformType(Pattern);
5290         if (NewType.isNull())
5291           return true;
5292 
5293         if (ParamInfos)
5294           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5295         OutParamTypes.push_back(NewType);
5296         if (PVars)
5297           PVars->push_back(nullptr);
5298       }
5299 
5300       // We'll substitute the parameter now without expanding the pack
5301       // expansion.
5302       OldType = Expansion->getPattern();
5303       IsPackExpansion = true;
5304       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5305       NewType = getDerived().TransformType(OldType);
5306     } else {
5307       NewType = getDerived().TransformType(OldType);
5308     }
5309 
5310     if (NewType.isNull())
5311       return true;
5312 
5313     if (IsPackExpansion)
5314       NewType = getSema().Context.getPackExpansionType(NewType,
5315                                                        NumExpansions);
5316 
5317     if (ParamInfos)
5318       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5319     OutParamTypes.push_back(NewType);
5320     if (PVars)
5321       PVars->push_back(nullptr);
5322   }
5323 
5324 #ifndef NDEBUG
5325   if (PVars) {
5326     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5327       if (ParmVarDecl *parm = (*PVars)[i])
5328         assert(parm->getFunctionScopeIndex() == i);
5329   }
5330 #endif
5331 
5332   return false;
5333 }
5334 
5335 template<typename Derived>
5336 QualType
5337 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5338                                                    FunctionProtoTypeLoc TL) {
5339   SmallVector<QualType, 4> ExceptionStorage;
5340   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5341   return getDerived().TransformFunctionProtoType(
5342       TLB, TL, nullptr, Qualifiers(),
5343       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5344         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5345                                             ExceptionStorage, Changed);
5346       });
5347 }
5348 
5349 template<typename Derived> template<typename Fn>
5350 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5351     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5352     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5353 
5354   // Transform the parameters and return type.
5355   //
5356   // We are required to instantiate the params and return type in source order.
5357   // When the function has a trailing return type, we instantiate the
5358   // parameters before the return type,  since the return type can then refer
5359   // to the parameters themselves (via decltype, sizeof, etc.).
5360   //
5361   SmallVector<QualType, 4> ParamTypes;
5362   SmallVector<ParmVarDecl*, 4> ParamDecls;
5363   Sema::ExtParameterInfoBuilder ExtParamInfos;
5364   const FunctionProtoType *T = TL.getTypePtr();
5365 
5366   QualType ResultType;
5367 
5368   if (T->hasTrailingReturn()) {
5369     if (getDerived().TransformFunctionTypeParams(
5370             TL.getBeginLoc(), TL.getParams(),
5371             TL.getTypePtr()->param_type_begin(),
5372             T->getExtParameterInfosOrNull(),
5373             ParamTypes, &ParamDecls, ExtParamInfos))
5374       return QualType();
5375 
5376     {
5377       // C++11 [expr.prim.general]p3:
5378       //   If a declaration declares a member function or member function
5379       //   template of a class X, the expression this is a prvalue of type
5380       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5381       //   and the end of the function-definition, member-declarator, or
5382       //   declarator.
5383       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5384 
5385       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5386       if (ResultType.isNull())
5387         return QualType();
5388     }
5389   }
5390   else {
5391     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5392     if (ResultType.isNull())
5393       return QualType();
5394 
5395     if (getDerived().TransformFunctionTypeParams(
5396             TL.getBeginLoc(), TL.getParams(),
5397             TL.getTypePtr()->param_type_begin(),
5398             T->getExtParameterInfosOrNull(),
5399             ParamTypes, &ParamDecls, ExtParamInfos))
5400       return QualType();
5401   }
5402 
5403   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5404 
5405   bool EPIChanged = false;
5406   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5407     return QualType();
5408 
5409   // Handle extended parameter information.
5410   if (auto NewExtParamInfos =
5411         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5412     if (!EPI.ExtParameterInfos ||
5413         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5414           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5415       EPIChanged = true;
5416     }
5417     EPI.ExtParameterInfos = NewExtParamInfos;
5418   } else if (EPI.ExtParameterInfos) {
5419     EPIChanged = true;
5420     EPI.ExtParameterInfos = nullptr;
5421   }
5422 
5423   QualType Result = TL.getType();
5424   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5425       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5426     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5427     if (Result.isNull())
5428       return QualType();
5429   }
5430 
5431   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5432   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5433   NewTL.setLParenLoc(TL.getLParenLoc());
5434   NewTL.setRParenLoc(TL.getRParenLoc());
5435   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5436   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5437   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5438     NewTL.setParam(i, ParamDecls[i]);
5439 
5440   return Result;
5441 }
5442 
5443 template<typename Derived>
5444 bool TreeTransform<Derived>::TransformExceptionSpec(
5445     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5446     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5447   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5448 
5449   // Instantiate a dynamic noexcept expression, if any.
5450   if (isComputedNoexcept(ESI.Type)) {
5451     EnterExpressionEvaluationContext Unevaluated(
5452         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5453     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5454     if (NoexceptExpr.isInvalid())
5455       return true;
5456 
5457     ExceptionSpecificationType EST = ESI.Type;
5458     NoexceptExpr =
5459         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5460     if (NoexceptExpr.isInvalid())
5461       return true;
5462 
5463     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5464       Changed = true;
5465     ESI.NoexceptExpr = NoexceptExpr.get();
5466     ESI.Type = EST;
5467   }
5468 
5469   if (ESI.Type != EST_Dynamic)
5470     return false;
5471 
5472   // Instantiate a dynamic exception specification's type.
5473   for (QualType T : ESI.Exceptions) {
5474     if (const PackExpansionType *PackExpansion =
5475             T->getAs<PackExpansionType>()) {
5476       Changed = true;
5477 
5478       // We have a pack expansion. Instantiate it.
5479       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5480       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5481                                               Unexpanded);
5482       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5483 
5484       // Determine whether the set of unexpanded parameter packs can and
5485       // should
5486       // be expanded.
5487       bool Expand = false;
5488       bool RetainExpansion = false;
5489       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5490       // FIXME: Track the location of the ellipsis (and track source location
5491       // information for the types in the exception specification in general).
5492       if (getDerived().TryExpandParameterPacks(
5493               Loc, SourceRange(), Unexpanded, Expand,
5494               RetainExpansion, NumExpansions))
5495         return true;
5496 
5497       if (!Expand) {
5498         // We can't expand this pack expansion into separate arguments yet;
5499         // just substitute into the pattern and create a new pack expansion
5500         // type.
5501         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5502         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5503         if (U.isNull())
5504           return true;
5505 
5506         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5507         Exceptions.push_back(U);
5508         continue;
5509       }
5510 
5511       // Substitute into the pack expansion pattern for each slice of the
5512       // pack.
5513       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5514         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5515 
5516         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5517         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5518           return true;
5519 
5520         Exceptions.push_back(U);
5521       }
5522     } else {
5523       QualType U = getDerived().TransformType(T);
5524       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5525         return true;
5526       if (T != U)
5527         Changed = true;
5528 
5529       Exceptions.push_back(U);
5530     }
5531   }
5532 
5533   ESI.Exceptions = Exceptions;
5534   if (ESI.Exceptions.empty())
5535     ESI.Type = EST_DynamicNone;
5536   return false;
5537 }
5538 
5539 template<typename Derived>
5540 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5541                                                  TypeLocBuilder &TLB,
5542                                                  FunctionNoProtoTypeLoc TL) {
5543   const FunctionNoProtoType *T = TL.getTypePtr();
5544   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5545   if (ResultType.isNull())
5546     return QualType();
5547 
5548   QualType Result = TL.getType();
5549   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5550     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5551 
5552   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5553   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5554   NewTL.setLParenLoc(TL.getLParenLoc());
5555   NewTL.setRParenLoc(TL.getRParenLoc());
5556   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5557 
5558   return Result;
5559 }
5560 
5561 template<typename Derived> QualType
5562 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5563                                                  UnresolvedUsingTypeLoc TL) {
5564   const UnresolvedUsingType *T = TL.getTypePtr();
5565   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5566   if (!D)
5567     return QualType();
5568 
5569   QualType Result = TL.getType();
5570   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5571     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5572     if (Result.isNull())
5573       return QualType();
5574   }
5575 
5576   // We might get an arbitrary type spec type back.  We should at
5577   // least always get a type spec type, though.
5578   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5579   NewTL.setNameLoc(TL.getNameLoc());
5580 
5581   return Result;
5582 }
5583 
5584 template<typename Derived>
5585 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5586                                                       TypedefTypeLoc TL) {
5587   const TypedefType *T = TL.getTypePtr();
5588   TypedefNameDecl *Typedef
5589     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5590                                                                T->getDecl()));
5591   if (!Typedef)
5592     return QualType();
5593 
5594   QualType Result = TL.getType();
5595   if (getDerived().AlwaysRebuild() ||
5596       Typedef != T->getDecl()) {
5597     Result = getDerived().RebuildTypedefType(Typedef);
5598     if (Result.isNull())
5599       return QualType();
5600   }
5601 
5602   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5603   NewTL.setNameLoc(TL.getNameLoc());
5604 
5605   return Result;
5606 }
5607 
5608 template<typename Derived>
5609 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5610                                                       TypeOfExprTypeLoc TL) {
5611   // typeof expressions are not potentially evaluated contexts
5612   EnterExpressionEvaluationContext Unevaluated(
5613       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5614       Sema::ReuseLambdaContextDecl);
5615 
5616   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5617   if (E.isInvalid())
5618     return QualType();
5619 
5620   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5621   if (E.isInvalid())
5622     return QualType();
5623 
5624   QualType Result = TL.getType();
5625   if (getDerived().AlwaysRebuild() ||
5626       E.get() != TL.getUnderlyingExpr()) {
5627     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5628     if (Result.isNull())
5629       return QualType();
5630   }
5631   else E.get();
5632 
5633   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5634   NewTL.setTypeofLoc(TL.getTypeofLoc());
5635   NewTL.setLParenLoc(TL.getLParenLoc());
5636   NewTL.setRParenLoc(TL.getRParenLoc());
5637 
5638   return Result;
5639 }
5640 
5641 template<typename Derived>
5642 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5643                                                      TypeOfTypeLoc TL) {
5644   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5645   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5646   if (!New_Under_TI)
5647     return QualType();
5648 
5649   QualType Result = TL.getType();
5650   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5651     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5652     if (Result.isNull())
5653       return QualType();
5654   }
5655 
5656   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5657   NewTL.setTypeofLoc(TL.getTypeofLoc());
5658   NewTL.setLParenLoc(TL.getLParenLoc());
5659   NewTL.setRParenLoc(TL.getRParenLoc());
5660   NewTL.setUnderlyingTInfo(New_Under_TI);
5661 
5662   return Result;
5663 }
5664 
5665 template<typename Derived>
5666 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5667                                                        DecltypeTypeLoc TL) {
5668   const DecltypeType *T = TL.getTypePtr();
5669 
5670   // decltype expressions are not potentially evaluated contexts
5671   EnterExpressionEvaluationContext Unevaluated(
5672       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5673       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5674 
5675   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5676   if (E.isInvalid())
5677     return QualType();
5678 
5679   E = getSema().ActOnDecltypeExpression(E.get());
5680   if (E.isInvalid())
5681     return QualType();
5682 
5683   QualType Result = TL.getType();
5684   if (getDerived().AlwaysRebuild() ||
5685       E.get() != T->getUnderlyingExpr()) {
5686     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5687     if (Result.isNull())
5688       return QualType();
5689   }
5690   else E.get();
5691 
5692   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5693   NewTL.setNameLoc(TL.getNameLoc());
5694 
5695   return Result;
5696 }
5697 
5698 template<typename Derived>
5699 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5700                                                             TypeLocBuilder &TLB,
5701                                                      UnaryTransformTypeLoc TL) {
5702   QualType Result = TL.getType();
5703   if (Result->isDependentType()) {
5704     const UnaryTransformType *T = TL.getTypePtr();
5705     QualType NewBase =
5706       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5707     Result = getDerived().RebuildUnaryTransformType(NewBase,
5708                                                     T->getUTTKind(),
5709                                                     TL.getKWLoc());
5710     if (Result.isNull())
5711       return QualType();
5712   }
5713 
5714   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5715   NewTL.setKWLoc(TL.getKWLoc());
5716   NewTL.setParensRange(TL.getParensRange());
5717   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5718   return Result;
5719 }
5720 
5721 template<typename Derived>
5722 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5723                                                    AutoTypeLoc TL) {
5724   const AutoType *T = TL.getTypePtr();
5725   QualType OldDeduced = T->getDeducedType();
5726   QualType NewDeduced;
5727   if (!OldDeduced.isNull()) {
5728     NewDeduced = getDerived().TransformType(OldDeduced);
5729     if (NewDeduced.isNull())
5730       return QualType();
5731   }
5732 
5733   QualType Result = TL.getType();
5734   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5735       T->isDependentType()) {
5736     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5737     if (Result.isNull())
5738       return QualType();
5739   }
5740 
5741   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5742   NewTL.setNameLoc(TL.getNameLoc());
5743 
5744   return Result;
5745 }
5746 
5747 template<typename Derived>
5748 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5749     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5750   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5751 
5752   CXXScopeSpec SS;
5753   TemplateName TemplateName = getDerived().TransformTemplateName(
5754       SS, T->getTemplateName(), TL.getTemplateNameLoc());
5755   if (TemplateName.isNull())
5756     return QualType();
5757 
5758   QualType OldDeduced = T->getDeducedType();
5759   QualType NewDeduced;
5760   if (!OldDeduced.isNull()) {
5761     NewDeduced = getDerived().TransformType(OldDeduced);
5762     if (NewDeduced.isNull())
5763       return QualType();
5764   }
5765 
5766   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5767       TemplateName, NewDeduced);
5768   if (Result.isNull())
5769     return QualType();
5770 
5771   DeducedTemplateSpecializationTypeLoc NewTL =
5772       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5773   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5774 
5775   return Result;
5776 }
5777 
5778 template<typename Derived>
5779 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5780                                                      RecordTypeLoc TL) {
5781   const RecordType *T = TL.getTypePtr();
5782   RecordDecl *Record
5783     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5784                                                           T->getDecl()));
5785   if (!Record)
5786     return QualType();
5787 
5788   QualType Result = TL.getType();
5789   if (getDerived().AlwaysRebuild() ||
5790       Record != T->getDecl()) {
5791     Result = getDerived().RebuildRecordType(Record);
5792     if (Result.isNull())
5793       return QualType();
5794   }
5795 
5796   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5797   NewTL.setNameLoc(TL.getNameLoc());
5798 
5799   return Result;
5800 }
5801 
5802 template<typename Derived>
5803 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5804                                                    EnumTypeLoc TL) {
5805   const EnumType *T = TL.getTypePtr();
5806   EnumDecl *Enum
5807     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5808                                                         T->getDecl()));
5809   if (!Enum)
5810     return QualType();
5811 
5812   QualType Result = TL.getType();
5813   if (getDerived().AlwaysRebuild() ||
5814       Enum != T->getDecl()) {
5815     Result = getDerived().RebuildEnumType(Enum);
5816     if (Result.isNull())
5817       return QualType();
5818   }
5819 
5820   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5821   NewTL.setNameLoc(TL.getNameLoc());
5822 
5823   return Result;
5824 }
5825 
5826 template<typename Derived>
5827 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5828                                          TypeLocBuilder &TLB,
5829                                          InjectedClassNameTypeLoc TL) {
5830   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5831                                        TL.getTypePtr()->getDecl());
5832   if (!D) return QualType();
5833 
5834   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5835   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5836   return T;
5837 }
5838 
5839 template<typename Derived>
5840 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5841                                                 TypeLocBuilder &TLB,
5842                                                 TemplateTypeParmTypeLoc TL) {
5843   return TransformTypeSpecType(TLB, TL);
5844 }
5845 
5846 template<typename Derived>
5847 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5848                                          TypeLocBuilder &TLB,
5849                                          SubstTemplateTypeParmTypeLoc TL) {
5850   const SubstTemplateTypeParmType *T = TL.getTypePtr();
5851 
5852   // Substitute into the replacement type, which itself might involve something
5853   // that needs to be transformed. This only tends to occur with default
5854   // template arguments of template template parameters.
5855   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5856   QualType Replacement = getDerived().TransformType(T->getReplacementType());
5857   if (Replacement.isNull())
5858     return QualType();
5859 
5860   // Always canonicalize the replacement type.
5861   Replacement = SemaRef.Context.getCanonicalType(Replacement);
5862   QualType Result
5863     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5864                                                    Replacement);
5865 
5866   // Propagate type-source information.
5867   SubstTemplateTypeParmTypeLoc NewTL
5868     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5869   NewTL.setNameLoc(TL.getNameLoc());
5870   return Result;
5871 
5872 }
5873 
5874 template<typename Derived>
5875 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5876                                           TypeLocBuilder &TLB,
5877                                           SubstTemplateTypeParmPackTypeLoc TL) {
5878   return TransformTypeSpecType(TLB, TL);
5879 }
5880 
5881 template<typename Derived>
5882 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5883                                                         TypeLocBuilder &TLB,
5884                                            TemplateSpecializationTypeLoc TL) {
5885   const TemplateSpecializationType *T = TL.getTypePtr();
5886 
5887   // The nested-name-specifier never matters in a TemplateSpecializationType,
5888   // because we can't have a dependent nested-name-specifier anyway.
5889   CXXScopeSpec SS;
5890   TemplateName Template
5891     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5892                                          TL.getTemplateNameLoc());
5893   if (Template.isNull())
5894     return QualType();
5895 
5896   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5897 }
5898 
5899 template<typename Derived>
5900 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5901                                                      AtomicTypeLoc TL) {
5902   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5903   if (ValueType.isNull())
5904     return QualType();
5905 
5906   QualType Result = TL.getType();
5907   if (getDerived().AlwaysRebuild() ||
5908       ValueType != TL.getValueLoc().getType()) {
5909     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5910     if (Result.isNull())
5911       return QualType();
5912   }
5913 
5914   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5915   NewTL.setKWLoc(TL.getKWLoc());
5916   NewTL.setLParenLoc(TL.getLParenLoc());
5917   NewTL.setRParenLoc(TL.getRParenLoc());
5918 
5919   return Result;
5920 }
5921 
5922 template <typename Derived>
5923 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5924                                                    PipeTypeLoc TL) {
5925   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5926   if (ValueType.isNull())
5927     return QualType();
5928 
5929   QualType Result = TL.getType();
5930   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5931     const PipeType *PT = Result->getAs<PipeType>();
5932     bool isReadPipe = PT->isReadOnly();
5933     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5934     if (Result.isNull())
5935       return QualType();
5936   }
5937 
5938   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5939   NewTL.setKWLoc(TL.getKWLoc());
5940 
5941   return Result;
5942 }
5943 
5944   /// Simple iterator that traverses the template arguments in a
5945   /// container that provides a \c getArgLoc() member function.
5946   ///
5947   /// This iterator is intended to be used with the iterator form of
5948   /// \c TreeTransform<Derived>::TransformTemplateArguments().
5949   template<typename ArgLocContainer>
5950   class TemplateArgumentLocContainerIterator {
5951     ArgLocContainer *Container;
5952     unsigned Index;
5953 
5954   public:
5955     typedef TemplateArgumentLoc value_type;
5956     typedef TemplateArgumentLoc reference;
5957     typedef int difference_type;
5958     typedef std::input_iterator_tag iterator_category;
5959 
5960     class pointer {
5961       TemplateArgumentLoc Arg;
5962 
5963     public:
5964       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5965 
5966       const TemplateArgumentLoc *operator->() const {
5967         return &Arg;
5968       }
5969     };
5970 
5971 
5972     TemplateArgumentLocContainerIterator() {}
5973 
5974     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5975                                  unsigned Index)
5976       : Container(&Container), Index(Index) { }
5977 
5978     TemplateArgumentLocContainerIterator &operator++() {
5979       ++Index;
5980       return *this;
5981     }
5982 
5983     TemplateArgumentLocContainerIterator operator++(int) {
5984       TemplateArgumentLocContainerIterator Old(*this);
5985       ++(*this);
5986       return Old;
5987     }
5988 
5989     TemplateArgumentLoc operator*() const {
5990       return Container->getArgLoc(Index);
5991     }
5992 
5993     pointer operator->() const {
5994       return pointer(Container->getArgLoc(Index));
5995     }
5996 
5997     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5998                            const TemplateArgumentLocContainerIterator &Y) {
5999       return X.Container == Y.Container && X.Index == Y.Index;
6000     }
6001 
6002     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6003                            const TemplateArgumentLocContainerIterator &Y) {
6004       return !(X == Y);
6005     }
6006   };
6007 
6008 
6009 template <typename Derived>
6010 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6011                                                         TypeLocBuilder &TLB,
6012                                            TemplateSpecializationTypeLoc TL,
6013                                                       TemplateName Template) {
6014   TemplateArgumentListInfo NewTemplateArgs;
6015   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6016   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6017   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6018     ArgIterator;
6019   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6020                                               ArgIterator(TL, TL.getNumArgs()),
6021                                               NewTemplateArgs))
6022     return QualType();
6023 
6024   // FIXME: maybe don't rebuild if all the template arguments are the same.
6025 
6026   QualType Result =
6027     getDerived().RebuildTemplateSpecializationType(Template,
6028                                                    TL.getTemplateNameLoc(),
6029                                                    NewTemplateArgs);
6030 
6031   if (!Result.isNull()) {
6032     // Specializations of template template parameters are represented as
6033     // TemplateSpecializationTypes, and substitution of type alias templates
6034     // within a dependent context can transform them into
6035     // DependentTemplateSpecializationTypes.
6036     if (isa<DependentTemplateSpecializationType>(Result)) {
6037       DependentTemplateSpecializationTypeLoc NewTL
6038         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6039       NewTL.setElaboratedKeywordLoc(SourceLocation());
6040       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6041       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6042       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6043       NewTL.setLAngleLoc(TL.getLAngleLoc());
6044       NewTL.setRAngleLoc(TL.getRAngleLoc());
6045       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6046         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6047       return Result;
6048     }
6049 
6050     TemplateSpecializationTypeLoc NewTL
6051       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6052     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6053     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6054     NewTL.setLAngleLoc(TL.getLAngleLoc());
6055     NewTL.setRAngleLoc(TL.getRAngleLoc());
6056     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6057       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6058   }
6059 
6060   return Result;
6061 }
6062 
6063 template <typename Derived>
6064 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6065                                      TypeLocBuilder &TLB,
6066                                      DependentTemplateSpecializationTypeLoc TL,
6067                                      TemplateName Template,
6068                                      CXXScopeSpec &SS) {
6069   TemplateArgumentListInfo NewTemplateArgs;
6070   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6071   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6072   typedef TemplateArgumentLocContainerIterator<
6073             DependentTemplateSpecializationTypeLoc> ArgIterator;
6074   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6075                                               ArgIterator(TL, TL.getNumArgs()),
6076                                               NewTemplateArgs))
6077     return QualType();
6078 
6079   // FIXME: maybe don't rebuild if all the template arguments are the same.
6080 
6081   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6082     QualType Result
6083       = getSema().Context.getDependentTemplateSpecializationType(
6084                                                 TL.getTypePtr()->getKeyword(),
6085                                                          DTN->getQualifier(),
6086                                                          DTN->getIdentifier(),
6087                                                                NewTemplateArgs);
6088 
6089     DependentTemplateSpecializationTypeLoc NewTL
6090       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6091     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6092     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6093     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6094     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6095     NewTL.setLAngleLoc(TL.getLAngleLoc());
6096     NewTL.setRAngleLoc(TL.getRAngleLoc());
6097     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6098       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6099     return Result;
6100   }
6101 
6102   QualType Result
6103     = getDerived().RebuildTemplateSpecializationType(Template,
6104                                                      TL.getTemplateNameLoc(),
6105                                                      NewTemplateArgs);
6106 
6107   if (!Result.isNull()) {
6108     /// FIXME: Wrap this in an elaborated-type-specifier?
6109     TemplateSpecializationTypeLoc NewTL
6110       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6111     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6112     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6113     NewTL.setLAngleLoc(TL.getLAngleLoc());
6114     NewTL.setRAngleLoc(TL.getRAngleLoc());
6115     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6116       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6117   }
6118 
6119   return Result;
6120 }
6121 
6122 template<typename Derived>
6123 QualType
6124 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6125                                                 ElaboratedTypeLoc TL) {
6126   const ElaboratedType *T = TL.getTypePtr();
6127 
6128   NestedNameSpecifierLoc QualifierLoc;
6129   // NOTE: the qualifier in an ElaboratedType is optional.
6130   if (TL.getQualifierLoc()) {
6131     QualifierLoc
6132       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6133     if (!QualifierLoc)
6134       return QualType();
6135   }
6136 
6137   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6138   if (NamedT.isNull())
6139     return QualType();
6140 
6141   // C++0x [dcl.type.elab]p2:
6142   //   If the identifier resolves to a typedef-name or the simple-template-id
6143   //   resolves to an alias template specialization, the
6144   //   elaborated-type-specifier is ill-formed.
6145   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6146     if (const TemplateSpecializationType *TST =
6147           NamedT->getAs<TemplateSpecializationType>()) {
6148       TemplateName Template = TST->getTemplateName();
6149       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6150               Template.getAsTemplateDecl())) {
6151         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6152                      diag::err_tag_reference_non_tag)
6153             << TAT << Sema::NTK_TypeAliasTemplate
6154             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6155         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6156       }
6157     }
6158   }
6159 
6160   QualType Result = TL.getType();
6161   if (getDerived().AlwaysRebuild() ||
6162       QualifierLoc != TL.getQualifierLoc() ||
6163       NamedT != T->getNamedType()) {
6164     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6165                                                 T->getKeyword(),
6166                                                 QualifierLoc, NamedT);
6167     if (Result.isNull())
6168       return QualType();
6169   }
6170 
6171   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6172   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6173   NewTL.setQualifierLoc(QualifierLoc);
6174   return Result;
6175 }
6176 
6177 template<typename Derived>
6178 QualType TreeTransform<Derived>::TransformAttributedType(
6179                                                 TypeLocBuilder &TLB,
6180                                                 AttributedTypeLoc TL) {
6181   const AttributedType *oldType = TL.getTypePtr();
6182   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6183   if (modifiedType.isNull())
6184     return QualType();
6185 
6186   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6187   const Attr *oldAttr = TL.getAttr();
6188   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6189   if (oldAttr && !newAttr)
6190     return QualType();
6191 
6192   QualType result = TL.getType();
6193 
6194   // FIXME: dependent operand expressions?
6195   if (getDerived().AlwaysRebuild() ||
6196       modifiedType != oldType->getModifiedType()) {
6197     // TODO: this is really lame; we should really be rebuilding the
6198     // equivalent type from first principles.
6199     QualType equivalentType
6200       = getDerived().TransformType(oldType->getEquivalentType());
6201     if (equivalentType.isNull())
6202       return QualType();
6203 
6204     // Check whether we can add nullability; it is only represented as
6205     // type sugar, and therefore cannot be diagnosed in any other way.
6206     if (auto nullability = oldType->getImmediateNullability()) {
6207       if (!modifiedType->canHaveNullability()) {
6208         SemaRef.Diag(TL.getAttr()->getLocation(),
6209                      diag::err_nullability_nonpointer)
6210             << DiagNullabilityKind(*nullability, false) << modifiedType;
6211         return QualType();
6212       }
6213     }
6214 
6215     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6216                                                modifiedType,
6217                                                equivalentType);
6218   }
6219 
6220   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6221   newTL.setAttr(newAttr);
6222   return result;
6223 }
6224 
6225 template<typename Derived>
6226 QualType
6227 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6228                                            ParenTypeLoc TL) {
6229   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6230   if (Inner.isNull())
6231     return QualType();
6232 
6233   QualType Result = TL.getType();
6234   if (getDerived().AlwaysRebuild() ||
6235       Inner != TL.getInnerLoc().getType()) {
6236     Result = getDerived().RebuildParenType(Inner);
6237     if (Result.isNull())
6238       return QualType();
6239   }
6240 
6241   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6242   NewTL.setLParenLoc(TL.getLParenLoc());
6243   NewTL.setRParenLoc(TL.getRParenLoc());
6244   return Result;
6245 }
6246 
6247 template <typename Derived>
6248 QualType
6249 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6250                                                     MacroQualifiedTypeLoc TL) {
6251   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6252   if (Inner.isNull())
6253     return QualType();
6254 
6255   QualType Result = TL.getType();
6256   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6257     Result =
6258         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6259     if (Result.isNull())
6260       return QualType();
6261   }
6262 
6263   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6264   NewTL.setExpansionLoc(TL.getExpansionLoc());
6265   return Result;
6266 }
6267 
6268 template<typename Derived>
6269 QualType TreeTransform<Derived>::TransformDependentNameType(
6270     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6271   return TransformDependentNameType(TLB, TL, false);
6272 }
6273 
6274 template<typename Derived>
6275 QualType TreeTransform<Derived>::TransformDependentNameType(
6276     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6277   const DependentNameType *T = TL.getTypePtr();
6278 
6279   NestedNameSpecifierLoc QualifierLoc
6280     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6281   if (!QualifierLoc)
6282     return QualType();
6283 
6284   QualType Result
6285     = getDerived().RebuildDependentNameType(T->getKeyword(),
6286                                             TL.getElaboratedKeywordLoc(),
6287                                             QualifierLoc,
6288                                             T->getIdentifier(),
6289                                             TL.getNameLoc(),
6290                                             DeducedTSTContext);
6291   if (Result.isNull())
6292     return QualType();
6293 
6294   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6295     QualType NamedT = ElabT->getNamedType();
6296     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6297 
6298     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6299     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6300     NewTL.setQualifierLoc(QualifierLoc);
6301   } else {
6302     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6303     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6304     NewTL.setQualifierLoc(QualifierLoc);
6305     NewTL.setNameLoc(TL.getNameLoc());
6306   }
6307   return Result;
6308 }
6309 
6310 template<typename Derived>
6311 QualType TreeTransform<Derived>::
6312           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6313                                  DependentTemplateSpecializationTypeLoc TL) {
6314   NestedNameSpecifierLoc QualifierLoc;
6315   if (TL.getQualifierLoc()) {
6316     QualifierLoc
6317       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6318     if (!QualifierLoc)
6319       return QualType();
6320   }
6321 
6322   return getDerived()
6323            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6324 }
6325 
6326 template<typename Derived>
6327 QualType TreeTransform<Derived>::
6328 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6329                                    DependentTemplateSpecializationTypeLoc TL,
6330                                        NestedNameSpecifierLoc QualifierLoc) {
6331   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6332 
6333   TemplateArgumentListInfo NewTemplateArgs;
6334   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6335   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6336 
6337   typedef TemplateArgumentLocContainerIterator<
6338   DependentTemplateSpecializationTypeLoc> ArgIterator;
6339   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6340                                               ArgIterator(TL, TL.getNumArgs()),
6341                                               NewTemplateArgs))
6342     return QualType();
6343 
6344   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6345       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6346       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6347       /*AllowInjectedClassName*/ false);
6348   if (Result.isNull())
6349     return QualType();
6350 
6351   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6352     QualType NamedT = ElabT->getNamedType();
6353 
6354     // Copy information relevant to the template specialization.
6355     TemplateSpecializationTypeLoc NamedTL
6356       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6357     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6358     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6359     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6360     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6361     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6362       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6363 
6364     // Copy information relevant to the elaborated type.
6365     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6366     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6367     NewTL.setQualifierLoc(QualifierLoc);
6368   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6369     DependentTemplateSpecializationTypeLoc SpecTL
6370       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6371     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6372     SpecTL.setQualifierLoc(QualifierLoc);
6373     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6374     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6375     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6376     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6377     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6378       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6379   } else {
6380     TemplateSpecializationTypeLoc SpecTL
6381       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6382     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6383     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6384     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6385     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6386     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6387       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6388   }
6389   return Result;
6390 }
6391 
6392 template<typename Derived>
6393 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6394                                                       PackExpansionTypeLoc TL) {
6395   QualType Pattern
6396     = getDerived().TransformType(TLB, TL.getPatternLoc());
6397   if (Pattern.isNull())
6398     return QualType();
6399 
6400   QualType Result = TL.getType();
6401   if (getDerived().AlwaysRebuild() ||
6402       Pattern != TL.getPatternLoc().getType()) {
6403     Result = getDerived().RebuildPackExpansionType(Pattern,
6404                                            TL.getPatternLoc().getSourceRange(),
6405                                                    TL.getEllipsisLoc(),
6406                                            TL.getTypePtr()->getNumExpansions());
6407     if (Result.isNull())
6408       return QualType();
6409   }
6410 
6411   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6412   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6413   return Result;
6414 }
6415 
6416 template<typename Derived>
6417 QualType
6418 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6419                                                    ObjCInterfaceTypeLoc TL) {
6420   // ObjCInterfaceType is never dependent.
6421   TLB.pushFullCopy(TL);
6422   return TL.getType();
6423 }
6424 
6425 template<typename Derived>
6426 QualType
6427 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6428                                                    ObjCTypeParamTypeLoc TL) {
6429   const ObjCTypeParamType *T = TL.getTypePtr();
6430   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6431       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6432   if (!OTP)
6433     return QualType();
6434 
6435   QualType Result = TL.getType();
6436   if (getDerived().AlwaysRebuild() ||
6437       OTP != T->getDecl()) {
6438     Result = getDerived().RebuildObjCTypeParamType(OTP,
6439                  TL.getProtocolLAngleLoc(),
6440                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6441                                     TL.getNumProtocols()),
6442                  TL.getProtocolLocs(),
6443                  TL.getProtocolRAngleLoc());
6444     if (Result.isNull())
6445       return QualType();
6446   }
6447 
6448   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6449   if (TL.getNumProtocols()) {
6450     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6451     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6452       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6453     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6454   }
6455   return Result;
6456 }
6457 
6458 template<typename Derived>
6459 QualType
6460 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6461                                                 ObjCObjectTypeLoc TL) {
6462   // Transform base type.
6463   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6464   if (BaseType.isNull())
6465     return QualType();
6466 
6467   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6468 
6469   // Transform type arguments.
6470   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6471   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6472     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6473     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6474     QualType TypeArg = TypeArgInfo->getType();
6475     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6476       AnyChanged = true;
6477 
6478       // We have a pack expansion. Instantiate it.
6479       const auto *PackExpansion = PackExpansionLoc.getType()
6480                                     ->castAs<PackExpansionType>();
6481       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6482       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6483                                               Unexpanded);
6484       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6485 
6486       // Determine whether the set of unexpanded parameter packs can
6487       // and should be expanded.
6488       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6489       bool Expand = false;
6490       bool RetainExpansion = false;
6491       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6492       if (getDerived().TryExpandParameterPacks(
6493             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6494             Unexpanded, Expand, RetainExpansion, NumExpansions))
6495         return QualType();
6496 
6497       if (!Expand) {
6498         // We can't expand this pack expansion into separate arguments yet;
6499         // just substitute into the pattern and create a new pack expansion
6500         // type.
6501         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6502 
6503         TypeLocBuilder TypeArgBuilder;
6504         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6505         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6506                                                              PatternLoc);
6507         if (NewPatternType.isNull())
6508           return QualType();
6509 
6510         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6511                                       NewPatternType, NumExpansions);
6512         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6513         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6514         NewTypeArgInfos.push_back(
6515           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6516         continue;
6517       }
6518 
6519       // Substitute into the pack expansion pattern for each slice of the
6520       // pack.
6521       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6522         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6523 
6524         TypeLocBuilder TypeArgBuilder;
6525         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6526 
6527         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6528                                                          PatternLoc);
6529         if (NewTypeArg.isNull())
6530           return QualType();
6531 
6532         NewTypeArgInfos.push_back(
6533           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6534       }
6535 
6536       continue;
6537     }
6538 
6539     TypeLocBuilder TypeArgBuilder;
6540     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6541     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6542     if (NewTypeArg.isNull())
6543       return QualType();
6544 
6545     // If nothing changed, just keep the old TypeSourceInfo.
6546     if (NewTypeArg == TypeArg) {
6547       NewTypeArgInfos.push_back(TypeArgInfo);
6548       continue;
6549     }
6550 
6551     NewTypeArgInfos.push_back(
6552       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6553     AnyChanged = true;
6554   }
6555 
6556   QualType Result = TL.getType();
6557   if (getDerived().AlwaysRebuild() || AnyChanged) {
6558     // Rebuild the type.
6559     Result = getDerived().RebuildObjCObjectType(
6560         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6561         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6562         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6563         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6564 
6565     if (Result.isNull())
6566       return QualType();
6567   }
6568 
6569   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6570   NewT.setHasBaseTypeAsWritten(true);
6571   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6572   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6573     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6574   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6575   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6576   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6577     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6578   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6579   return Result;
6580 }
6581 
6582 template<typename Derived>
6583 QualType
6584 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6585                                                ObjCObjectPointerTypeLoc TL) {
6586   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6587   if (PointeeType.isNull())
6588     return QualType();
6589 
6590   QualType Result = TL.getType();
6591   if (getDerived().AlwaysRebuild() ||
6592       PointeeType != TL.getPointeeLoc().getType()) {
6593     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6594                                                        TL.getStarLoc());
6595     if (Result.isNull())
6596       return QualType();
6597   }
6598 
6599   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6600   NewT.setStarLoc(TL.getStarLoc());
6601   return Result;
6602 }
6603 
6604 //===----------------------------------------------------------------------===//
6605 // Statement transformation
6606 //===----------------------------------------------------------------------===//
6607 template<typename Derived>
6608 StmtResult
6609 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6610   return S;
6611 }
6612 
6613 template<typename Derived>
6614 StmtResult
6615 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6616   return getDerived().TransformCompoundStmt(S, false);
6617 }
6618 
6619 template<typename Derived>
6620 StmtResult
6621 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6622                                               bool IsStmtExpr) {
6623   Sema::CompoundScopeRAII CompoundScope(getSema());
6624 
6625   const Stmt *ExprResult = S->getStmtExprResult();
6626   bool SubStmtInvalid = false;
6627   bool SubStmtChanged = false;
6628   SmallVector<Stmt*, 8> Statements;
6629   for (auto *B : S->body()) {
6630     StmtResult Result = getDerived().TransformStmt(
6631         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
6632 
6633     if (Result.isInvalid()) {
6634       // Immediately fail if this was a DeclStmt, since it's very
6635       // likely that this will cause problems for future statements.
6636       if (isa<DeclStmt>(B))
6637         return StmtError();
6638 
6639       // Otherwise, just keep processing substatements and fail later.
6640       SubStmtInvalid = true;
6641       continue;
6642     }
6643 
6644     SubStmtChanged = SubStmtChanged || Result.get() != B;
6645     Statements.push_back(Result.getAs<Stmt>());
6646   }
6647 
6648   if (SubStmtInvalid)
6649     return StmtError();
6650 
6651   if (!getDerived().AlwaysRebuild() &&
6652       !SubStmtChanged)
6653     return S;
6654 
6655   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6656                                           Statements,
6657                                           S->getRBracLoc(),
6658                                           IsStmtExpr);
6659 }
6660 
6661 template<typename Derived>
6662 StmtResult
6663 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6664   ExprResult LHS, RHS;
6665   {
6666     EnterExpressionEvaluationContext Unevaluated(
6667         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6668 
6669     // Transform the left-hand case value.
6670     LHS = getDerived().TransformExpr(S->getLHS());
6671     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6672     if (LHS.isInvalid())
6673       return StmtError();
6674 
6675     // Transform the right-hand case value (for the GNU case-range extension).
6676     RHS = getDerived().TransformExpr(S->getRHS());
6677     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6678     if (RHS.isInvalid())
6679       return StmtError();
6680   }
6681 
6682   // Build the case statement.
6683   // Case statements are always rebuilt so that they will attached to their
6684   // transformed switch statement.
6685   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6686                                                        LHS.get(),
6687                                                        S->getEllipsisLoc(),
6688                                                        RHS.get(),
6689                                                        S->getColonLoc());
6690   if (Case.isInvalid())
6691     return StmtError();
6692 
6693   // Transform the statement following the case
6694   StmtResult SubStmt =
6695       getDerived().TransformStmt(S->getSubStmt());
6696   if (SubStmt.isInvalid())
6697     return StmtError();
6698 
6699   // Attach the body to the case statement
6700   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6701 }
6702 
6703 template <typename Derived>
6704 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6705   // Transform the statement following the default case
6706   StmtResult SubStmt =
6707       getDerived().TransformStmt(S->getSubStmt());
6708   if (SubStmt.isInvalid())
6709     return StmtError();
6710 
6711   // Default statements are always rebuilt
6712   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6713                                          SubStmt.get());
6714 }
6715 
6716 template<typename Derived>
6717 StmtResult
6718 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
6719   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6720   if (SubStmt.isInvalid())
6721     return StmtError();
6722 
6723   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6724                                         S->getDecl());
6725   if (!LD)
6726     return StmtError();
6727 
6728   // If we're transforming "in-place" (we're not creating new local
6729   // declarations), assume we're replacing the old label statement
6730   // and clear out the reference to it.
6731   if (LD == S->getDecl())
6732     S->getDecl()->setStmt(nullptr);
6733 
6734   // FIXME: Pass the real colon location in.
6735   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6736                                        cast<LabelDecl>(LD), SourceLocation(),
6737                                        SubStmt.get());
6738 }
6739 
6740 template <typename Derived>
6741 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6742   if (!R)
6743     return R;
6744 
6745   switch (R->getKind()) {
6746 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6747 #define ATTR(X)
6748 #define PRAGMA_SPELLING_ATTR(X)                                                \
6749   case attr::X:                                                                \
6750     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6751 #include "clang/Basic/AttrList.inc"
6752   default:
6753     return R;
6754   }
6755 }
6756 
6757 template <typename Derived>
6758 StmtResult
6759 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
6760                                                 StmtDiscardKind SDK) {
6761   bool AttrsChanged = false;
6762   SmallVector<const Attr *, 1> Attrs;
6763 
6764   // Visit attributes and keep track if any are transformed.
6765   for (const auto *I : S->getAttrs()) {
6766     const Attr *R = getDerived().TransformAttr(I);
6767     AttrsChanged |= (I != R);
6768     Attrs.push_back(R);
6769   }
6770 
6771   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6772   if (SubStmt.isInvalid())
6773     return StmtError();
6774 
6775   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6776     return S;
6777 
6778   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6779                                             SubStmt.get());
6780 }
6781 
6782 template<typename Derived>
6783 StmtResult
6784 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6785   // Transform the initialization statement
6786   StmtResult Init = getDerived().TransformStmt(S->getInit());
6787   if (Init.isInvalid())
6788     return StmtError();
6789 
6790   // Transform the condition
6791   Sema::ConditionResult Cond = getDerived().TransformCondition(
6792       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6793       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6794                        : Sema::ConditionKind::Boolean);
6795   if (Cond.isInvalid())
6796     return StmtError();
6797 
6798   // If this is a constexpr if, determine which arm we should instantiate.
6799   llvm::Optional<bool> ConstexprConditionValue;
6800   if (S->isConstexpr())
6801     ConstexprConditionValue = Cond.getKnownValue();
6802 
6803   // Transform the "then" branch.
6804   StmtResult Then;
6805   if (!ConstexprConditionValue || *ConstexprConditionValue) {
6806     Then = getDerived().TransformStmt(S->getThen());
6807     if (Then.isInvalid())
6808       return StmtError();
6809   } else {
6810     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6811   }
6812 
6813   // Transform the "else" branch.
6814   StmtResult Else;
6815   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6816     Else = getDerived().TransformStmt(S->getElse());
6817     if (Else.isInvalid())
6818       return StmtError();
6819   }
6820 
6821   if (!getDerived().AlwaysRebuild() &&
6822       Init.get() == S->getInit() &&
6823       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6824       Then.get() == S->getThen() &&
6825       Else.get() == S->getElse())
6826     return S;
6827 
6828   return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6829                                     Init.get(), Then.get(), S->getElseLoc(),
6830                                     Else.get());
6831 }
6832 
6833 template<typename Derived>
6834 StmtResult
6835 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6836   // Transform the initialization statement
6837   StmtResult Init = getDerived().TransformStmt(S->getInit());
6838   if (Init.isInvalid())
6839     return StmtError();
6840 
6841   // Transform the condition.
6842   Sema::ConditionResult Cond = getDerived().TransformCondition(
6843       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6844       Sema::ConditionKind::Switch);
6845   if (Cond.isInvalid())
6846     return StmtError();
6847 
6848   // Rebuild the switch statement.
6849   StmtResult Switch
6850     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
6851   if (Switch.isInvalid())
6852     return StmtError();
6853 
6854   // Transform the body of the switch statement.
6855   StmtResult Body = getDerived().TransformStmt(S->getBody());
6856   if (Body.isInvalid())
6857     return StmtError();
6858 
6859   // Complete the switch statement.
6860   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6861                                             Body.get());
6862 }
6863 
6864 template<typename Derived>
6865 StmtResult
6866 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6867   // Transform the condition
6868   Sema::ConditionResult Cond = getDerived().TransformCondition(
6869       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6870       Sema::ConditionKind::Boolean);
6871   if (Cond.isInvalid())
6872     return StmtError();
6873 
6874   // Transform the body
6875   StmtResult Body = getDerived().TransformStmt(S->getBody());
6876   if (Body.isInvalid())
6877     return StmtError();
6878 
6879   if (!getDerived().AlwaysRebuild() &&
6880       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6881       Body.get() == S->getBody())
6882     return Owned(S);
6883 
6884   return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6885 }
6886 
6887 template<typename Derived>
6888 StmtResult
6889 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6890   // Transform the body
6891   StmtResult Body = getDerived().TransformStmt(S->getBody());
6892   if (Body.isInvalid())
6893     return StmtError();
6894 
6895   // Transform the condition
6896   ExprResult Cond = getDerived().TransformExpr(S->getCond());
6897   if (Cond.isInvalid())
6898     return StmtError();
6899 
6900   if (!getDerived().AlwaysRebuild() &&
6901       Cond.get() == S->getCond() &&
6902       Body.get() == S->getBody())
6903     return S;
6904 
6905   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6906                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
6907                                     S->getRParenLoc());
6908 }
6909 
6910 template<typename Derived>
6911 StmtResult
6912 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6913   if (getSema().getLangOpts().OpenMP)
6914     getSema().startOpenMPLoop();
6915 
6916   // Transform the initialization statement
6917   StmtResult Init = getDerived().TransformStmt(S->getInit());
6918   if (Init.isInvalid())
6919     return StmtError();
6920 
6921   // In OpenMP loop region loop control variable must be captured and be
6922   // private. Perform analysis of first part (if any).
6923   if (getSema().getLangOpts().OpenMP && Init.isUsable())
6924     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6925 
6926   // Transform the condition
6927   Sema::ConditionResult Cond = getDerived().TransformCondition(
6928       S->getForLoc(), S->getConditionVariable(), S->getCond(),
6929       Sema::ConditionKind::Boolean);
6930   if (Cond.isInvalid())
6931     return StmtError();
6932 
6933   // Transform the increment
6934   ExprResult Inc = getDerived().TransformExpr(S->getInc());
6935   if (Inc.isInvalid())
6936     return StmtError();
6937 
6938   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6939   if (S->getInc() && !FullInc.get())
6940     return StmtError();
6941 
6942   // Transform the body
6943   StmtResult Body = getDerived().TransformStmt(S->getBody());
6944   if (Body.isInvalid())
6945     return StmtError();
6946 
6947   if (!getDerived().AlwaysRebuild() &&
6948       Init.get() == S->getInit() &&
6949       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6950       Inc.get() == S->getInc() &&
6951       Body.get() == S->getBody())
6952     return S;
6953 
6954   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6955                                      Init.get(), Cond, FullInc,
6956                                      S->getRParenLoc(), Body.get());
6957 }
6958 
6959 template<typename Derived>
6960 StmtResult
6961 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6962   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6963                                         S->getLabel());
6964   if (!LD)
6965     return StmtError();
6966 
6967   // Goto statements must always be rebuilt, to resolve the label.
6968   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6969                                       cast<LabelDecl>(LD));
6970 }
6971 
6972 template<typename Derived>
6973 StmtResult
6974 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6975   ExprResult Target = getDerived().TransformExpr(S->getTarget());
6976   if (Target.isInvalid())
6977     return StmtError();
6978   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6979 
6980   if (!getDerived().AlwaysRebuild() &&
6981       Target.get() == S->getTarget())
6982     return S;
6983 
6984   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6985                                               Target.get());
6986 }
6987 
6988 template<typename Derived>
6989 StmtResult
6990 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6991   return S;
6992 }
6993 
6994 template<typename Derived>
6995 StmtResult
6996 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6997   return S;
6998 }
6999 
7000 template<typename Derived>
7001 StmtResult
7002 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7003   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7004                                                         /*NotCopyInit*/false);
7005   if (Result.isInvalid())
7006     return StmtError();
7007 
7008   // FIXME: We always rebuild the return statement because there is no way
7009   // to tell whether the return type of the function has changed.
7010   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7011 }
7012 
7013 template<typename Derived>
7014 StmtResult
7015 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7016   bool DeclChanged = false;
7017   SmallVector<Decl *, 4> Decls;
7018   for (auto *D : S->decls()) {
7019     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7020     if (!Transformed)
7021       return StmtError();
7022 
7023     if (Transformed != D)
7024       DeclChanged = true;
7025 
7026     Decls.push_back(Transformed);
7027   }
7028 
7029   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7030     return S;
7031 
7032   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7033 }
7034 
7035 template<typename Derived>
7036 StmtResult
7037 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7038 
7039   SmallVector<Expr*, 8> Constraints;
7040   SmallVector<Expr*, 8> Exprs;
7041   SmallVector<IdentifierInfo *, 4> Names;
7042 
7043   ExprResult AsmString;
7044   SmallVector<Expr*, 8> Clobbers;
7045 
7046   bool ExprsChanged = false;
7047 
7048   // Go through the outputs.
7049   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7050     Names.push_back(S->getOutputIdentifier(I));
7051 
7052     // No need to transform the constraint literal.
7053     Constraints.push_back(S->getOutputConstraintLiteral(I));
7054 
7055     // Transform the output expr.
7056     Expr *OutputExpr = S->getOutputExpr(I);
7057     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7058     if (Result.isInvalid())
7059       return StmtError();
7060 
7061     ExprsChanged |= Result.get() != OutputExpr;
7062 
7063     Exprs.push_back(Result.get());
7064   }
7065 
7066   // Go through the inputs.
7067   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7068     Names.push_back(S->getInputIdentifier(I));
7069 
7070     // No need to transform the constraint literal.
7071     Constraints.push_back(S->getInputConstraintLiteral(I));
7072 
7073     // Transform the input expr.
7074     Expr *InputExpr = S->getInputExpr(I);
7075     ExprResult Result = getDerived().TransformExpr(InputExpr);
7076     if (Result.isInvalid())
7077       return StmtError();
7078 
7079     ExprsChanged |= Result.get() != InputExpr;
7080 
7081     Exprs.push_back(Result.get());
7082   }
7083 
7084   // Go through the Labels.
7085   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7086     Names.push_back(S->getLabelIdentifier(I));
7087 
7088     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7089     if (Result.isInvalid())
7090       return StmtError();
7091     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7092     Exprs.push_back(Result.get());
7093   }
7094   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7095     return S;
7096 
7097   // Go through the clobbers.
7098   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7099     Clobbers.push_back(S->getClobberStringLiteral(I));
7100 
7101   // No need to transform the asm string literal.
7102   AsmString = S->getAsmString();
7103   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7104                                         S->isVolatile(), S->getNumOutputs(),
7105                                         S->getNumInputs(), Names.data(),
7106                                         Constraints, Exprs, AsmString.get(),
7107                                         Clobbers, S->getNumLabels(),
7108                                         S->getRParenLoc());
7109 }
7110 
7111 template<typename Derived>
7112 StmtResult
7113 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7114   ArrayRef<Token> AsmToks =
7115     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7116 
7117   bool HadError = false, HadChange = false;
7118 
7119   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7120   SmallVector<Expr*, 8> TransformedExprs;
7121   TransformedExprs.reserve(SrcExprs.size());
7122   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7123     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7124     if (!Result.isUsable()) {
7125       HadError = true;
7126     } else {
7127       HadChange |= (Result.get() != SrcExprs[i]);
7128       TransformedExprs.push_back(Result.get());
7129     }
7130   }
7131 
7132   if (HadError) return StmtError();
7133   if (!HadChange && !getDerived().AlwaysRebuild())
7134     return Owned(S);
7135 
7136   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7137                                        AsmToks, S->getAsmString(),
7138                                        S->getNumOutputs(), S->getNumInputs(),
7139                                        S->getAllConstraints(), S->getClobbers(),
7140                                        TransformedExprs, S->getEndLoc());
7141 }
7142 
7143 // C++ Coroutines TS
7144 
7145 template<typename Derived>
7146 StmtResult
7147 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7148   auto *ScopeInfo = SemaRef.getCurFunction();
7149   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7150   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7151          ScopeInfo->NeedsCoroutineSuspends &&
7152          ScopeInfo->CoroutineSuspends.first == nullptr &&
7153          ScopeInfo->CoroutineSuspends.second == nullptr &&
7154          "expected clean scope info");
7155 
7156   // Set that we have (possibly-invalid) suspend points before we do anything
7157   // that may fail.
7158   ScopeInfo->setNeedsCoroutineSuspends(false);
7159 
7160   // The new CoroutinePromise object needs to be built and put into the current
7161   // FunctionScopeInfo before any transformations or rebuilding occurs.
7162   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7163     return StmtError();
7164   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7165   if (!Promise)
7166     return StmtError();
7167   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7168   ScopeInfo->CoroutinePromise = Promise;
7169 
7170   // Transform the implicit coroutine statements we built during the initial
7171   // parse.
7172   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7173   if (InitSuspend.isInvalid())
7174     return StmtError();
7175   StmtResult FinalSuspend =
7176       getDerived().TransformStmt(S->getFinalSuspendStmt());
7177   if (FinalSuspend.isInvalid())
7178     return StmtError();
7179   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7180   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7181 
7182   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7183   if (BodyRes.isInvalid())
7184     return StmtError();
7185 
7186   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7187   if (Builder.isInvalid())
7188     return StmtError();
7189 
7190   Expr *ReturnObject = S->getReturnValueInit();
7191   assert(ReturnObject && "the return object is expected to be valid");
7192   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7193                                                      /*NoCopyInit*/ false);
7194   if (Res.isInvalid())
7195     return StmtError();
7196   Builder.ReturnValue = Res.get();
7197 
7198   if (S->hasDependentPromiseType()) {
7199     // PR41909: We may find a generic coroutine lambda definition within a
7200     // template function that is being instantiated. In this case, the lambda
7201     // will have a dependent promise type, until it is used in an expression
7202     // that creates an instantiation with a non-dependent promise type. We
7203     // should not assert or build coroutine dependent statements for such a
7204     // generic lambda.
7205     auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD);
7206     if (!MD || !MD->getParent()->isGenericLambda()) {
7207       assert(!Promise->getType()->isDependentType() &&
7208              "the promise type must no longer be dependent");
7209       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7210              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7211              "these nodes should not have been built yet");
7212       if (!Builder.buildDependentStatements())
7213         return StmtError();
7214     }
7215   } else {
7216     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7217       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7218       if (Res.isInvalid())
7219         return StmtError();
7220       Builder.OnFallthrough = Res.get();
7221     }
7222 
7223     if (auto *OnException = S->getExceptionHandler()) {
7224       StmtResult Res = getDerived().TransformStmt(OnException);
7225       if (Res.isInvalid())
7226         return StmtError();
7227       Builder.OnException = Res.get();
7228     }
7229 
7230     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7231       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7232       if (Res.isInvalid())
7233         return StmtError();
7234       Builder.ReturnStmtOnAllocFailure = Res.get();
7235     }
7236 
7237     // Transform any additional statements we may have already built
7238     assert(S->getAllocate() && S->getDeallocate() &&
7239            "allocation and deallocation calls must already be built");
7240     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7241     if (AllocRes.isInvalid())
7242       return StmtError();
7243     Builder.Allocate = AllocRes.get();
7244 
7245     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7246     if (DeallocRes.isInvalid())
7247       return StmtError();
7248     Builder.Deallocate = DeallocRes.get();
7249 
7250     assert(S->getResultDecl() && "ResultDecl must already be built");
7251     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7252     if (ResultDecl.isInvalid())
7253       return StmtError();
7254     Builder.ResultDecl = ResultDecl.get();
7255 
7256     if (auto *ReturnStmt = S->getReturnStmt()) {
7257       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7258       if (Res.isInvalid())
7259         return StmtError();
7260       Builder.ReturnStmt = Res.get();
7261     }
7262   }
7263 
7264   return getDerived().RebuildCoroutineBodyStmt(Builder);
7265 }
7266 
7267 template<typename Derived>
7268 StmtResult
7269 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7270   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7271                                                         /*NotCopyInit*/false);
7272   if (Result.isInvalid())
7273     return StmtError();
7274 
7275   // Always rebuild; we don't know if this needs to be injected into a new
7276   // context or if the promise type has changed.
7277   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7278                                           S->isImplicit());
7279 }
7280 
7281 template<typename Derived>
7282 ExprResult
7283 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7284   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7285                                                         /*NotCopyInit*/false);
7286   if (Result.isInvalid())
7287     return ExprError();
7288 
7289   // Always rebuild; we don't know if this needs to be injected into a new
7290   // context or if the promise type has changed.
7291   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7292                                          E->isImplicit());
7293 }
7294 
7295 template <typename Derived>
7296 ExprResult
7297 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7298   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7299                                                         /*NotCopyInit*/ false);
7300   if (OperandResult.isInvalid())
7301     return ExprError();
7302 
7303   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7304           E->getOperatorCoawaitLookup());
7305 
7306   if (LookupResult.isInvalid())
7307     return ExprError();
7308 
7309   // Always rebuild; we don't know if this needs to be injected into a new
7310   // context or if the promise type has changed.
7311   return getDerived().RebuildDependentCoawaitExpr(
7312       E->getKeywordLoc(), OperandResult.get(),
7313       cast<UnresolvedLookupExpr>(LookupResult.get()));
7314 }
7315 
7316 template<typename Derived>
7317 ExprResult
7318 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7319   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7320                                                         /*NotCopyInit*/false);
7321   if (Result.isInvalid())
7322     return ExprError();
7323 
7324   // Always rebuild; we don't know if this needs to be injected into a new
7325   // context or if the promise type has changed.
7326   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7327 }
7328 
7329 // Objective-C Statements.
7330 
7331 template<typename Derived>
7332 StmtResult
7333 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7334   // Transform the body of the @try.
7335   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7336   if (TryBody.isInvalid())
7337     return StmtError();
7338 
7339   // Transform the @catch statements (if present).
7340   bool AnyCatchChanged = false;
7341   SmallVector<Stmt*, 8> CatchStmts;
7342   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7343     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7344     if (Catch.isInvalid())
7345       return StmtError();
7346     if (Catch.get() != S->getCatchStmt(I))
7347       AnyCatchChanged = true;
7348     CatchStmts.push_back(Catch.get());
7349   }
7350 
7351   // Transform the @finally statement (if present).
7352   StmtResult Finally;
7353   if (S->getFinallyStmt()) {
7354     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7355     if (Finally.isInvalid())
7356       return StmtError();
7357   }
7358 
7359   // If nothing changed, just retain this statement.
7360   if (!getDerived().AlwaysRebuild() &&
7361       TryBody.get() == S->getTryBody() &&
7362       !AnyCatchChanged &&
7363       Finally.get() == S->getFinallyStmt())
7364     return S;
7365 
7366   // Build a new statement.
7367   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7368                                            CatchStmts, Finally.get());
7369 }
7370 
7371 template<typename Derived>
7372 StmtResult
7373 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7374   // Transform the @catch parameter, if there is one.
7375   VarDecl *Var = nullptr;
7376   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7377     TypeSourceInfo *TSInfo = nullptr;
7378     if (FromVar->getTypeSourceInfo()) {
7379       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7380       if (!TSInfo)
7381         return StmtError();
7382     }
7383 
7384     QualType T;
7385     if (TSInfo)
7386       T = TSInfo->getType();
7387     else {
7388       T = getDerived().TransformType(FromVar->getType());
7389       if (T.isNull())
7390         return StmtError();
7391     }
7392 
7393     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7394     if (!Var)
7395       return StmtError();
7396   }
7397 
7398   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7399   if (Body.isInvalid())
7400     return StmtError();
7401 
7402   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7403                                              S->getRParenLoc(),
7404                                              Var, Body.get());
7405 }
7406 
7407 template<typename Derived>
7408 StmtResult
7409 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7410   // Transform the body.
7411   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7412   if (Body.isInvalid())
7413     return StmtError();
7414 
7415   // If nothing changed, just retain this statement.
7416   if (!getDerived().AlwaysRebuild() &&
7417       Body.get() == S->getFinallyBody())
7418     return S;
7419 
7420   // Build a new statement.
7421   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7422                                                Body.get());
7423 }
7424 
7425 template<typename Derived>
7426 StmtResult
7427 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7428   ExprResult Operand;
7429   if (S->getThrowExpr()) {
7430     Operand = getDerived().TransformExpr(S->getThrowExpr());
7431     if (Operand.isInvalid())
7432       return StmtError();
7433   }
7434 
7435   if (!getDerived().AlwaysRebuild() &&
7436       Operand.get() == S->getThrowExpr())
7437     return S;
7438 
7439   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7440 }
7441 
7442 template<typename Derived>
7443 StmtResult
7444 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7445                                                   ObjCAtSynchronizedStmt *S) {
7446   // Transform the object we are locking.
7447   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7448   if (Object.isInvalid())
7449     return StmtError();
7450   Object =
7451     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7452                                                   Object.get());
7453   if (Object.isInvalid())
7454     return StmtError();
7455 
7456   // Transform the body.
7457   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7458   if (Body.isInvalid())
7459     return StmtError();
7460 
7461   // If nothing change, just retain the current statement.
7462   if (!getDerived().AlwaysRebuild() &&
7463       Object.get() == S->getSynchExpr() &&
7464       Body.get() == S->getSynchBody())
7465     return S;
7466 
7467   // Build a new statement.
7468   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7469                                                     Object.get(), Body.get());
7470 }
7471 
7472 template<typename Derived>
7473 StmtResult
7474 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7475                                               ObjCAutoreleasePoolStmt *S) {
7476   // Transform the body.
7477   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7478   if (Body.isInvalid())
7479     return StmtError();
7480 
7481   // If nothing changed, just retain this statement.
7482   if (!getDerived().AlwaysRebuild() &&
7483       Body.get() == S->getSubStmt())
7484     return S;
7485 
7486   // Build a new statement.
7487   return getDerived().RebuildObjCAutoreleasePoolStmt(
7488                         S->getAtLoc(), Body.get());
7489 }
7490 
7491 template<typename Derived>
7492 StmtResult
7493 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7494                                                   ObjCForCollectionStmt *S) {
7495   // Transform the element statement.
7496   StmtResult Element =
7497       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7498   if (Element.isInvalid())
7499     return StmtError();
7500 
7501   // Transform the collection expression.
7502   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7503   if (Collection.isInvalid())
7504     return StmtError();
7505 
7506   // Transform the body.
7507   StmtResult Body = getDerived().TransformStmt(S->getBody());
7508   if (Body.isInvalid())
7509     return StmtError();
7510 
7511   // If nothing changed, just retain this statement.
7512   if (!getDerived().AlwaysRebuild() &&
7513       Element.get() == S->getElement() &&
7514       Collection.get() == S->getCollection() &&
7515       Body.get() == S->getBody())
7516     return S;
7517 
7518   // Build a new statement.
7519   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7520                                                    Element.get(),
7521                                                    Collection.get(),
7522                                                    S->getRParenLoc(),
7523                                                    Body.get());
7524 }
7525 
7526 template <typename Derived>
7527 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7528   // Transform the exception declaration, if any.
7529   VarDecl *Var = nullptr;
7530   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7531     TypeSourceInfo *T =
7532         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7533     if (!T)
7534       return StmtError();
7535 
7536     Var = getDerived().RebuildExceptionDecl(
7537         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7538         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7539     if (!Var || Var->isInvalidDecl())
7540       return StmtError();
7541   }
7542 
7543   // Transform the actual exception handler.
7544   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7545   if (Handler.isInvalid())
7546     return StmtError();
7547 
7548   if (!getDerived().AlwaysRebuild() && !Var &&
7549       Handler.get() == S->getHandlerBlock())
7550     return S;
7551 
7552   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7553 }
7554 
7555 template <typename Derived>
7556 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7557   // Transform the try block itself.
7558   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7559   if (TryBlock.isInvalid())
7560     return StmtError();
7561 
7562   // Transform the handlers.
7563   bool HandlerChanged = false;
7564   SmallVector<Stmt *, 8> Handlers;
7565   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7566     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7567     if (Handler.isInvalid())
7568       return StmtError();
7569 
7570     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7571     Handlers.push_back(Handler.getAs<Stmt>());
7572   }
7573 
7574   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7575       !HandlerChanged)
7576     return S;
7577 
7578   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7579                                         Handlers);
7580 }
7581 
7582 template<typename Derived>
7583 StmtResult
7584 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7585   StmtResult Init =
7586       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7587   if (Init.isInvalid())
7588     return StmtError();
7589 
7590   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7591   if (Range.isInvalid())
7592     return StmtError();
7593 
7594   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7595   if (Begin.isInvalid())
7596     return StmtError();
7597   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7598   if (End.isInvalid())
7599     return StmtError();
7600 
7601   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7602   if (Cond.isInvalid())
7603     return StmtError();
7604   if (Cond.get())
7605     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7606   if (Cond.isInvalid())
7607     return StmtError();
7608   if (Cond.get())
7609     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7610 
7611   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7612   if (Inc.isInvalid())
7613     return StmtError();
7614   if (Inc.get())
7615     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7616 
7617   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7618   if (LoopVar.isInvalid())
7619     return StmtError();
7620 
7621   StmtResult NewStmt = S;
7622   if (getDerived().AlwaysRebuild() ||
7623       Init.get() != S->getInit() ||
7624       Range.get() != S->getRangeStmt() ||
7625       Begin.get() != S->getBeginStmt() ||
7626       End.get() != S->getEndStmt() ||
7627       Cond.get() != S->getCond() ||
7628       Inc.get() != S->getInc() ||
7629       LoopVar.get() != S->getLoopVarStmt()) {
7630     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7631                                                   S->getCoawaitLoc(), Init.get(),
7632                                                   S->getColonLoc(), Range.get(),
7633                                                   Begin.get(), End.get(),
7634                                                   Cond.get(),
7635                                                   Inc.get(), LoopVar.get(),
7636                                                   S->getRParenLoc());
7637     if (NewStmt.isInvalid())
7638       return StmtError();
7639   }
7640 
7641   StmtResult Body = getDerived().TransformStmt(S->getBody());
7642   if (Body.isInvalid())
7643     return StmtError();
7644 
7645   // Body has changed but we didn't rebuild the for-range statement. Rebuild
7646   // it now so we have a new statement to attach the body to.
7647   if (Body.get() != S->getBody() && NewStmt.get() == S) {
7648     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7649                                                   S->getCoawaitLoc(), Init.get(),
7650                                                   S->getColonLoc(), Range.get(),
7651                                                   Begin.get(), End.get(),
7652                                                   Cond.get(),
7653                                                   Inc.get(), LoopVar.get(),
7654                                                   S->getRParenLoc());
7655     if (NewStmt.isInvalid())
7656       return StmtError();
7657   }
7658 
7659   if (NewStmt.get() == S)
7660     return S;
7661 
7662   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7663 }
7664 
7665 template<typename Derived>
7666 StmtResult
7667 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7668                                                     MSDependentExistsStmt *S) {
7669   // Transform the nested-name-specifier, if any.
7670   NestedNameSpecifierLoc QualifierLoc;
7671   if (S->getQualifierLoc()) {
7672     QualifierLoc
7673       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7674     if (!QualifierLoc)
7675       return StmtError();
7676   }
7677 
7678   // Transform the declaration name.
7679   DeclarationNameInfo NameInfo = S->getNameInfo();
7680   if (NameInfo.getName()) {
7681     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7682     if (!NameInfo.getName())
7683       return StmtError();
7684   }
7685 
7686   // Check whether anything changed.
7687   if (!getDerived().AlwaysRebuild() &&
7688       QualifierLoc == S->getQualifierLoc() &&
7689       NameInfo.getName() == S->getNameInfo().getName())
7690     return S;
7691 
7692   // Determine whether this name exists, if we can.
7693   CXXScopeSpec SS;
7694   SS.Adopt(QualifierLoc);
7695   bool Dependent = false;
7696   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7697   case Sema::IER_Exists:
7698     if (S->isIfExists())
7699       break;
7700 
7701     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7702 
7703   case Sema::IER_DoesNotExist:
7704     if (S->isIfNotExists())
7705       break;
7706 
7707     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7708 
7709   case Sema::IER_Dependent:
7710     Dependent = true;
7711     break;
7712 
7713   case Sema::IER_Error:
7714     return StmtError();
7715   }
7716 
7717   // We need to continue with the instantiation, so do so now.
7718   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7719   if (SubStmt.isInvalid())
7720     return StmtError();
7721 
7722   // If we have resolved the name, just transform to the substatement.
7723   if (!Dependent)
7724     return SubStmt;
7725 
7726   // The name is still dependent, so build a dependent expression again.
7727   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7728                                                    S->isIfExists(),
7729                                                    QualifierLoc,
7730                                                    NameInfo,
7731                                                    SubStmt.get());
7732 }
7733 
7734 template<typename Derived>
7735 ExprResult
7736 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7737   NestedNameSpecifierLoc QualifierLoc;
7738   if (E->getQualifierLoc()) {
7739     QualifierLoc
7740     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7741     if (!QualifierLoc)
7742       return ExprError();
7743   }
7744 
7745   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7746     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7747   if (!PD)
7748     return ExprError();
7749 
7750   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7751   if (Base.isInvalid())
7752     return ExprError();
7753 
7754   return new (SemaRef.getASTContext())
7755       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7756                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7757                         QualifierLoc, E->getMemberLoc());
7758 }
7759 
7760 template <typename Derived>
7761 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7762     MSPropertySubscriptExpr *E) {
7763   auto BaseRes = getDerived().TransformExpr(E->getBase());
7764   if (BaseRes.isInvalid())
7765     return ExprError();
7766   auto IdxRes = getDerived().TransformExpr(E->getIdx());
7767   if (IdxRes.isInvalid())
7768     return ExprError();
7769 
7770   if (!getDerived().AlwaysRebuild() &&
7771       BaseRes.get() == E->getBase() &&
7772       IdxRes.get() == E->getIdx())
7773     return E;
7774 
7775   return getDerived().RebuildArraySubscriptExpr(
7776       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7777 }
7778 
7779 template <typename Derived>
7780 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7781   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7782   if (TryBlock.isInvalid())
7783     return StmtError();
7784 
7785   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7786   if (Handler.isInvalid())
7787     return StmtError();
7788 
7789   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7790       Handler.get() == S->getHandler())
7791     return S;
7792 
7793   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7794                                         TryBlock.get(), Handler.get());
7795 }
7796 
7797 template <typename Derived>
7798 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7799   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7800   if (Block.isInvalid())
7801     return StmtError();
7802 
7803   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7804 }
7805 
7806 template <typename Derived>
7807 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7808   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7809   if (FilterExpr.isInvalid())
7810     return StmtError();
7811 
7812   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7813   if (Block.isInvalid())
7814     return StmtError();
7815 
7816   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7817                                            Block.get());
7818 }
7819 
7820 template <typename Derived>
7821 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7822   if (isa<SEHFinallyStmt>(Handler))
7823     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7824   else
7825     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7826 }
7827 
7828 template<typename Derived>
7829 StmtResult
7830 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7831   return S;
7832 }
7833 
7834 //===----------------------------------------------------------------------===//
7835 // OpenMP directive transformation
7836 //===----------------------------------------------------------------------===//
7837 template <typename Derived>
7838 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7839     OMPExecutableDirective *D) {
7840 
7841   // Transform the clauses
7842   llvm::SmallVector<OMPClause *, 16> TClauses;
7843   ArrayRef<OMPClause *> Clauses = D->clauses();
7844   TClauses.reserve(Clauses.size());
7845   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7846        I != E; ++I) {
7847     if (*I) {
7848       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7849       OMPClause *Clause = getDerived().TransformOMPClause(*I);
7850       getDerived().getSema().EndOpenMPClause();
7851       if (Clause)
7852         TClauses.push_back(Clause);
7853     } else {
7854       TClauses.push_back(nullptr);
7855     }
7856   }
7857   StmtResult AssociatedStmt;
7858   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7859     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7860                                                   /*CurScope=*/nullptr);
7861     StmtResult Body;
7862     {
7863       Sema::CompoundScopeRAII CompoundScope(getSema());
7864       Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
7865       Body = getDerived().TransformStmt(CS);
7866     }
7867     AssociatedStmt =
7868         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7869     if (AssociatedStmt.isInvalid()) {
7870       return StmtError();
7871     }
7872   }
7873   if (TClauses.size() != Clauses.size()) {
7874     return StmtError();
7875   }
7876 
7877   // Transform directive name for 'omp critical' directive.
7878   DeclarationNameInfo DirName;
7879   if (D->getDirectiveKind() == OMPD_critical) {
7880     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7881     DirName = getDerived().TransformDeclarationNameInfo(DirName);
7882   }
7883   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7884   if (D->getDirectiveKind() == OMPD_cancellation_point) {
7885     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7886   } else if (D->getDirectiveKind() == OMPD_cancel) {
7887     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7888   }
7889 
7890   return getDerived().RebuildOMPExecutableDirective(
7891       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7892       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
7893 }
7894 
7895 template <typename Derived>
7896 StmtResult
7897 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7898   DeclarationNameInfo DirName;
7899   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7900                                              D->getBeginLoc());
7901   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7902   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7903   return Res;
7904 }
7905 
7906 template <typename Derived>
7907 StmtResult
7908 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7909   DeclarationNameInfo DirName;
7910   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7911                                              D->getBeginLoc());
7912   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7913   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7914   return Res;
7915 }
7916 
7917 template <typename Derived>
7918 StmtResult
7919 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7920   DeclarationNameInfo DirName;
7921   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7922                                              D->getBeginLoc());
7923   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7924   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7925   return Res;
7926 }
7927 
7928 template <typename Derived>
7929 StmtResult
7930 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7931   DeclarationNameInfo DirName;
7932   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7933                                              D->getBeginLoc());
7934   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7935   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7936   return Res;
7937 }
7938 
7939 template <typename Derived>
7940 StmtResult
7941 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7942   DeclarationNameInfo DirName;
7943   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7944                                              D->getBeginLoc());
7945   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7946   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7947   return Res;
7948 }
7949 
7950 template <typename Derived>
7951 StmtResult
7952 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7953   DeclarationNameInfo DirName;
7954   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7955                                              D->getBeginLoc());
7956   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7957   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7958   return Res;
7959 }
7960 
7961 template <typename Derived>
7962 StmtResult
7963 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7964   DeclarationNameInfo DirName;
7965   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7966                                              D->getBeginLoc());
7967   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7968   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7969   return Res;
7970 }
7971 
7972 template <typename Derived>
7973 StmtResult
7974 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
7975   DeclarationNameInfo DirName;
7976   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
7977                                              D->getBeginLoc());
7978   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7979   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7980   return Res;
7981 }
7982 
7983 template <typename Derived>
7984 StmtResult
7985 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
7986   getDerived().getSema().StartOpenMPDSABlock(
7987       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
7988   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7989   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7990   return Res;
7991 }
7992 
7993 template <typename Derived>
7994 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
7995     OMPParallelForDirective *D) {
7996   DeclarationNameInfo DirName;
7997   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
7998                                              nullptr, D->getBeginLoc());
7999   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8000   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8001   return Res;
8002 }
8003 
8004 template <typename Derived>
8005 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8006     OMPParallelForSimdDirective *D) {
8007   DeclarationNameInfo DirName;
8008   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8009                                              nullptr, D->getBeginLoc());
8010   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8011   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8012   return Res;
8013 }
8014 
8015 template <typename Derived>
8016 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8017     OMPParallelSectionsDirective *D) {
8018   DeclarationNameInfo DirName;
8019   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8020                                              nullptr, D->getBeginLoc());
8021   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8022   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8023   return Res;
8024 }
8025 
8026 template <typename Derived>
8027 StmtResult
8028 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8029   DeclarationNameInfo DirName;
8030   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8031                                              D->getBeginLoc());
8032   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8033   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8034   return Res;
8035 }
8036 
8037 template <typename Derived>
8038 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8039     OMPTaskyieldDirective *D) {
8040   DeclarationNameInfo DirName;
8041   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8042                                              D->getBeginLoc());
8043   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8044   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8045   return Res;
8046 }
8047 
8048 template <typename Derived>
8049 StmtResult
8050 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8051   DeclarationNameInfo DirName;
8052   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8053                                              D->getBeginLoc());
8054   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8055   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8056   return Res;
8057 }
8058 
8059 template <typename Derived>
8060 StmtResult
8061 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8062   DeclarationNameInfo DirName;
8063   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8064                                              D->getBeginLoc());
8065   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8066   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8067   return Res;
8068 }
8069 
8070 template <typename Derived>
8071 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8072     OMPTaskgroupDirective *D) {
8073   DeclarationNameInfo DirName;
8074   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8075                                              D->getBeginLoc());
8076   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8077   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8078   return Res;
8079 }
8080 
8081 template <typename Derived>
8082 StmtResult
8083 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8084   DeclarationNameInfo DirName;
8085   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8086                                              D->getBeginLoc());
8087   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8088   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8089   return Res;
8090 }
8091 
8092 template <typename Derived>
8093 StmtResult
8094 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8095   DeclarationNameInfo DirName;
8096   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8097                                              D->getBeginLoc());
8098   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8099   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8100   return Res;
8101 }
8102 
8103 template <typename Derived>
8104 StmtResult
8105 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8106   DeclarationNameInfo DirName;
8107   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8108                                              D->getBeginLoc());
8109   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8110   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8111   return Res;
8112 }
8113 
8114 template <typename Derived>
8115 StmtResult
8116 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8117   DeclarationNameInfo DirName;
8118   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8119                                              D->getBeginLoc());
8120   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8121   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8122   return Res;
8123 }
8124 
8125 template <typename Derived>
8126 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8127     OMPTargetDataDirective *D) {
8128   DeclarationNameInfo DirName;
8129   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8130                                              D->getBeginLoc());
8131   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8132   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8133   return Res;
8134 }
8135 
8136 template <typename Derived>
8137 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8138     OMPTargetEnterDataDirective *D) {
8139   DeclarationNameInfo DirName;
8140   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8141                                              nullptr, D->getBeginLoc());
8142   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8143   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8144   return Res;
8145 }
8146 
8147 template <typename Derived>
8148 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8149     OMPTargetExitDataDirective *D) {
8150   DeclarationNameInfo DirName;
8151   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8152                                              nullptr, D->getBeginLoc());
8153   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8154   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8155   return Res;
8156 }
8157 
8158 template <typename Derived>
8159 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8160     OMPTargetParallelDirective *D) {
8161   DeclarationNameInfo DirName;
8162   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8163                                              nullptr, D->getBeginLoc());
8164   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8165   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8166   return Res;
8167 }
8168 
8169 template <typename Derived>
8170 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8171     OMPTargetParallelForDirective *D) {
8172   DeclarationNameInfo DirName;
8173   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8174                                              nullptr, D->getBeginLoc());
8175   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8176   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8177   return Res;
8178 }
8179 
8180 template <typename Derived>
8181 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8182     OMPTargetUpdateDirective *D) {
8183   DeclarationNameInfo DirName;
8184   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8185                                              nullptr, D->getBeginLoc());
8186   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8187   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8188   return Res;
8189 }
8190 
8191 template <typename Derived>
8192 StmtResult
8193 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8194   DeclarationNameInfo DirName;
8195   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8196                                              D->getBeginLoc());
8197   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8198   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8199   return Res;
8200 }
8201 
8202 template <typename Derived>
8203 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8204     OMPCancellationPointDirective *D) {
8205   DeclarationNameInfo DirName;
8206   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8207                                              nullptr, D->getBeginLoc());
8208   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8209   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8210   return Res;
8211 }
8212 
8213 template <typename Derived>
8214 StmtResult
8215 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8216   DeclarationNameInfo DirName;
8217   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8218                                              D->getBeginLoc());
8219   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8220   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8221   return Res;
8222 }
8223 
8224 template <typename Derived>
8225 StmtResult
8226 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8227   DeclarationNameInfo DirName;
8228   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8229                                              D->getBeginLoc());
8230   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8231   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8232   return Res;
8233 }
8234 
8235 template <typename Derived>
8236 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8237     OMPTaskLoopSimdDirective *D) {
8238   DeclarationNameInfo DirName;
8239   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8240                                              nullptr, D->getBeginLoc());
8241   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8242   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8243   return Res;
8244 }
8245 
8246 template <typename Derived>
8247 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8248     OMPDistributeDirective *D) {
8249   DeclarationNameInfo DirName;
8250   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8251                                              D->getBeginLoc());
8252   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8253   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8254   return Res;
8255 }
8256 
8257 template <typename Derived>
8258 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8259     OMPDistributeParallelForDirective *D) {
8260   DeclarationNameInfo DirName;
8261   getDerived().getSema().StartOpenMPDSABlock(
8262       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8263   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8264   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8265   return Res;
8266 }
8267 
8268 template <typename Derived>
8269 StmtResult
8270 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8271     OMPDistributeParallelForSimdDirective *D) {
8272   DeclarationNameInfo DirName;
8273   getDerived().getSema().StartOpenMPDSABlock(
8274       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8275   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8276   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8277   return Res;
8278 }
8279 
8280 template <typename Derived>
8281 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8282     OMPDistributeSimdDirective *D) {
8283   DeclarationNameInfo DirName;
8284   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8285                                              nullptr, D->getBeginLoc());
8286   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8287   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8288   return Res;
8289 }
8290 
8291 template <typename Derived>
8292 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8293     OMPTargetParallelForSimdDirective *D) {
8294   DeclarationNameInfo DirName;
8295   getDerived().getSema().StartOpenMPDSABlock(
8296       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8297   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8298   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8299   return Res;
8300 }
8301 
8302 template <typename Derived>
8303 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8304     OMPTargetSimdDirective *D) {
8305   DeclarationNameInfo DirName;
8306   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8307                                              D->getBeginLoc());
8308   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8309   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8310   return Res;
8311 }
8312 
8313 template <typename Derived>
8314 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8315     OMPTeamsDistributeDirective *D) {
8316   DeclarationNameInfo DirName;
8317   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8318                                              nullptr, D->getBeginLoc());
8319   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8320   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8321   return Res;
8322 }
8323 
8324 template <typename Derived>
8325 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8326     OMPTeamsDistributeSimdDirective *D) {
8327   DeclarationNameInfo DirName;
8328   getDerived().getSema().StartOpenMPDSABlock(
8329       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8330   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8331   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8332   return Res;
8333 }
8334 
8335 template <typename Derived>
8336 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8337     OMPTeamsDistributeParallelForSimdDirective *D) {
8338   DeclarationNameInfo DirName;
8339   getDerived().getSema().StartOpenMPDSABlock(
8340       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8341       D->getBeginLoc());
8342   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8343   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8344   return Res;
8345 }
8346 
8347 template <typename Derived>
8348 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8349     OMPTeamsDistributeParallelForDirective *D) {
8350   DeclarationNameInfo DirName;
8351   getDerived().getSema().StartOpenMPDSABlock(
8352       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8353   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8354   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8355   return Res;
8356 }
8357 
8358 template <typename Derived>
8359 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8360     OMPTargetTeamsDirective *D) {
8361   DeclarationNameInfo DirName;
8362   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8363                                              nullptr, D->getBeginLoc());
8364   auto Res = getDerived().TransformOMPExecutableDirective(D);
8365   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8366   return Res;
8367 }
8368 
8369 template <typename Derived>
8370 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8371     OMPTargetTeamsDistributeDirective *D) {
8372   DeclarationNameInfo DirName;
8373   getDerived().getSema().StartOpenMPDSABlock(
8374       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8375   auto Res = getDerived().TransformOMPExecutableDirective(D);
8376   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8377   return Res;
8378 }
8379 
8380 template <typename Derived>
8381 StmtResult
8382 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8383     OMPTargetTeamsDistributeParallelForDirective *D) {
8384   DeclarationNameInfo DirName;
8385   getDerived().getSema().StartOpenMPDSABlock(
8386       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8387       D->getBeginLoc());
8388   auto Res = getDerived().TransformOMPExecutableDirective(D);
8389   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8390   return Res;
8391 }
8392 
8393 template <typename Derived>
8394 StmtResult TreeTransform<Derived>::
8395     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8396         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8397   DeclarationNameInfo DirName;
8398   getDerived().getSema().StartOpenMPDSABlock(
8399       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8400       D->getBeginLoc());
8401   auto Res = getDerived().TransformOMPExecutableDirective(D);
8402   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8403   return Res;
8404 }
8405 
8406 template <typename Derived>
8407 StmtResult
8408 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8409     OMPTargetTeamsDistributeSimdDirective *D) {
8410   DeclarationNameInfo DirName;
8411   getDerived().getSema().StartOpenMPDSABlock(
8412       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8413   auto Res = getDerived().TransformOMPExecutableDirective(D);
8414   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8415   return Res;
8416 }
8417 
8418 
8419 //===----------------------------------------------------------------------===//
8420 // OpenMP clause transformation
8421 //===----------------------------------------------------------------------===//
8422 template <typename Derived>
8423 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8424   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8425   if (Cond.isInvalid())
8426     return nullptr;
8427   return getDerived().RebuildOMPIfClause(
8428       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8429       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8430 }
8431 
8432 template <typename Derived>
8433 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8434   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8435   if (Cond.isInvalid())
8436     return nullptr;
8437   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8438                                             C->getLParenLoc(), C->getEndLoc());
8439 }
8440 
8441 template <typename Derived>
8442 OMPClause *
8443 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8444   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8445   if (NumThreads.isInvalid())
8446     return nullptr;
8447   return getDerived().RebuildOMPNumThreadsClause(
8448       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8449 }
8450 
8451 template <typename Derived>
8452 OMPClause *
8453 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8454   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8455   if (E.isInvalid())
8456     return nullptr;
8457   return getDerived().RebuildOMPSafelenClause(
8458       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8459 }
8460 
8461 template <typename Derived>
8462 OMPClause *
8463 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8464   ExprResult E = getDerived().TransformExpr(C->getAllocator());
8465   if (E.isInvalid())
8466     return nullptr;
8467   return getDerived().RebuildOMPAllocatorClause(
8468       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8469 }
8470 
8471 template <typename Derived>
8472 OMPClause *
8473 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8474   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8475   if (E.isInvalid())
8476     return nullptr;
8477   return getDerived().RebuildOMPSimdlenClause(
8478       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8479 }
8480 
8481 template <typename Derived>
8482 OMPClause *
8483 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8484   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8485   if (E.isInvalid())
8486     return nullptr;
8487   return getDerived().RebuildOMPCollapseClause(
8488       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8489 }
8490 
8491 template <typename Derived>
8492 OMPClause *
8493 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8494   return getDerived().RebuildOMPDefaultClause(
8495       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8496       C->getLParenLoc(), C->getEndLoc());
8497 }
8498 
8499 template <typename Derived>
8500 OMPClause *
8501 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8502   return getDerived().RebuildOMPProcBindClause(
8503       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8504       C->getLParenLoc(), C->getEndLoc());
8505 }
8506 
8507 template <typename Derived>
8508 OMPClause *
8509 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8510   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8511   if (E.isInvalid())
8512     return nullptr;
8513   return getDerived().RebuildOMPScheduleClause(
8514       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8515       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8516       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8517       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8518 }
8519 
8520 template <typename Derived>
8521 OMPClause *
8522 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8523   ExprResult E;
8524   if (auto *Num = C->getNumForLoops()) {
8525     E = getDerived().TransformExpr(Num);
8526     if (E.isInvalid())
8527       return nullptr;
8528   }
8529   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8530                                               C->getLParenLoc(), E.get());
8531 }
8532 
8533 template <typename Derived>
8534 OMPClause *
8535 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8536   // No need to rebuild this clause, no template-dependent parameters.
8537   return C;
8538 }
8539 
8540 template <typename Derived>
8541 OMPClause *
8542 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8543   // No need to rebuild this clause, no template-dependent parameters.
8544   return C;
8545 }
8546 
8547 template <typename Derived>
8548 OMPClause *
8549 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8550   // No need to rebuild this clause, no template-dependent parameters.
8551   return C;
8552 }
8553 
8554 template <typename Derived>
8555 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8556   // No need to rebuild this clause, no template-dependent parameters.
8557   return C;
8558 }
8559 
8560 template <typename Derived>
8561 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8562   // No need to rebuild this clause, no template-dependent parameters.
8563   return C;
8564 }
8565 
8566 template <typename Derived>
8567 OMPClause *
8568 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8569   // No need to rebuild this clause, no template-dependent parameters.
8570   return C;
8571 }
8572 
8573 template <typename Derived>
8574 OMPClause *
8575 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8576   // No need to rebuild this clause, no template-dependent parameters.
8577   return C;
8578 }
8579 
8580 template <typename Derived>
8581 OMPClause *
8582 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8583   // No need to rebuild this clause, no template-dependent parameters.
8584   return C;
8585 }
8586 
8587 template <typename Derived>
8588 OMPClause *
8589 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8590   // No need to rebuild this clause, no template-dependent parameters.
8591   return C;
8592 }
8593 
8594 template <typename Derived>
8595 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8596   // No need to rebuild this clause, no template-dependent parameters.
8597   return C;
8598 }
8599 
8600 template <typename Derived>
8601 OMPClause *
8602 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8603   // No need to rebuild this clause, no template-dependent parameters.
8604   return C;
8605 }
8606 
8607 template <typename Derived>
8608 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8609     OMPUnifiedAddressClause *C) {
8610   llvm_unreachable("unified_address clause cannot appear in dependent context");
8611 }
8612 
8613 template <typename Derived>
8614 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8615     OMPUnifiedSharedMemoryClause *C) {
8616   llvm_unreachable(
8617       "unified_shared_memory clause cannot appear in dependent context");
8618 }
8619 
8620 template <typename Derived>
8621 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8622     OMPReverseOffloadClause *C) {
8623   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8624 }
8625 
8626 template <typename Derived>
8627 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8628     OMPDynamicAllocatorsClause *C) {
8629   llvm_unreachable(
8630       "dynamic_allocators clause cannot appear in dependent context");
8631 }
8632 
8633 template <typename Derived>
8634 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8635     OMPAtomicDefaultMemOrderClause *C) {
8636   llvm_unreachable(
8637       "atomic_default_mem_order clause cannot appear in dependent context");
8638 }
8639 
8640 template <typename Derived>
8641 OMPClause *
8642 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8643   llvm::SmallVector<Expr *, 16> Vars;
8644   Vars.reserve(C->varlist_size());
8645   for (auto *VE : C->varlists()) {
8646     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8647     if (EVar.isInvalid())
8648       return nullptr;
8649     Vars.push_back(EVar.get());
8650   }
8651   return getDerived().RebuildOMPPrivateClause(
8652       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8653 }
8654 
8655 template <typename Derived>
8656 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8657     OMPFirstprivateClause *C) {
8658   llvm::SmallVector<Expr *, 16> Vars;
8659   Vars.reserve(C->varlist_size());
8660   for (auto *VE : C->varlists()) {
8661     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8662     if (EVar.isInvalid())
8663       return nullptr;
8664     Vars.push_back(EVar.get());
8665   }
8666   return getDerived().RebuildOMPFirstprivateClause(
8667       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8668 }
8669 
8670 template <typename Derived>
8671 OMPClause *
8672 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8673   llvm::SmallVector<Expr *, 16> Vars;
8674   Vars.reserve(C->varlist_size());
8675   for (auto *VE : C->varlists()) {
8676     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8677     if (EVar.isInvalid())
8678       return nullptr;
8679     Vars.push_back(EVar.get());
8680   }
8681   return getDerived().RebuildOMPLastprivateClause(
8682       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8683 }
8684 
8685 template <typename Derived>
8686 OMPClause *
8687 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8688   llvm::SmallVector<Expr *, 16> Vars;
8689   Vars.reserve(C->varlist_size());
8690   for (auto *VE : C->varlists()) {
8691     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8692     if (EVar.isInvalid())
8693       return nullptr;
8694     Vars.push_back(EVar.get());
8695   }
8696   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8697                                              C->getLParenLoc(), C->getEndLoc());
8698 }
8699 
8700 template <typename Derived>
8701 OMPClause *
8702 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8703   llvm::SmallVector<Expr *, 16> Vars;
8704   Vars.reserve(C->varlist_size());
8705   for (auto *VE : C->varlists()) {
8706     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8707     if (EVar.isInvalid())
8708       return nullptr;
8709     Vars.push_back(EVar.get());
8710   }
8711   CXXScopeSpec ReductionIdScopeSpec;
8712   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8713 
8714   DeclarationNameInfo NameInfo = C->getNameInfo();
8715   if (NameInfo.getName()) {
8716     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8717     if (!NameInfo.getName())
8718       return nullptr;
8719   }
8720   // Build a list of all UDR decls with the same names ranged by the Scopes.
8721   // The Scope boundary is a duplication of the previous decl.
8722   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8723   for (auto *E : C->reduction_ops()) {
8724     // Transform all the decls.
8725     if (E) {
8726       auto *ULE = cast<UnresolvedLookupExpr>(E);
8727       UnresolvedSet<8> Decls;
8728       for (auto *D : ULE->decls()) {
8729         NamedDecl *InstD =
8730             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8731         Decls.addDecl(InstD, InstD->getAccess());
8732       }
8733       UnresolvedReductions.push_back(
8734        UnresolvedLookupExpr::Create(
8735           SemaRef.Context, /*NamingClass=*/nullptr,
8736           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8737           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8738           Decls.begin(), Decls.end()));
8739     } else
8740       UnresolvedReductions.push_back(nullptr);
8741   }
8742   return getDerived().RebuildOMPReductionClause(
8743       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8744       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8745 }
8746 
8747 template <typename Derived>
8748 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8749     OMPTaskReductionClause *C) {
8750   llvm::SmallVector<Expr *, 16> Vars;
8751   Vars.reserve(C->varlist_size());
8752   for (auto *VE : C->varlists()) {
8753     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8754     if (EVar.isInvalid())
8755       return nullptr;
8756     Vars.push_back(EVar.get());
8757   }
8758   CXXScopeSpec ReductionIdScopeSpec;
8759   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8760 
8761   DeclarationNameInfo NameInfo = C->getNameInfo();
8762   if (NameInfo.getName()) {
8763     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8764     if (!NameInfo.getName())
8765       return nullptr;
8766   }
8767   // Build a list of all UDR decls with the same names ranged by the Scopes.
8768   // The Scope boundary is a duplication of the previous decl.
8769   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8770   for (auto *E : C->reduction_ops()) {
8771     // Transform all the decls.
8772     if (E) {
8773       auto *ULE = cast<UnresolvedLookupExpr>(E);
8774       UnresolvedSet<8> Decls;
8775       for (auto *D : ULE->decls()) {
8776         NamedDecl *InstD =
8777             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8778         Decls.addDecl(InstD, InstD->getAccess());
8779       }
8780       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8781           SemaRef.Context, /*NamingClass=*/nullptr,
8782           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8783           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8784     } else
8785       UnresolvedReductions.push_back(nullptr);
8786   }
8787   return getDerived().RebuildOMPTaskReductionClause(
8788       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8789       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8790 }
8791 
8792 template <typename Derived>
8793 OMPClause *
8794 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8795   llvm::SmallVector<Expr *, 16> Vars;
8796   Vars.reserve(C->varlist_size());
8797   for (auto *VE : C->varlists()) {
8798     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8799     if (EVar.isInvalid())
8800       return nullptr;
8801     Vars.push_back(EVar.get());
8802   }
8803   CXXScopeSpec ReductionIdScopeSpec;
8804   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8805 
8806   DeclarationNameInfo NameInfo = C->getNameInfo();
8807   if (NameInfo.getName()) {
8808     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8809     if (!NameInfo.getName())
8810       return nullptr;
8811   }
8812   // Build a list of all UDR decls with the same names ranged by the Scopes.
8813   // The Scope boundary is a duplication of the previous decl.
8814   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8815   for (auto *E : C->reduction_ops()) {
8816     // Transform all the decls.
8817     if (E) {
8818       auto *ULE = cast<UnresolvedLookupExpr>(E);
8819       UnresolvedSet<8> Decls;
8820       for (auto *D : ULE->decls()) {
8821         NamedDecl *InstD =
8822             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8823         Decls.addDecl(InstD, InstD->getAccess());
8824       }
8825       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8826           SemaRef.Context, /*NamingClass=*/nullptr,
8827           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8828           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8829     } else
8830       UnresolvedReductions.push_back(nullptr);
8831   }
8832   return getDerived().RebuildOMPInReductionClause(
8833       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8834       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8835 }
8836 
8837 template <typename Derived>
8838 OMPClause *
8839 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8840   llvm::SmallVector<Expr *, 16> Vars;
8841   Vars.reserve(C->varlist_size());
8842   for (auto *VE : C->varlists()) {
8843     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8844     if (EVar.isInvalid())
8845       return nullptr;
8846     Vars.push_back(EVar.get());
8847   }
8848   ExprResult Step = getDerived().TransformExpr(C->getStep());
8849   if (Step.isInvalid())
8850     return nullptr;
8851   return getDerived().RebuildOMPLinearClause(
8852       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8853       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8854 }
8855 
8856 template <typename Derived>
8857 OMPClause *
8858 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8859   llvm::SmallVector<Expr *, 16> Vars;
8860   Vars.reserve(C->varlist_size());
8861   for (auto *VE : C->varlists()) {
8862     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8863     if (EVar.isInvalid())
8864       return nullptr;
8865     Vars.push_back(EVar.get());
8866   }
8867   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8868   if (Alignment.isInvalid())
8869     return nullptr;
8870   return getDerived().RebuildOMPAlignedClause(
8871       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8872       C->getColonLoc(), C->getEndLoc());
8873 }
8874 
8875 template <typename Derived>
8876 OMPClause *
8877 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8878   llvm::SmallVector<Expr *, 16> Vars;
8879   Vars.reserve(C->varlist_size());
8880   for (auto *VE : C->varlists()) {
8881     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8882     if (EVar.isInvalid())
8883       return nullptr;
8884     Vars.push_back(EVar.get());
8885   }
8886   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8887                                              C->getLParenLoc(), C->getEndLoc());
8888 }
8889 
8890 template <typename Derived>
8891 OMPClause *
8892 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8893   llvm::SmallVector<Expr *, 16> Vars;
8894   Vars.reserve(C->varlist_size());
8895   for (auto *VE : C->varlists()) {
8896     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8897     if (EVar.isInvalid())
8898       return nullptr;
8899     Vars.push_back(EVar.get());
8900   }
8901   return getDerived().RebuildOMPCopyprivateClause(
8902       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8903 }
8904 
8905 template <typename Derived>
8906 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8907   llvm::SmallVector<Expr *, 16> Vars;
8908   Vars.reserve(C->varlist_size());
8909   for (auto *VE : C->varlists()) {
8910     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8911     if (EVar.isInvalid())
8912       return nullptr;
8913     Vars.push_back(EVar.get());
8914   }
8915   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
8916                                             C->getLParenLoc(), C->getEndLoc());
8917 }
8918 
8919 template <typename Derived>
8920 OMPClause *
8921 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8922   llvm::SmallVector<Expr *, 16> Vars;
8923   Vars.reserve(C->varlist_size());
8924   for (auto *VE : C->varlists()) {
8925     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8926     if (EVar.isInvalid())
8927       return nullptr;
8928     Vars.push_back(EVar.get());
8929   }
8930   return getDerived().RebuildOMPDependClause(
8931       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8932       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8933 }
8934 
8935 template <typename Derived>
8936 OMPClause *
8937 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
8938   ExprResult E = getDerived().TransformExpr(C->getDevice());
8939   if (E.isInvalid())
8940     return nullptr;
8941   return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
8942                                              C->getLParenLoc(), C->getEndLoc());
8943 }
8944 
8945 template <typename Derived, class T>
8946 bool transformOMPMappableExprListClause(
8947     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
8948     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
8949     DeclarationNameInfo &MapperIdInfo,
8950     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
8951   // Transform expressions in the list.
8952   Vars.reserve(C->varlist_size());
8953   for (auto *VE : C->varlists()) {
8954     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
8955     if (EVar.isInvalid())
8956       return true;
8957     Vars.push_back(EVar.get());
8958   }
8959   // Transform mapper scope specifier and identifier.
8960   NestedNameSpecifierLoc QualifierLoc;
8961   if (C->getMapperQualifierLoc()) {
8962     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
8963         C->getMapperQualifierLoc());
8964     if (!QualifierLoc)
8965       return true;
8966   }
8967   MapperIdScopeSpec.Adopt(QualifierLoc);
8968   MapperIdInfo = C->getMapperIdInfo();
8969   if (MapperIdInfo.getName()) {
8970     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
8971     if (!MapperIdInfo.getName())
8972       return true;
8973   }
8974   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
8975   // the previous user-defined mapper lookup in dependent environment.
8976   for (auto *E : C->mapperlists()) {
8977     // Transform all the decls.
8978     if (E) {
8979       auto *ULE = cast<UnresolvedLookupExpr>(E);
8980       UnresolvedSet<8> Decls;
8981       for (auto *D : ULE->decls()) {
8982         NamedDecl *InstD =
8983             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
8984         Decls.addDecl(InstD, InstD->getAccess());
8985       }
8986       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
8987           TT.getSema().Context, /*NamingClass=*/nullptr,
8988           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
8989           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
8990           Decls.end()));
8991     } else {
8992       UnresolvedMappers.push_back(nullptr);
8993     }
8994   }
8995   return false;
8996 }
8997 
8998 template <typename Derived>
8999 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9000   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9001   llvm::SmallVector<Expr *, 16> Vars;
9002   CXXScopeSpec MapperIdScopeSpec;
9003   DeclarationNameInfo MapperIdInfo;
9004   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9005   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9006           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9007     return nullptr;
9008   return getDerived().RebuildOMPMapClause(
9009       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9010       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9011       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9012 }
9013 
9014 template <typename Derived>
9015 OMPClause *
9016 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9017   Expr *Allocator = C->getAllocator();
9018   if (Allocator) {
9019     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9020     if (AllocatorRes.isInvalid())
9021       return nullptr;
9022     Allocator = AllocatorRes.get();
9023   }
9024   llvm::SmallVector<Expr *, 16> Vars;
9025   Vars.reserve(C->varlist_size());
9026   for (auto *VE : C->varlists()) {
9027     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9028     if (EVar.isInvalid())
9029       return nullptr;
9030     Vars.push_back(EVar.get());
9031   }
9032   return getDerived().RebuildOMPAllocateClause(
9033       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9034       C->getEndLoc());
9035 }
9036 
9037 template <typename Derived>
9038 OMPClause *
9039 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9040   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9041   if (E.isInvalid())
9042     return nullptr;
9043   return getDerived().RebuildOMPNumTeamsClause(
9044       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9045 }
9046 
9047 template <typename Derived>
9048 OMPClause *
9049 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9050   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9051   if (E.isInvalid())
9052     return nullptr;
9053   return getDerived().RebuildOMPThreadLimitClause(
9054       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9055 }
9056 
9057 template <typename Derived>
9058 OMPClause *
9059 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9060   ExprResult E = getDerived().TransformExpr(C->getPriority());
9061   if (E.isInvalid())
9062     return nullptr;
9063   return getDerived().RebuildOMPPriorityClause(
9064       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9065 }
9066 
9067 template <typename Derived>
9068 OMPClause *
9069 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9070   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9071   if (E.isInvalid())
9072     return nullptr;
9073   return getDerived().RebuildOMPGrainsizeClause(
9074       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9075 }
9076 
9077 template <typename Derived>
9078 OMPClause *
9079 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9080   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9081   if (E.isInvalid())
9082     return nullptr;
9083   return getDerived().RebuildOMPNumTasksClause(
9084       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9085 }
9086 
9087 template <typename Derived>
9088 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9089   ExprResult E = getDerived().TransformExpr(C->getHint());
9090   if (E.isInvalid())
9091     return nullptr;
9092   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9093                                            C->getLParenLoc(), C->getEndLoc());
9094 }
9095 
9096 template <typename Derived>
9097 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9098     OMPDistScheduleClause *C) {
9099   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9100   if (E.isInvalid())
9101     return nullptr;
9102   return getDerived().RebuildOMPDistScheduleClause(
9103       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9104       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9105 }
9106 
9107 template <typename Derived>
9108 OMPClause *
9109 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9110   return C;
9111 }
9112 
9113 template <typename Derived>
9114 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9115   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9116   llvm::SmallVector<Expr *, 16> Vars;
9117   CXXScopeSpec MapperIdScopeSpec;
9118   DeclarationNameInfo MapperIdInfo;
9119   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9120   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9121           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9122     return nullptr;
9123   return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9124                                          Locs, UnresolvedMappers);
9125 }
9126 
9127 template <typename Derived>
9128 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9129   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9130   llvm::SmallVector<Expr *, 16> Vars;
9131   CXXScopeSpec MapperIdScopeSpec;
9132   DeclarationNameInfo MapperIdInfo;
9133   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9134   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9135           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9136     return nullptr;
9137   return getDerived().RebuildOMPFromClause(
9138       Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9139 }
9140 
9141 template <typename Derived>
9142 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9143     OMPUseDevicePtrClause *C) {
9144   llvm::SmallVector<Expr *, 16> Vars;
9145   Vars.reserve(C->varlist_size());
9146   for (auto *VE : C->varlists()) {
9147     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9148     if (EVar.isInvalid())
9149       return nullptr;
9150     Vars.push_back(EVar.get());
9151   }
9152   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9153   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9154 }
9155 
9156 template <typename Derived>
9157 OMPClause *
9158 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9159   llvm::SmallVector<Expr *, 16> Vars;
9160   Vars.reserve(C->varlist_size());
9161   for (auto *VE : C->varlists()) {
9162     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9163     if (EVar.isInvalid())
9164       return nullptr;
9165     Vars.push_back(EVar.get());
9166   }
9167   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9168   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9169 }
9170 
9171 //===----------------------------------------------------------------------===//
9172 // Expression transformation
9173 //===----------------------------------------------------------------------===//
9174 template<typename Derived>
9175 ExprResult
9176 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9177   return TransformExpr(E->getSubExpr());
9178 }
9179 
9180 template<typename Derived>
9181 ExprResult
9182 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9183   if (!E->isTypeDependent())
9184     return E;
9185 
9186   return getDerived().RebuildPredefinedExpr(E->getLocation(),
9187                                             E->getIdentKind());
9188 }
9189 
9190 template<typename Derived>
9191 ExprResult
9192 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9193   NestedNameSpecifierLoc QualifierLoc;
9194   if (E->getQualifierLoc()) {
9195     QualifierLoc
9196       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9197     if (!QualifierLoc)
9198       return ExprError();
9199   }
9200 
9201   ValueDecl *ND
9202     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9203                                                          E->getDecl()));
9204   if (!ND)
9205     return ExprError();
9206 
9207   DeclarationNameInfo NameInfo = E->getNameInfo();
9208   if (NameInfo.getName()) {
9209     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9210     if (!NameInfo.getName())
9211       return ExprError();
9212   }
9213 
9214   if (!getDerived().AlwaysRebuild() &&
9215       QualifierLoc == E->getQualifierLoc() &&
9216       ND == E->getDecl() &&
9217       NameInfo.getName() == E->getDecl()->getDeclName() &&
9218       !E->hasExplicitTemplateArgs()) {
9219 
9220     // Mark it referenced in the new context regardless.
9221     // FIXME: this is a bit instantiation-specific.
9222     SemaRef.MarkDeclRefReferenced(E);
9223 
9224     return E;
9225   }
9226 
9227   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9228   if (E->hasExplicitTemplateArgs()) {
9229     TemplateArgs = &TransArgs;
9230     TransArgs.setLAngleLoc(E->getLAngleLoc());
9231     TransArgs.setRAngleLoc(E->getRAngleLoc());
9232     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9233                                                 E->getNumTemplateArgs(),
9234                                                 TransArgs))
9235       return ExprError();
9236   }
9237 
9238   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9239                                          TemplateArgs);
9240 }
9241 
9242 template<typename Derived>
9243 ExprResult
9244 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9245   return E;
9246 }
9247 
9248 template <typename Derived>
9249 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9250     FixedPointLiteral *E) {
9251   return E;
9252 }
9253 
9254 template<typename Derived>
9255 ExprResult
9256 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9257   return E;
9258 }
9259 
9260 template<typename Derived>
9261 ExprResult
9262 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9263   return E;
9264 }
9265 
9266 template<typename Derived>
9267 ExprResult
9268 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9269   return E;
9270 }
9271 
9272 template<typename Derived>
9273 ExprResult
9274 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9275   return E;
9276 }
9277 
9278 template<typename Derived>
9279 ExprResult
9280 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9281   if (FunctionDecl *FD = E->getDirectCallee())
9282     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9283   return SemaRef.MaybeBindToTemporary(E);
9284 }
9285 
9286 template<typename Derived>
9287 ExprResult
9288 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9289   ExprResult ControllingExpr =
9290     getDerived().TransformExpr(E->getControllingExpr());
9291   if (ControllingExpr.isInvalid())
9292     return ExprError();
9293 
9294   SmallVector<Expr *, 4> AssocExprs;
9295   SmallVector<TypeSourceInfo *, 4> AssocTypes;
9296   for (const GenericSelectionExpr::Association &Assoc : E->associations()) {
9297     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9298     if (TSI) {
9299       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9300       if (!AssocType)
9301         return ExprError();
9302       AssocTypes.push_back(AssocType);
9303     } else {
9304       AssocTypes.push_back(nullptr);
9305     }
9306 
9307     ExprResult AssocExpr =
9308         getDerived().TransformExpr(Assoc.getAssociationExpr());
9309     if (AssocExpr.isInvalid())
9310       return ExprError();
9311     AssocExprs.push_back(AssocExpr.get());
9312   }
9313 
9314   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9315                                                   E->getDefaultLoc(),
9316                                                   E->getRParenLoc(),
9317                                                   ControllingExpr.get(),
9318                                                   AssocTypes,
9319                                                   AssocExprs);
9320 }
9321 
9322 template<typename Derived>
9323 ExprResult
9324 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9325   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9326   if (SubExpr.isInvalid())
9327     return ExprError();
9328 
9329   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9330     return E;
9331 
9332   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9333                                        E->getRParen());
9334 }
9335 
9336 /// The operand of a unary address-of operator has special rules: it's
9337 /// allowed to refer to a non-static member of a class even if there's no 'this'
9338 /// object available.
9339 template<typename Derived>
9340 ExprResult
9341 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9342   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9343     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9344   else
9345     return getDerived().TransformExpr(E);
9346 }
9347 
9348 template<typename Derived>
9349 ExprResult
9350 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9351   ExprResult SubExpr;
9352   if (E->getOpcode() == UO_AddrOf)
9353     SubExpr = TransformAddressOfOperand(E->getSubExpr());
9354   else
9355     SubExpr = TransformExpr(E->getSubExpr());
9356   if (SubExpr.isInvalid())
9357     return ExprError();
9358 
9359   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9360     return E;
9361 
9362   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9363                                            E->getOpcode(),
9364                                            SubExpr.get());
9365 }
9366 
9367 template<typename Derived>
9368 ExprResult
9369 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9370   // Transform the type.
9371   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9372   if (!Type)
9373     return ExprError();
9374 
9375   // Transform all of the components into components similar to what the
9376   // parser uses.
9377   // FIXME: It would be slightly more efficient in the non-dependent case to
9378   // just map FieldDecls, rather than requiring the rebuilder to look for
9379   // the fields again. However, __builtin_offsetof is rare enough in
9380   // template code that we don't care.
9381   bool ExprChanged = false;
9382   typedef Sema::OffsetOfComponent Component;
9383   SmallVector<Component, 4> Components;
9384   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9385     const OffsetOfNode &ON = E->getComponent(I);
9386     Component Comp;
9387     Comp.isBrackets = true;
9388     Comp.LocStart = ON.getSourceRange().getBegin();
9389     Comp.LocEnd = ON.getSourceRange().getEnd();
9390     switch (ON.getKind()) {
9391     case OffsetOfNode::Array: {
9392       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9393       ExprResult Index = getDerived().TransformExpr(FromIndex);
9394       if (Index.isInvalid())
9395         return ExprError();
9396 
9397       ExprChanged = ExprChanged || Index.get() != FromIndex;
9398       Comp.isBrackets = true;
9399       Comp.U.E = Index.get();
9400       break;
9401     }
9402 
9403     case OffsetOfNode::Field:
9404     case OffsetOfNode::Identifier:
9405       Comp.isBrackets = false;
9406       Comp.U.IdentInfo = ON.getFieldName();
9407       if (!Comp.U.IdentInfo)
9408         continue;
9409 
9410       break;
9411 
9412     case OffsetOfNode::Base:
9413       // Will be recomputed during the rebuild.
9414       continue;
9415     }
9416 
9417     Components.push_back(Comp);
9418   }
9419 
9420   // If nothing changed, retain the existing expression.
9421   if (!getDerived().AlwaysRebuild() &&
9422       Type == E->getTypeSourceInfo() &&
9423       !ExprChanged)
9424     return E;
9425 
9426   // Build a new offsetof expression.
9427   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9428                                           Components, E->getRParenLoc());
9429 }
9430 
9431 template<typename Derived>
9432 ExprResult
9433 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9434   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9435          "opaque value expression requires transformation");
9436   return E;
9437 }
9438 
9439 template<typename Derived>
9440 ExprResult
9441 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9442   return E;
9443 }
9444 
9445 template<typename Derived>
9446 ExprResult
9447 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9448   // Rebuild the syntactic form.  The original syntactic form has
9449   // opaque-value expressions in it, so strip those away and rebuild
9450   // the result.  This is a really awful way of doing this, but the
9451   // better solution (rebuilding the semantic expressions and
9452   // rebinding OVEs as necessary) doesn't work; we'd need
9453   // TreeTransform to not strip away implicit conversions.
9454   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9455   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9456   if (result.isInvalid()) return ExprError();
9457 
9458   // If that gives us a pseudo-object result back, the pseudo-object
9459   // expression must have been an lvalue-to-rvalue conversion which we
9460   // should reapply.
9461   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9462     result = SemaRef.checkPseudoObjectRValue(result.get());
9463 
9464   return result;
9465 }
9466 
9467 template<typename Derived>
9468 ExprResult
9469 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9470                                                 UnaryExprOrTypeTraitExpr *E) {
9471   if (E->isArgumentType()) {
9472     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9473 
9474     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9475     if (!NewT)
9476       return ExprError();
9477 
9478     if (!getDerived().AlwaysRebuild() && OldT == NewT)
9479       return E;
9480 
9481     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9482                                                     E->getKind(),
9483                                                     E->getSourceRange());
9484   }
9485 
9486   // C++0x [expr.sizeof]p1:
9487   //   The operand is either an expression, which is an unevaluated operand
9488   //   [...]
9489   EnterExpressionEvaluationContext Unevaluated(
9490       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9491       Sema::ReuseLambdaContextDecl);
9492 
9493   // Try to recover if we have something like sizeof(T::X) where X is a type.
9494   // Notably, there must be *exactly* one set of parens if X is a type.
9495   TypeSourceInfo *RecoveryTSI = nullptr;
9496   ExprResult SubExpr;
9497   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9498   if (auto *DRE =
9499           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9500     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9501         PE, DRE, false, &RecoveryTSI);
9502   else
9503     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9504 
9505   if (RecoveryTSI) {
9506     return getDerived().RebuildUnaryExprOrTypeTrait(
9507         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9508   } else if (SubExpr.isInvalid())
9509     return ExprError();
9510 
9511   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9512     return E;
9513 
9514   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9515                                                   E->getOperatorLoc(),
9516                                                   E->getKind(),
9517                                                   E->getSourceRange());
9518 }
9519 
9520 template<typename Derived>
9521 ExprResult
9522 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9523   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9524   if (LHS.isInvalid())
9525     return ExprError();
9526 
9527   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9528   if (RHS.isInvalid())
9529     return ExprError();
9530 
9531 
9532   if (!getDerived().AlwaysRebuild() &&
9533       LHS.get() == E->getLHS() &&
9534       RHS.get() == E->getRHS())
9535     return E;
9536 
9537   return getDerived().RebuildArraySubscriptExpr(
9538       LHS.get(),
9539       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9540 }
9541 
9542 template <typename Derived>
9543 ExprResult
9544 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9545   ExprResult Base = getDerived().TransformExpr(E->getBase());
9546   if (Base.isInvalid())
9547     return ExprError();
9548 
9549   ExprResult LowerBound;
9550   if (E->getLowerBound()) {
9551     LowerBound = getDerived().TransformExpr(E->getLowerBound());
9552     if (LowerBound.isInvalid())
9553       return ExprError();
9554   }
9555 
9556   ExprResult Length;
9557   if (E->getLength()) {
9558     Length = getDerived().TransformExpr(E->getLength());
9559     if (Length.isInvalid())
9560       return ExprError();
9561   }
9562 
9563   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9564       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9565     return E;
9566 
9567   return getDerived().RebuildOMPArraySectionExpr(
9568       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9569       Length.get(), E->getRBracketLoc());
9570 }
9571 
9572 template<typename Derived>
9573 ExprResult
9574 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9575   // Transform the callee.
9576   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9577   if (Callee.isInvalid())
9578     return ExprError();
9579 
9580   // Transform arguments.
9581   bool ArgChanged = false;
9582   SmallVector<Expr*, 8> Args;
9583   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9584                                   &ArgChanged))
9585     return ExprError();
9586 
9587   if (!getDerived().AlwaysRebuild() &&
9588       Callee.get() == E->getCallee() &&
9589       !ArgChanged)
9590     return SemaRef.MaybeBindToTemporary(E);
9591 
9592   // FIXME: Wrong source location information for the '('.
9593   SourceLocation FakeLParenLoc
9594     = ((Expr *)Callee.get())->getSourceRange().getBegin();
9595   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9596                                       Args,
9597                                       E->getRParenLoc());
9598 }
9599 
9600 template<typename Derived>
9601 ExprResult
9602 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9603   ExprResult Base = getDerived().TransformExpr(E->getBase());
9604   if (Base.isInvalid())
9605     return ExprError();
9606 
9607   NestedNameSpecifierLoc QualifierLoc;
9608   if (E->hasQualifier()) {
9609     QualifierLoc
9610       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9611 
9612     if (!QualifierLoc)
9613       return ExprError();
9614   }
9615   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9616 
9617   ValueDecl *Member
9618     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9619                                                          E->getMemberDecl()));
9620   if (!Member)
9621     return ExprError();
9622 
9623   NamedDecl *FoundDecl = E->getFoundDecl();
9624   if (FoundDecl == E->getMemberDecl()) {
9625     FoundDecl = Member;
9626   } else {
9627     FoundDecl = cast_or_null<NamedDecl>(
9628                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9629     if (!FoundDecl)
9630       return ExprError();
9631   }
9632 
9633   if (!getDerived().AlwaysRebuild() &&
9634       Base.get() == E->getBase() &&
9635       QualifierLoc == E->getQualifierLoc() &&
9636       Member == E->getMemberDecl() &&
9637       FoundDecl == E->getFoundDecl() &&
9638       !E->hasExplicitTemplateArgs()) {
9639 
9640     // Mark it referenced in the new context regardless.
9641     // FIXME: this is a bit instantiation-specific.
9642     SemaRef.MarkMemberReferenced(E);
9643 
9644     return E;
9645   }
9646 
9647   TemplateArgumentListInfo TransArgs;
9648   if (E->hasExplicitTemplateArgs()) {
9649     TransArgs.setLAngleLoc(E->getLAngleLoc());
9650     TransArgs.setRAngleLoc(E->getRAngleLoc());
9651     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9652                                                 E->getNumTemplateArgs(),
9653                                                 TransArgs))
9654       return ExprError();
9655   }
9656 
9657   // FIXME: Bogus source location for the operator
9658   SourceLocation FakeOperatorLoc =
9659       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9660 
9661   // FIXME: to do this check properly, we will need to preserve the
9662   // first-qualifier-in-scope here, just in case we had a dependent
9663   // base (and therefore couldn't do the check) and a
9664   // nested-name-qualifier (and therefore could do the lookup).
9665   NamedDecl *FirstQualifierInScope = nullptr;
9666   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9667   if (MemberNameInfo.getName()) {
9668     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9669     if (!MemberNameInfo.getName())
9670       return ExprError();
9671   }
9672 
9673   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9674                                         E->isArrow(),
9675                                         QualifierLoc,
9676                                         TemplateKWLoc,
9677                                         MemberNameInfo,
9678                                         Member,
9679                                         FoundDecl,
9680                                         (E->hasExplicitTemplateArgs()
9681                                            ? &TransArgs : nullptr),
9682                                         FirstQualifierInScope);
9683 }
9684 
9685 template<typename Derived>
9686 ExprResult
9687 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9688   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9689   if (LHS.isInvalid())
9690     return ExprError();
9691 
9692   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9693   if (RHS.isInvalid())
9694     return ExprError();
9695 
9696   if (!getDerived().AlwaysRebuild() &&
9697       LHS.get() == E->getLHS() &&
9698       RHS.get() == E->getRHS())
9699     return E;
9700 
9701   Sema::FPContractStateRAII FPContractState(getSema());
9702   getSema().FPFeatures = E->getFPFeatures();
9703 
9704   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9705                                             LHS.get(), RHS.get());
9706 }
9707 
9708 template<typename Derived>
9709 ExprResult
9710 TreeTransform<Derived>::TransformCompoundAssignOperator(
9711                                                       CompoundAssignOperator *E) {
9712   return getDerived().TransformBinaryOperator(E);
9713 }
9714 
9715 template<typename Derived>
9716 ExprResult TreeTransform<Derived>::
9717 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9718   // Just rebuild the common and RHS expressions and see whether we
9719   // get any changes.
9720 
9721   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9722   if (commonExpr.isInvalid())
9723     return ExprError();
9724 
9725   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9726   if (rhs.isInvalid())
9727     return ExprError();
9728 
9729   if (!getDerived().AlwaysRebuild() &&
9730       commonExpr.get() == e->getCommon() &&
9731       rhs.get() == e->getFalseExpr())
9732     return e;
9733 
9734   return getDerived().RebuildConditionalOperator(commonExpr.get(),
9735                                                  e->getQuestionLoc(),
9736                                                  nullptr,
9737                                                  e->getColonLoc(),
9738                                                  rhs.get());
9739 }
9740 
9741 template<typename Derived>
9742 ExprResult
9743 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9744   ExprResult Cond = getDerived().TransformExpr(E->getCond());
9745   if (Cond.isInvalid())
9746     return ExprError();
9747 
9748   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9749   if (LHS.isInvalid())
9750     return ExprError();
9751 
9752   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9753   if (RHS.isInvalid())
9754     return ExprError();
9755 
9756   if (!getDerived().AlwaysRebuild() &&
9757       Cond.get() == E->getCond() &&
9758       LHS.get() == E->getLHS() &&
9759       RHS.get() == E->getRHS())
9760     return E;
9761 
9762   return getDerived().RebuildConditionalOperator(Cond.get(),
9763                                                  E->getQuestionLoc(),
9764                                                  LHS.get(),
9765                                                  E->getColonLoc(),
9766                                                  RHS.get());
9767 }
9768 
9769 template<typename Derived>
9770 ExprResult
9771 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9772   // Implicit casts are eliminated during transformation, since they
9773   // will be recomputed by semantic analysis after transformation.
9774   return getDerived().TransformExpr(E->getSubExprAsWritten());
9775 }
9776 
9777 template<typename Derived>
9778 ExprResult
9779 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9780   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9781   if (!Type)
9782     return ExprError();
9783 
9784   ExprResult SubExpr
9785     = getDerived().TransformExpr(E->getSubExprAsWritten());
9786   if (SubExpr.isInvalid())
9787     return ExprError();
9788 
9789   if (!getDerived().AlwaysRebuild() &&
9790       Type == E->getTypeInfoAsWritten() &&
9791       SubExpr.get() == E->getSubExpr())
9792     return E;
9793 
9794   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9795                                             Type,
9796                                             E->getRParenLoc(),
9797                                             SubExpr.get());
9798 }
9799 
9800 template<typename Derived>
9801 ExprResult
9802 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9803   TypeSourceInfo *OldT = E->getTypeSourceInfo();
9804   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9805   if (!NewT)
9806     return ExprError();
9807 
9808   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9809   if (Init.isInvalid())
9810     return ExprError();
9811 
9812   if (!getDerived().AlwaysRebuild() &&
9813       OldT == NewT &&
9814       Init.get() == E->getInitializer())
9815     return SemaRef.MaybeBindToTemporary(E);
9816 
9817   // Note: the expression type doesn't necessarily match the
9818   // type-as-written, but that's okay, because it should always be
9819   // derivable from the initializer.
9820 
9821   return getDerived().RebuildCompoundLiteralExpr(
9822       E->getLParenLoc(), NewT,
9823       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
9824 }
9825 
9826 template<typename Derived>
9827 ExprResult
9828 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9829   ExprResult Base = getDerived().TransformExpr(E->getBase());
9830   if (Base.isInvalid())
9831     return ExprError();
9832 
9833   if (!getDerived().AlwaysRebuild() &&
9834       Base.get() == E->getBase())
9835     return E;
9836 
9837   // FIXME: Bad source location
9838   SourceLocation FakeOperatorLoc =
9839       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
9840   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9841                                                   E->getAccessorLoc(),
9842                                                   E->getAccessor());
9843 }
9844 
9845 template<typename Derived>
9846 ExprResult
9847 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9848   if (InitListExpr *Syntactic = E->getSyntacticForm())
9849     E = Syntactic;
9850 
9851   bool InitChanged = false;
9852 
9853   EnterExpressionEvaluationContext Context(
9854       getSema(), EnterExpressionEvaluationContext::InitList);
9855 
9856   SmallVector<Expr*, 4> Inits;
9857   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9858                                   Inits, &InitChanged))
9859     return ExprError();
9860 
9861   if (!getDerived().AlwaysRebuild() && !InitChanged) {
9862     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9863     // in some cases. We can't reuse it in general, because the syntactic and
9864     // semantic forms are linked, and we can't know that semantic form will
9865     // match even if the syntactic form does.
9866   }
9867 
9868   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9869                                       E->getRBraceLoc());
9870 }
9871 
9872 template<typename Derived>
9873 ExprResult
9874 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9875   Designation Desig;
9876 
9877   // transform the initializer value
9878   ExprResult Init = getDerived().TransformExpr(E->getInit());
9879   if (Init.isInvalid())
9880     return ExprError();
9881 
9882   // transform the designators.
9883   SmallVector<Expr*, 4> ArrayExprs;
9884   bool ExprChanged = false;
9885   for (const DesignatedInitExpr::Designator &D : E->designators()) {
9886     if (D.isFieldDesignator()) {
9887       Desig.AddDesignator(Designator::getField(D.getFieldName(),
9888                                                D.getDotLoc(),
9889                                                D.getFieldLoc()));
9890       if (D.getField()) {
9891         FieldDecl *Field = cast_or_null<FieldDecl>(
9892             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
9893         if (Field != D.getField())
9894           // Rebuild the expression when the transformed FieldDecl is
9895           // different to the already assigned FieldDecl.
9896           ExprChanged = true;
9897       } else {
9898         // Ensure that the designator expression is rebuilt when there isn't
9899         // a resolved FieldDecl in the designator as we don't want to assign
9900         // a FieldDecl to a pattern designator that will be instantiated again.
9901         ExprChanged = true;
9902       }
9903       continue;
9904     }
9905 
9906     if (D.isArrayDesignator()) {
9907       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
9908       if (Index.isInvalid())
9909         return ExprError();
9910 
9911       Desig.AddDesignator(
9912           Designator::getArray(Index.get(), D.getLBracketLoc()));
9913 
9914       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
9915       ArrayExprs.push_back(Index.get());
9916       continue;
9917     }
9918 
9919     assert(D.isArrayRangeDesignator() && "New kind of designator?");
9920     ExprResult Start
9921       = getDerived().TransformExpr(E->getArrayRangeStart(D));
9922     if (Start.isInvalid())
9923       return ExprError();
9924 
9925     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
9926     if (End.isInvalid())
9927       return ExprError();
9928 
9929     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
9930                                                   End.get(),
9931                                                   D.getLBracketLoc(),
9932                                                   D.getEllipsisLoc()));
9933 
9934     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
9935                   End.get() != E->getArrayRangeEnd(D);
9936 
9937     ArrayExprs.push_back(Start.get());
9938     ArrayExprs.push_back(End.get());
9939   }
9940 
9941   if (!getDerived().AlwaysRebuild() &&
9942       Init.get() == E->getInit() &&
9943       !ExprChanged)
9944     return E;
9945 
9946   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
9947                                                 E->getEqualOrColonLoc(),
9948                                                 E->usesGNUSyntax(), Init.get());
9949 }
9950 
9951 // Seems that if TransformInitListExpr() only works on the syntactic form of an
9952 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
9953 template<typename Derived>
9954 ExprResult
9955 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
9956     DesignatedInitUpdateExpr *E) {
9957   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
9958                    "initializer");
9959   return ExprError();
9960 }
9961 
9962 template<typename Derived>
9963 ExprResult
9964 TreeTransform<Derived>::TransformNoInitExpr(
9965     NoInitExpr *E) {
9966   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
9967   return ExprError();
9968 }
9969 
9970 template<typename Derived>
9971 ExprResult
9972 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
9973   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
9974   return ExprError();
9975 }
9976 
9977 template<typename Derived>
9978 ExprResult
9979 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
9980   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
9981   return ExprError();
9982 }
9983 
9984 template<typename Derived>
9985 ExprResult
9986 TreeTransform<Derived>::TransformImplicitValueInitExpr(
9987                                                      ImplicitValueInitExpr *E) {
9988   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
9989 
9990   // FIXME: Will we ever have proper type location here? Will we actually
9991   // need to transform the type?
9992   QualType T = getDerived().TransformType(E->getType());
9993   if (T.isNull())
9994     return ExprError();
9995 
9996   if (!getDerived().AlwaysRebuild() &&
9997       T == E->getType())
9998     return E;
9999 
10000   return getDerived().RebuildImplicitValueInitExpr(T);
10001 }
10002 
10003 template<typename Derived>
10004 ExprResult
10005 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10006   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10007   if (!TInfo)
10008     return ExprError();
10009 
10010   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10011   if (SubExpr.isInvalid())
10012     return ExprError();
10013 
10014   if (!getDerived().AlwaysRebuild() &&
10015       TInfo == E->getWrittenTypeInfo() &&
10016       SubExpr.get() == E->getSubExpr())
10017     return E;
10018 
10019   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10020                                        TInfo, E->getRParenLoc());
10021 }
10022 
10023 template<typename Derived>
10024 ExprResult
10025 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10026   bool ArgumentChanged = false;
10027   SmallVector<Expr*, 4> Inits;
10028   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10029                      &ArgumentChanged))
10030     return ExprError();
10031 
10032   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10033                                            Inits,
10034                                            E->getRParenLoc());
10035 }
10036 
10037 /// Transform an address-of-label expression.
10038 ///
10039 /// By default, the transformation of an address-of-label expression always
10040 /// rebuilds the expression, so that the label identifier can be resolved to
10041 /// the corresponding label statement by semantic analysis.
10042 template<typename Derived>
10043 ExprResult
10044 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10045   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10046                                         E->getLabel());
10047   if (!LD)
10048     return ExprError();
10049 
10050   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10051                                            cast<LabelDecl>(LD));
10052 }
10053 
10054 template<typename Derived>
10055 ExprResult
10056 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10057   SemaRef.ActOnStartStmtExpr();
10058   StmtResult SubStmt
10059     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10060   if (SubStmt.isInvalid()) {
10061     SemaRef.ActOnStmtExprError();
10062     return ExprError();
10063   }
10064 
10065   if (!getDerived().AlwaysRebuild() &&
10066       SubStmt.get() == E->getSubStmt()) {
10067     // Calling this an 'error' is unintuitive, but it does the right thing.
10068     SemaRef.ActOnStmtExprError();
10069     return SemaRef.MaybeBindToTemporary(E);
10070   }
10071 
10072   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
10073                                       SubStmt.get(),
10074                                       E->getRParenLoc());
10075 }
10076 
10077 template<typename Derived>
10078 ExprResult
10079 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10080   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10081   if (Cond.isInvalid())
10082     return ExprError();
10083 
10084   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10085   if (LHS.isInvalid())
10086     return ExprError();
10087 
10088   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10089   if (RHS.isInvalid())
10090     return ExprError();
10091 
10092   if (!getDerived().AlwaysRebuild() &&
10093       Cond.get() == E->getCond() &&
10094       LHS.get() == E->getLHS() &&
10095       RHS.get() == E->getRHS())
10096     return E;
10097 
10098   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10099                                         Cond.get(), LHS.get(), RHS.get(),
10100                                         E->getRParenLoc());
10101 }
10102 
10103 template<typename Derived>
10104 ExprResult
10105 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10106   return E;
10107 }
10108 
10109 template<typename Derived>
10110 ExprResult
10111 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10112   switch (E->getOperator()) {
10113   case OO_New:
10114   case OO_Delete:
10115   case OO_Array_New:
10116   case OO_Array_Delete:
10117     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
10118 
10119   case OO_Call: {
10120     // This is a call to an object's operator().
10121     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
10122 
10123     // Transform the object itself.
10124     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10125     if (Object.isInvalid())
10126       return ExprError();
10127 
10128     // FIXME: Poor location information
10129     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10130         static_cast<Expr *>(Object.get())->getEndLoc());
10131 
10132     // Transform the call arguments.
10133     SmallVector<Expr*, 8> Args;
10134     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10135                                     Args))
10136       return ExprError();
10137 
10138     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10139                                         E->getEndLoc());
10140   }
10141 
10142 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10143   case OO_##Name:
10144 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10145 #include "clang/Basic/OperatorKinds.def"
10146   case OO_Subscript:
10147     // Handled below.
10148     break;
10149 
10150   case OO_Conditional:
10151     llvm_unreachable("conditional operator is not actually overloadable");
10152 
10153   case OO_None:
10154   case NUM_OVERLOADED_OPERATORS:
10155     llvm_unreachable("not an overloaded operator?");
10156   }
10157 
10158   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10159   if (Callee.isInvalid())
10160     return ExprError();
10161 
10162   ExprResult First;
10163   if (E->getOperator() == OO_Amp)
10164     First = getDerived().TransformAddressOfOperand(E->getArg(0));
10165   else
10166     First = getDerived().TransformExpr(E->getArg(0));
10167   if (First.isInvalid())
10168     return ExprError();
10169 
10170   ExprResult Second;
10171   if (E->getNumArgs() == 2) {
10172     Second = getDerived().TransformExpr(E->getArg(1));
10173     if (Second.isInvalid())
10174       return ExprError();
10175   }
10176 
10177   if (!getDerived().AlwaysRebuild() &&
10178       Callee.get() == E->getCallee() &&
10179       First.get() == E->getArg(0) &&
10180       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10181     return SemaRef.MaybeBindToTemporary(E);
10182 
10183   Sema::FPContractStateRAII FPContractState(getSema());
10184   getSema().FPFeatures = E->getFPFeatures();
10185 
10186   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10187                                                  E->getOperatorLoc(),
10188                                                  Callee.get(),
10189                                                  First.get(),
10190                                                  Second.get());
10191 }
10192 
10193 template<typename Derived>
10194 ExprResult
10195 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10196   return getDerived().TransformCallExpr(E);
10197 }
10198 
10199 template <typename Derived>
10200 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10201   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10202                          getSema().CurContext != E->getParentContext();
10203 
10204   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10205     return E;
10206 
10207   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10208                                            E->getEndLoc(),
10209                                            getSema().CurContext);
10210 }
10211 
10212 template<typename Derived>
10213 ExprResult
10214 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10215   // Transform the callee.
10216   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10217   if (Callee.isInvalid())
10218     return ExprError();
10219 
10220   // Transform exec config.
10221   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10222   if (EC.isInvalid())
10223     return ExprError();
10224 
10225   // Transform arguments.
10226   bool ArgChanged = false;
10227   SmallVector<Expr*, 8> Args;
10228   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10229                                   &ArgChanged))
10230     return ExprError();
10231 
10232   if (!getDerived().AlwaysRebuild() &&
10233       Callee.get() == E->getCallee() &&
10234       !ArgChanged)
10235     return SemaRef.MaybeBindToTemporary(E);
10236 
10237   // FIXME: Wrong source location information for the '('.
10238   SourceLocation FakeLParenLoc
10239     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10240   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10241                                       Args,
10242                                       E->getRParenLoc(), EC.get());
10243 }
10244 
10245 template<typename Derived>
10246 ExprResult
10247 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10248   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10249   if (!Type)
10250     return ExprError();
10251 
10252   ExprResult SubExpr
10253     = getDerived().TransformExpr(E->getSubExprAsWritten());
10254   if (SubExpr.isInvalid())
10255     return ExprError();
10256 
10257   if (!getDerived().AlwaysRebuild() &&
10258       Type == E->getTypeInfoAsWritten() &&
10259       SubExpr.get() == E->getSubExpr())
10260     return E;
10261   return getDerived().RebuildCXXNamedCastExpr(
10262       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10263       Type, E->getAngleBrackets().getEnd(),
10264       // FIXME. this should be '(' location
10265       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10266 }
10267 
10268 template<typename Derived>
10269 ExprResult
10270 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10271   TypeSourceInfo *TSI =
10272       getDerived().TransformType(BCE->getTypeInfoAsWritten());
10273   if (!TSI)
10274     return ExprError();
10275 
10276   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10277   if (Sub.isInvalid())
10278     return ExprError();
10279 
10280   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10281                                                 Sub.get(), BCE->getEndLoc());
10282 }
10283 
10284 template<typename Derived>
10285 ExprResult
10286 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10287   return getDerived().TransformCXXNamedCastExpr(E);
10288 }
10289 
10290 template<typename Derived>
10291 ExprResult
10292 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10293   return getDerived().TransformCXXNamedCastExpr(E);
10294 }
10295 
10296 template<typename Derived>
10297 ExprResult
10298 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10299                                                       CXXReinterpretCastExpr *E) {
10300   return getDerived().TransformCXXNamedCastExpr(E);
10301 }
10302 
10303 template<typename Derived>
10304 ExprResult
10305 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10306   return getDerived().TransformCXXNamedCastExpr(E);
10307 }
10308 
10309 template<typename Derived>
10310 ExprResult
10311 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10312                                                      CXXFunctionalCastExpr *E) {
10313   TypeSourceInfo *Type =
10314       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10315   if (!Type)
10316     return ExprError();
10317 
10318   ExprResult SubExpr
10319     = getDerived().TransformExpr(E->getSubExprAsWritten());
10320   if (SubExpr.isInvalid())
10321     return ExprError();
10322 
10323   if (!getDerived().AlwaysRebuild() &&
10324       Type == E->getTypeInfoAsWritten() &&
10325       SubExpr.get() == E->getSubExpr())
10326     return E;
10327 
10328   return getDerived().RebuildCXXFunctionalCastExpr(Type,
10329                                                    E->getLParenLoc(),
10330                                                    SubExpr.get(),
10331                                                    E->getRParenLoc(),
10332                                                    E->isListInitialization());
10333 }
10334 
10335 template<typename Derived>
10336 ExprResult
10337 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10338   if (E->isTypeOperand()) {
10339     TypeSourceInfo *TInfo
10340       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10341     if (!TInfo)
10342       return ExprError();
10343 
10344     if (!getDerived().AlwaysRebuild() &&
10345         TInfo == E->getTypeOperandSourceInfo())
10346       return E;
10347 
10348     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10349                                              TInfo, E->getEndLoc());
10350   }
10351 
10352   // We don't know whether the subexpression is potentially evaluated until
10353   // after we perform semantic analysis.  We speculatively assume it is
10354   // unevaluated; it will get fixed later if the subexpression is in fact
10355   // potentially evaluated.
10356   EnterExpressionEvaluationContext Unevaluated(
10357       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10358       Sema::ReuseLambdaContextDecl);
10359 
10360   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10361   if (SubExpr.isInvalid())
10362     return ExprError();
10363 
10364   if (!getDerived().AlwaysRebuild() &&
10365       SubExpr.get() == E->getExprOperand())
10366     return E;
10367 
10368   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10369                                            SubExpr.get(), E->getEndLoc());
10370 }
10371 
10372 template<typename Derived>
10373 ExprResult
10374 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10375   if (E->isTypeOperand()) {
10376     TypeSourceInfo *TInfo
10377       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10378     if (!TInfo)
10379       return ExprError();
10380 
10381     if (!getDerived().AlwaysRebuild() &&
10382         TInfo == E->getTypeOperandSourceInfo())
10383       return E;
10384 
10385     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10386                                              TInfo, E->getEndLoc());
10387   }
10388 
10389   EnterExpressionEvaluationContext Unevaluated(
10390       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10391 
10392   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10393   if (SubExpr.isInvalid())
10394     return ExprError();
10395 
10396   if (!getDerived().AlwaysRebuild() &&
10397       SubExpr.get() == E->getExprOperand())
10398     return E;
10399 
10400   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10401                                            SubExpr.get(), E->getEndLoc());
10402 }
10403 
10404 template<typename Derived>
10405 ExprResult
10406 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10407   return E;
10408 }
10409 
10410 template<typename Derived>
10411 ExprResult
10412 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10413                                                      CXXNullPtrLiteralExpr *E) {
10414   return E;
10415 }
10416 
10417 template<typename Derived>
10418 ExprResult
10419 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10420   QualType T = getSema().getCurrentThisType();
10421 
10422   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10423     // Mark it referenced in the new context regardless.
10424     // FIXME: this is a bit instantiation-specific.
10425     getSema().MarkThisReferenced(E);
10426     return E;
10427   }
10428 
10429   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10430 }
10431 
10432 template<typename Derived>
10433 ExprResult
10434 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10435   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10436   if (SubExpr.isInvalid())
10437     return ExprError();
10438 
10439   if (!getDerived().AlwaysRebuild() &&
10440       SubExpr.get() == E->getSubExpr())
10441     return E;
10442 
10443   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10444                                           E->isThrownVariableInScope());
10445 }
10446 
10447 template<typename Derived>
10448 ExprResult
10449 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10450   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10451       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10452   if (!Param)
10453     return ExprError();
10454 
10455   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10456       E->getUsedContext() == SemaRef.CurContext)
10457     return E;
10458 
10459   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10460 }
10461 
10462 template<typename Derived>
10463 ExprResult
10464 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10465   FieldDecl *Field = cast_or_null<FieldDecl>(
10466       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10467   if (!Field)
10468     return ExprError();
10469 
10470   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10471       E->getUsedContext() == SemaRef.CurContext)
10472     return E;
10473 
10474   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10475 }
10476 
10477 template<typename Derived>
10478 ExprResult
10479 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10480                                                     CXXScalarValueInitExpr *E) {
10481   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10482   if (!T)
10483     return ExprError();
10484 
10485   if (!getDerived().AlwaysRebuild() &&
10486       T == E->getTypeSourceInfo())
10487     return E;
10488 
10489   return getDerived().RebuildCXXScalarValueInitExpr(T,
10490                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
10491                                                     E->getRParenLoc());
10492 }
10493 
10494 template<typename Derived>
10495 ExprResult
10496 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10497   // Transform the type that we're allocating
10498   TypeSourceInfo *AllocTypeInfo =
10499       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10500   if (!AllocTypeInfo)
10501     return ExprError();
10502 
10503   // Transform the size of the array we're allocating (if any).
10504   Optional<Expr *> ArraySize;
10505   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10506     ExprResult NewArraySize;
10507     if (*OldArraySize) {
10508       NewArraySize = getDerived().TransformExpr(*OldArraySize);
10509       if (NewArraySize.isInvalid())
10510         return ExprError();
10511     }
10512     ArraySize = NewArraySize.get();
10513   }
10514 
10515   // Transform the placement arguments (if any).
10516   bool ArgumentChanged = false;
10517   SmallVector<Expr*, 8> PlacementArgs;
10518   if (getDerived().TransformExprs(E->getPlacementArgs(),
10519                                   E->getNumPlacementArgs(), true,
10520                                   PlacementArgs, &ArgumentChanged))
10521     return ExprError();
10522 
10523   // Transform the initializer (if any).
10524   Expr *OldInit = E->getInitializer();
10525   ExprResult NewInit;
10526   if (OldInit)
10527     NewInit = getDerived().TransformInitializer(OldInit, true);
10528   if (NewInit.isInvalid())
10529     return ExprError();
10530 
10531   // Transform new operator and delete operator.
10532   FunctionDecl *OperatorNew = nullptr;
10533   if (E->getOperatorNew()) {
10534     OperatorNew = cast_or_null<FunctionDecl>(
10535         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10536     if (!OperatorNew)
10537       return ExprError();
10538   }
10539 
10540   FunctionDecl *OperatorDelete = nullptr;
10541   if (E->getOperatorDelete()) {
10542     OperatorDelete = cast_or_null<FunctionDecl>(
10543         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10544     if (!OperatorDelete)
10545       return ExprError();
10546   }
10547 
10548   if (!getDerived().AlwaysRebuild() &&
10549       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10550       ArraySize == E->getArraySize() &&
10551       NewInit.get() == OldInit &&
10552       OperatorNew == E->getOperatorNew() &&
10553       OperatorDelete == E->getOperatorDelete() &&
10554       !ArgumentChanged) {
10555     // Mark any declarations we need as referenced.
10556     // FIXME: instantiation-specific.
10557     if (OperatorNew)
10558       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10559     if (OperatorDelete)
10560       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10561 
10562     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10563       QualType ElementType
10564         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10565       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10566         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10567         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10568           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10569         }
10570       }
10571     }
10572 
10573     return E;
10574   }
10575 
10576   QualType AllocType = AllocTypeInfo->getType();
10577   if (!ArraySize) {
10578     // If no array size was specified, but the new expression was
10579     // instantiated with an array type (e.g., "new T" where T is
10580     // instantiated with "int[4]"), extract the outer bound from the
10581     // array type as our array size. We do this with constant and
10582     // dependently-sized array types.
10583     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10584     if (!ArrayT) {
10585       // Do nothing
10586     } else if (const ConstantArrayType *ConsArrayT
10587                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
10588       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10589                                          SemaRef.Context.getSizeType(),
10590                                          /*FIXME:*/ E->getBeginLoc());
10591       AllocType = ConsArrayT->getElementType();
10592     } else if (const DependentSizedArrayType *DepArrayT
10593                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10594       if (DepArrayT->getSizeExpr()) {
10595         ArraySize = DepArrayT->getSizeExpr();
10596         AllocType = DepArrayT->getElementType();
10597       }
10598     }
10599   }
10600 
10601   return getDerived().RebuildCXXNewExpr(
10602       E->getBeginLoc(), E->isGlobalNew(),
10603       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10604       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10605       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10606 }
10607 
10608 template<typename Derived>
10609 ExprResult
10610 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10611   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10612   if (Operand.isInvalid())
10613     return ExprError();
10614 
10615   // Transform the delete operator, if known.
10616   FunctionDecl *OperatorDelete = nullptr;
10617   if (E->getOperatorDelete()) {
10618     OperatorDelete = cast_or_null<FunctionDecl>(
10619         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10620     if (!OperatorDelete)
10621       return ExprError();
10622   }
10623 
10624   if (!getDerived().AlwaysRebuild() &&
10625       Operand.get() == E->getArgument() &&
10626       OperatorDelete == E->getOperatorDelete()) {
10627     // Mark any declarations we need as referenced.
10628     // FIXME: instantiation-specific.
10629     if (OperatorDelete)
10630       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10631 
10632     if (!E->getArgument()->isTypeDependent()) {
10633       QualType Destroyed = SemaRef.Context.getBaseElementType(
10634                                                          E->getDestroyedType());
10635       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10636         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10637         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10638                                        SemaRef.LookupDestructor(Record));
10639       }
10640     }
10641 
10642     return E;
10643   }
10644 
10645   return getDerived().RebuildCXXDeleteExpr(
10646       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10647 }
10648 
10649 template<typename Derived>
10650 ExprResult
10651 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10652                                                      CXXPseudoDestructorExpr *E) {
10653   ExprResult Base = getDerived().TransformExpr(E->getBase());
10654   if (Base.isInvalid())
10655     return ExprError();
10656 
10657   ParsedType ObjectTypePtr;
10658   bool MayBePseudoDestructor = false;
10659   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10660                                               E->getOperatorLoc(),
10661                                         E->isArrow()? tok::arrow : tok::period,
10662                                               ObjectTypePtr,
10663                                               MayBePseudoDestructor);
10664   if (Base.isInvalid())
10665     return ExprError();
10666 
10667   QualType ObjectType = ObjectTypePtr.get();
10668   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10669   if (QualifierLoc) {
10670     QualifierLoc
10671       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10672     if (!QualifierLoc)
10673       return ExprError();
10674   }
10675   CXXScopeSpec SS;
10676   SS.Adopt(QualifierLoc);
10677 
10678   PseudoDestructorTypeStorage Destroyed;
10679   if (E->getDestroyedTypeInfo()) {
10680     TypeSourceInfo *DestroyedTypeInfo
10681       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10682                                                 ObjectType, nullptr, SS);
10683     if (!DestroyedTypeInfo)
10684       return ExprError();
10685     Destroyed = DestroyedTypeInfo;
10686   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10687     // We aren't likely to be able to resolve the identifier down to a type
10688     // now anyway, so just retain the identifier.
10689     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10690                                             E->getDestroyedTypeLoc());
10691   } else {
10692     // Look for a destructor known with the given name.
10693     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10694                                               *E->getDestroyedTypeIdentifier(),
10695                                                 E->getDestroyedTypeLoc(),
10696                                                 /*Scope=*/nullptr,
10697                                                 SS, ObjectTypePtr,
10698                                                 false);
10699     if (!T)
10700       return ExprError();
10701 
10702     Destroyed
10703       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10704                                                  E->getDestroyedTypeLoc());
10705   }
10706 
10707   TypeSourceInfo *ScopeTypeInfo = nullptr;
10708   if (E->getScopeTypeInfo()) {
10709     CXXScopeSpec EmptySS;
10710     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10711                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10712     if (!ScopeTypeInfo)
10713       return ExprError();
10714   }
10715 
10716   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10717                                                      E->getOperatorLoc(),
10718                                                      E->isArrow(),
10719                                                      SS,
10720                                                      ScopeTypeInfo,
10721                                                      E->getColonColonLoc(),
10722                                                      E->getTildeLoc(),
10723                                                      Destroyed);
10724 }
10725 
10726 template <typename Derived>
10727 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10728                                                         bool RequiresADL,
10729                                                         LookupResult &R) {
10730   // Transform all the decls.
10731   bool AllEmptyPacks = true;
10732   for (auto *OldD : Old->decls()) {
10733     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10734     if (!InstD) {
10735       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10736       // This can happen because of dependent hiding.
10737       if (isa<UsingShadowDecl>(OldD))
10738         continue;
10739       else {
10740         R.clear();
10741         return true;
10742       }
10743     }
10744 
10745     // Expand using pack declarations.
10746     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10747     ArrayRef<NamedDecl*> Decls = SingleDecl;
10748     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10749       Decls = UPD->expansions();
10750 
10751     // Expand using declarations.
10752     for (auto *D : Decls) {
10753       if (auto *UD = dyn_cast<UsingDecl>(D)) {
10754         for (auto *SD : UD->shadows())
10755           R.addDecl(SD);
10756       } else {
10757         R.addDecl(D);
10758       }
10759     }
10760 
10761     AllEmptyPacks &= Decls.empty();
10762   };
10763 
10764   // C++ [temp.res]/8.4.2:
10765   //   The program is ill-formed, no diagnostic required, if [...] lookup for
10766   //   a name in the template definition found a using-declaration, but the
10767   //   lookup in the corresponding scope in the instantiation odoes not find
10768   //   any declarations because the using-declaration was a pack expansion and
10769   //   the corresponding pack is empty
10770   if (AllEmptyPacks && !RequiresADL) {
10771     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10772         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10773     return true;
10774   }
10775 
10776   // Resolve a kind, but don't do any further analysis.  If it's
10777   // ambiguous, the callee needs to deal with it.
10778   R.resolveKind();
10779   return false;
10780 }
10781 
10782 template<typename Derived>
10783 ExprResult
10784 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10785                                                   UnresolvedLookupExpr *Old) {
10786   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10787                  Sema::LookupOrdinaryName);
10788 
10789   // Transform the declaration set.
10790   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10791     return ExprError();
10792 
10793   // Rebuild the nested-name qualifier, if present.
10794   CXXScopeSpec SS;
10795   if (Old->getQualifierLoc()) {
10796     NestedNameSpecifierLoc QualifierLoc
10797       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10798     if (!QualifierLoc)
10799       return ExprError();
10800 
10801     SS.Adopt(QualifierLoc);
10802   }
10803 
10804   if (Old->getNamingClass()) {
10805     CXXRecordDecl *NamingClass
10806       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10807                                                             Old->getNameLoc(),
10808                                                         Old->getNamingClass()));
10809     if (!NamingClass) {
10810       R.clear();
10811       return ExprError();
10812     }
10813 
10814     R.setNamingClass(NamingClass);
10815   }
10816 
10817   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10818 
10819   // If we have neither explicit template arguments, nor the template keyword,
10820   // it's a normal declaration name or member reference.
10821   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10822     NamedDecl *D = R.getAsSingle<NamedDecl>();
10823     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10824     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10825     // give a good diagnostic.
10826     if (D && D->isCXXInstanceMember()) {
10827       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10828                                                      /*TemplateArgs=*/nullptr,
10829                                                      /*Scope=*/nullptr);
10830     }
10831 
10832     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10833   }
10834 
10835   // If we have template arguments, rebuild them, then rebuild the
10836   // templateid expression.
10837   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10838   if (Old->hasExplicitTemplateArgs() &&
10839       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10840                                               Old->getNumTemplateArgs(),
10841                                               TransArgs)) {
10842     R.clear();
10843     return ExprError();
10844   }
10845 
10846   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10847                                             Old->requiresADL(), &TransArgs);
10848 }
10849 
10850 template<typename Derived>
10851 ExprResult
10852 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10853   bool ArgChanged = false;
10854   SmallVector<TypeSourceInfo *, 4> Args;
10855   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10856     TypeSourceInfo *From = E->getArg(I);
10857     TypeLoc FromTL = From->getTypeLoc();
10858     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10859       TypeLocBuilder TLB;
10860       TLB.reserve(FromTL.getFullDataSize());
10861       QualType To = getDerived().TransformType(TLB, FromTL);
10862       if (To.isNull())
10863         return ExprError();
10864 
10865       if (To == From->getType())
10866         Args.push_back(From);
10867       else {
10868         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10869         ArgChanged = true;
10870       }
10871       continue;
10872     }
10873 
10874     ArgChanged = true;
10875 
10876     // We have a pack expansion. Instantiate it.
10877     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10878     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10879     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10880     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
10881 
10882     // Determine whether the set of unexpanded parameter packs can and should
10883     // be expanded.
10884     bool Expand = true;
10885     bool RetainExpansion = false;
10886     Optional<unsigned> OrigNumExpansions =
10887         ExpansionTL.getTypePtr()->getNumExpansions();
10888     Optional<unsigned> NumExpansions = OrigNumExpansions;
10889     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
10890                                              PatternTL.getSourceRange(),
10891                                              Unexpanded,
10892                                              Expand, RetainExpansion,
10893                                              NumExpansions))
10894       return ExprError();
10895 
10896     if (!Expand) {
10897       // The transform has determined that we should perform a simple
10898       // transformation on the pack expansion, producing another pack
10899       // expansion.
10900       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10901 
10902       TypeLocBuilder TLB;
10903       TLB.reserve(From->getTypeLoc().getFullDataSize());
10904 
10905       QualType To = getDerived().TransformType(TLB, PatternTL);
10906       if (To.isNull())
10907         return ExprError();
10908 
10909       To = getDerived().RebuildPackExpansionType(To,
10910                                                  PatternTL.getSourceRange(),
10911                                                  ExpansionTL.getEllipsisLoc(),
10912                                                  NumExpansions);
10913       if (To.isNull())
10914         return ExprError();
10915 
10916       PackExpansionTypeLoc ToExpansionTL
10917         = TLB.push<PackExpansionTypeLoc>(To);
10918       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10919       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10920       continue;
10921     }
10922 
10923     // Expand the pack expansion by substituting for each argument in the
10924     // pack(s).
10925     for (unsigned I = 0; I != *NumExpansions; ++I) {
10926       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
10927       TypeLocBuilder TLB;
10928       TLB.reserve(PatternTL.getFullDataSize());
10929       QualType To = getDerived().TransformType(TLB, PatternTL);
10930       if (To.isNull())
10931         return ExprError();
10932 
10933       if (To->containsUnexpandedParameterPack()) {
10934         To = getDerived().RebuildPackExpansionType(To,
10935                                                    PatternTL.getSourceRange(),
10936                                                    ExpansionTL.getEllipsisLoc(),
10937                                                    NumExpansions);
10938         if (To.isNull())
10939           return ExprError();
10940 
10941         PackExpansionTypeLoc ToExpansionTL
10942           = TLB.push<PackExpansionTypeLoc>(To);
10943         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10944       }
10945 
10946       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10947     }
10948 
10949     if (!RetainExpansion)
10950       continue;
10951 
10952     // If we're supposed to retain a pack expansion, do so by temporarily
10953     // forgetting the partially-substituted parameter pack.
10954     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10955 
10956     TypeLocBuilder TLB;
10957     TLB.reserve(From->getTypeLoc().getFullDataSize());
10958 
10959     QualType To = getDerived().TransformType(TLB, PatternTL);
10960     if (To.isNull())
10961       return ExprError();
10962 
10963     To = getDerived().RebuildPackExpansionType(To,
10964                                                PatternTL.getSourceRange(),
10965                                                ExpansionTL.getEllipsisLoc(),
10966                                                NumExpansions);
10967     if (To.isNull())
10968       return ExprError();
10969 
10970     PackExpansionTypeLoc ToExpansionTL
10971       = TLB.push<PackExpansionTypeLoc>(To);
10972     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10973     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10974   }
10975 
10976   if (!getDerived().AlwaysRebuild() && !ArgChanged)
10977     return E;
10978 
10979   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
10980                                        E->getEndLoc());
10981 }
10982 
10983 template<typename Derived>
10984 ExprResult
10985 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
10986   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
10987   if (!T)
10988     return ExprError();
10989 
10990   if (!getDerived().AlwaysRebuild() &&
10991       T == E->getQueriedTypeSourceInfo())
10992     return E;
10993 
10994   ExprResult SubExpr;
10995   {
10996     EnterExpressionEvaluationContext Unevaluated(
10997         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10998     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
10999     if (SubExpr.isInvalid())
11000       return ExprError();
11001 
11002     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11003       return E;
11004   }
11005 
11006   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11007                                             SubExpr.get(), E->getEndLoc());
11008 }
11009 
11010 template<typename Derived>
11011 ExprResult
11012 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11013   ExprResult SubExpr;
11014   {
11015     EnterExpressionEvaluationContext Unevaluated(
11016         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11017     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11018     if (SubExpr.isInvalid())
11019       return ExprError();
11020 
11021     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11022       return E;
11023   }
11024 
11025   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11026                                              SubExpr.get(), E->getEndLoc());
11027 }
11028 
11029 template <typename Derived>
11030 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11031     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11032     TypeSourceInfo **RecoveryTSI) {
11033   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11034       DRE, AddrTaken, RecoveryTSI);
11035 
11036   // Propagate both errors and recovered types, which return ExprEmpty.
11037   if (!NewDRE.isUsable())
11038     return NewDRE;
11039 
11040   // We got an expr, wrap it up in parens.
11041   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11042     return PE;
11043   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11044                                        PE->getRParen());
11045 }
11046 
11047 template <typename Derived>
11048 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11049     DependentScopeDeclRefExpr *E) {
11050   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11051                                             nullptr);
11052 }
11053 
11054 template<typename Derived>
11055 ExprResult
11056 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11057                                                DependentScopeDeclRefExpr *E,
11058                                                bool IsAddressOfOperand,
11059                                                TypeSourceInfo **RecoveryTSI) {
11060   assert(E->getQualifierLoc());
11061   NestedNameSpecifierLoc QualifierLoc
11062   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11063   if (!QualifierLoc)
11064     return ExprError();
11065   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11066 
11067   // TODO: If this is a conversion-function-id, verify that the
11068   // destination type name (if present) resolves the same way after
11069   // instantiation as it did in the local scope.
11070 
11071   DeclarationNameInfo NameInfo
11072     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11073   if (!NameInfo.getName())
11074     return ExprError();
11075 
11076   if (!E->hasExplicitTemplateArgs()) {
11077     if (!getDerived().AlwaysRebuild() &&
11078         QualifierLoc == E->getQualifierLoc() &&
11079         // Note: it is sufficient to compare the Name component of NameInfo:
11080         // if name has not changed, DNLoc has not changed either.
11081         NameInfo.getName() == E->getDeclName())
11082       return E;
11083 
11084     return getDerived().RebuildDependentScopeDeclRefExpr(
11085         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11086         IsAddressOfOperand, RecoveryTSI);
11087   }
11088 
11089   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11090   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11091                                               E->getNumTemplateArgs(),
11092                                               TransArgs))
11093     return ExprError();
11094 
11095   return getDerived().RebuildDependentScopeDeclRefExpr(
11096       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11097       RecoveryTSI);
11098 }
11099 
11100 template<typename Derived>
11101 ExprResult
11102 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11103   // CXXConstructExprs other than for list-initialization and
11104   // CXXTemporaryObjectExpr are always implicit, so when we have
11105   // a 1-argument construction we just transform that argument.
11106   if ((E->getNumArgs() == 1 ||
11107        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11108       (!getDerived().DropCallArgument(E->getArg(0))) &&
11109       !E->isListInitialization())
11110     return getDerived().TransformExpr(E->getArg(0));
11111 
11112   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11113 
11114   QualType T = getDerived().TransformType(E->getType());
11115   if (T.isNull())
11116     return ExprError();
11117 
11118   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11119       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11120   if (!Constructor)
11121     return ExprError();
11122 
11123   bool ArgumentChanged = false;
11124   SmallVector<Expr*, 8> Args;
11125   {
11126     EnterExpressionEvaluationContext Context(
11127         getSema(), EnterExpressionEvaluationContext::InitList,
11128         E->isListInitialization());
11129     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11130                                     &ArgumentChanged))
11131       return ExprError();
11132   }
11133 
11134   if (!getDerived().AlwaysRebuild() &&
11135       T == E->getType() &&
11136       Constructor == E->getConstructor() &&
11137       !ArgumentChanged) {
11138     // Mark the constructor as referenced.
11139     // FIXME: Instantiation-specific
11140     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11141     return E;
11142   }
11143 
11144   return getDerived().RebuildCXXConstructExpr(
11145       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11146       E->hadMultipleCandidates(), E->isListInitialization(),
11147       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11148       E->getConstructionKind(), E->getParenOrBraceRange());
11149 }
11150 
11151 template<typename Derived>
11152 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11153     CXXInheritedCtorInitExpr *E) {
11154   QualType T = getDerived().TransformType(E->getType());
11155   if (T.isNull())
11156     return ExprError();
11157 
11158   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11159       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11160   if (!Constructor)
11161     return ExprError();
11162 
11163   if (!getDerived().AlwaysRebuild() &&
11164       T == E->getType() &&
11165       Constructor == E->getConstructor()) {
11166     // Mark the constructor as referenced.
11167     // FIXME: Instantiation-specific
11168     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11169     return E;
11170   }
11171 
11172   return getDerived().RebuildCXXInheritedCtorInitExpr(
11173       T, E->getLocation(), Constructor,
11174       E->constructsVBase(), E->inheritedFromVBase());
11175 }
11176 
11177 /// Transform a C++ temporary-binding expression.
11178 ///
11179 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11180 /// transform the subexpression and return that.
11181 template<typename Derived>
11182 ExprResult
11183 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11184   return getDerived().TransformExpr(E->getSubExpr());
11185 }
11186 
11187 /// Transform a C++ expression that contains cleanups that should
11188 /// be run after the expression is evaluated.
11189 ///
11190 /// Since ExprWithCleanups nodes are implicitly generated, we
11191 /// just transform the subexpression and return that.
11192 template<typename Derived>
11193 ExprResult
11194 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11195   return getDerived().TransformExpr(E->getSubExpr());
11196 }
11197 
11198 template<typename Derived>
11199 ExprResult
11200 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11201                                                     CXXTemporaryObjectExpr *E) {
11202   TypeSourceInfo *T =
11203       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11204   if (!T)
11205     return ExprError();
11206 
11207   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11208       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11209   if (!Constructor)
11210     return ExprError();
11211 
11212   bool ArgumentChanged = false;
11213   SmallVector<Expr*, 8> Args;
11214   Args.reserve(E->getNumArgs());
11215   {
11216     EnterExpressionEvaluationContext Context(
11217         getSema(), EnterExpressionEvaluationContext::InitList,
11218         E->isListInitialization());
11219     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11220                        &ArgumentChanged))
11221       return ExprError();
11222   }
11223 
11224   if (!getDerived().AlwaysRebuild() &&
11225       T == E->getTypeSourceInfo() &&
11226       Constructor == E->getConstructor() &&
11227       !ArgumentChanged) {
11228     // FIXME: Instantiation-specific
11229     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11230     return SemaRef.MaybeBindToTemporary(E);
11231   }
11232 
11233   // FIXME: We should just pass E->isListInitialization(), but we're not
11234   // prepared to handle list-initialization without a child InitListExpr.
11235   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11236   return getDerived().RebuildCXXTemporaryObjectExpr(
11237       T, LParenLoc, Args, E->getEndLoc(),
11238       /*ListInitialization=*/LParenLoc.isInvalid());
11239 }
11240 
11241 template<typename Derived>
11242 ExprResult
11243 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11244   // Transform any init-capture expressions before entering the scope of the
11245   // lambda body, because they are not semantically within that scope.
11246   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11247   struct TransformedInitCapture {
11248     // The location of the ... if the result is retaining a pack expansion.
11249     SourceLocation EllipsisLoc;
11250     // Zero or more expansions of the init-capture.
11251     SmallVector<InitCaptureInfoTy, 4> Expansions;
11252   };
11253   SmallVector<TransformedInitCapture, 4> InitCaptures;
11254   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11255   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11256                                     CEnd = E->capture_end();
11257        C != CEnd; ++C) {
11258     if (!E->isInitCapture(C))
11259       continue;
11260 
11261     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11262     VarDecl *OldVD = C->getCapturedVar();
11263 
11264     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11265                                 Optional<unsigned> NumExpansions) {
11266       ExprResult NewExprInitResult = getDerived().TransformInitializer(
11267           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11268 
11269       if (NewExprInitResult.isInvalid()) {
11270         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11271         return;
11272       }
11273       Expr *NewExprInit = NewExprInitResult.get();
11274 
11275       QualType NewInitCaptureType =
11276           getSema().buildLambdaInitCaptureInitialization(
11277               C->getLocation(), OldVD->getType()->isReferenceType(),
11278               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11279               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11280               NewExprInit);
11281       Result.Expansions.push_back(
11282           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11283     };
11284 
11285     // If this is an init-capture pack, consider expanding the pack now.
11286     if (OldVD->isParameterPack()) {
11287       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11288                                              ->getTypeLoc()
11289                                              .castAs<PackExpansionTypeLoc>();
11290       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11291       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11292 
11293       // Determine whether the set of unexpanded parameter packs can and should
11294       // be expanded.
11295       bool Expand = true;
11296       bool RetainExpansion = false;
11297       Optional<unsigned> OrigNumExpansions =
11298           ExpansionTL.getTypePtr()->getNumExpansions();
11299       Optional<unsigned> NumExpansions = OrigNumExpansions;
11300       if (getDerived().TryExpandParameterPacks(
11301               ExpansionTL.getEllipsisLoc(),
11302               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11303               RetainExpansion, NumExpansions))
11304         return ExprError();
11305       if (Expand) {
11306         for (unsigned I = 0; I != *NumExpansions; ++I) {
11307           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11308           SubstInitCapture(SourceLocation(), None);
11309         }
11310       }
11311       if (!Expand || RetainExpansion) {
11312         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11313         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11314         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11315       }
11316     } else {
11317       SubstInitCapture(SourceLocation(), None);
11318     }
11319   }
11320 
11321   // Transform the template parameters, and add them to the current
11322   // instantiation scope. The null case is handled correctly.
11323   auto TPL = getDerived().TransformTemplateParameterList(
11324       E->getTemplateParameterList());
11325 
11326   // Transform the type of the original lambda's call operator.
11327   // The transformation MUST be done in the CurrentInstantiationScope since
11328   // it introduces a mapping of the original to the newly created
11329   // transformed parameters.
11330   TypeSourceInfo *NewCallOpTSI = nullptr;
11331   {
11332     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11333     FunctionProtoTypeLoc OldCallOpFPTL =
11334         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11335 
11336     TypeLocBuilder NewCallOpTLBuilder;
11337     SmallVector<QualType, 4> ExceptionStorage;
11338     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11339     QualType NewCallOpType = TransformFunctionProtoType(
11340         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11341         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11342           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11343                                               ExceptionStorage, Changed);
11344         });
11345     if (NewCallOpType.isNull())
11346       return ExprError();
11347     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11348                                                         NewCallOpType);
11349   }
11350 
11351   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11352   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11353   LSI->GLTemplateParameterList = TPL;
11354 
11355   // Create the local class that will describe the lambda.
11356   CXXRecordDecl *OldClass = E->getLambdaClass();
11357   CXXRecordDecl *Class
11358     = getSema().createLambdaClosureType(E->getIntroducerRange(),
11359                                         NewCallOpTSI,
11360                                         /*KnownDependent=*/false,
11361                                         E->getCaptureDefault());
11362   getDerived().transformedLocalDecl(OldClass, {Class});
11363 
11364   Optional<std::pair<unsigned, Decl*>> Mangling;
11365   if (getDerived().ReplacingOriginal())
11366     Mangling = std::make_pair(OldClass->getLambdaManglingNumber(),
11367                               OldClass->getLambdaContextDecl());
11368 
11369   // Build the call operator.
11370   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11371       Class, E->getIntroducerRange(), NewCallOpTSI,
11372       E->getCallOperator()->getEndLoc(),
11373       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11374       E->getCallOperator()->getConstexprKind(), Mangling);
11375 
11376   LSI->CallOperator = NewCallOperator;
11377 
11378   for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11379        I != NumParams; ++I) {
11380     auto *P = NewCallOperator->getParamDecl(I);
11381     if (P->hasUninstantiatedDefaultArg()) {
11382       EnterExpressionEvaluationContext Eval(
11383           getSema(),
11384           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11385       ExprResult R = getDerived().TransformExpr(
11386           E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11387       P->setDefaultArg(R.get());
11388     }
11389   }
11390 
11391   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11392   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11393 
11394   // Introduce the context of the call operator.
11395   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11396                                  /*NewThisContext*/false);
11397 
11398   // Enter the scope of the lambda.
11399   getSema().buildLambdaScope(LSI, NewCallOperator,
11400                              E->getIntroducerRange(),
11401                              E->getCaptureDefault(),
11402                              E->getCaptureDefaultLoc(),
11403                              E->hasExplicitParameters(),
11404                              E->hasExplicitResultType(),
11405                              E->isMutable());
11406 
11407   bool Invalid = false;
11408 
11409   // Transform captures.
11410   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11411                                  CEnd = E->capture_end();
11412        C != CEnd; ++C) {
11413     // When we hit the first implicit capture, tell Sema that we've finished
11414     // the list of explicit captures.
11415     if (C->isImplicit())
11416       break;
11417 
11418     // Capturing 'this' is trivial.
11419     if (C->capturesThis()) {
11420       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11421                                     /*BuildAndDiagnose*/ true, nullptr,
11422                                     C->getCaptureKind() == LCK_StarThis);
11423       continue;
11424     }
11425     // Captured expression will be recaptured during captured variables
11426     // rebuilding.
11427     if (C->capturesVLAType())
11428       continue;
11429 
11430     // Rebuild init-captures, including the implied field declaration.
11431     if (E->isInitCapture(C)) {
11432       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11433 
11434       VarDecl *OldVD = C->getCapturedVar();
11435       llvm::SmallVector<Decl*, 4> NewVDs;
11436 
11437       for (InitCaptureInfoTy &Info : NewC.Expansions) {
11438         ExprResult Init = Info.first;
11439         QualType InitQualType = Info.second;
11440         if (Init.isInvalid() || InitQualType.isNull()) {
11441           Invalid = true;
11442           break;
11443         }
11444         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11445             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11446             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11447         if (!NewVD) {
11448           Invalid = true;
11449           break;
11450         }
11451         NewVDs.push_back(NewVD);
11452         getSema().addInitCapture(LSI, NewVD);
11453       }
11454 
11455       if (Invalid)
11456         break;
11457 
11458       getDerived().transformedLocalDecl(OldVD, NewVDs);
11459       continue;
11460     }
11461 
11462     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11463 
11464     // Determine the capture kind for Sema.
11465     Sema::TryCaptureKind Kind
11466       = C->isImplicit()? Sema::TryCapture_Implicit
11467                        : C->getCaptureKind() == LCK_ByCopy
11468                            ? Sema::TryCapture_ExplicitByVal
11469                            : Sema::TryCapture_ExplicitByRef;
11470     SourceLocation EllipsisLoc;
11471     if (C->isPackExpansion()) {
11472       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11473       bool ShouldExpand = false;
11474       bool RetainExpansion = false;
11475       Optional<unsigned> NumExpansions;
11476       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11477                                                C->getLocation(),
11478                                                Unexpanded,
11479                                                ShouldExpand, RetainExpansion,
11480                                                NumExpansions)) {
11481         Invalid = true;
11482         continue;
11483       }
11484 
11485       if (ShouldExpand) {
11486         // The transform has determined that we should perform an expansion;
11487         // transform and capture each of the arguments.
11488         // expansion of the pattern. Do so.
11489         VarDecl *Pack = C->getCapturedVar();
11490         for (unsigned I = 0; I != *NumExpansions; ++I) {
11491           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11492           VarDecl *CapturedVar
11493             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11494                                                                Pack));
11495           if (!CapturedVar) {
11496             Invalid = true;
11497             continue;
11498           }
11499 
11500           // Capture the transformed variable.
11501           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11502         }
11503 
11504         // FIXME: Retain a pack expansion if RetainExpansion is true.
11505 
11506         continue;
11507       }
11508 
11509       EllipsisLoc = C->getEllipsisLoc();
11510     }
11511 
11512     // Transform the captured variable.
11513     VarDecl *CapturedVar
11514       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11515                                                          C->getCapturedVar()));
11516     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11517       Invalid = true;
11518       continue;
11519     }
11520 
11521     // Capture the transformed variable.
11522     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11523                                  EllipsisLoc);
11524   }
11525   getSema().finishLambdaExplicitCaptures(LSI);
11526 
11527   // FIXME: Sema's lambda-building mechanism expects us to push an expression
11528   // evaluation context even if we're not transforming the function body.
11529   getSema().PushExpressionEvaluationContext(
11530       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11531 
11532   // Instantiate the body of the lambda expression.
11533   StmtResult Body =
11534       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
11535 
11536   // ActOnLambda* will pop the function scope for us.
11537   FuncScopeCleanup.disable();
11538 
11539   if (Body.isInvalid()) {
11540     SavedContext.pop();
11541     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11542                                /*IsInstantiation=*/true);
11543     return ExprError();
11544   }
11545 
11546   // Copy the LSI before ActOnFinishFunctionBody removes it.
11547   // FIXME: This is dumb. Store the lambda information somewhere that outlives
11548   // the call operator.
11549   auto LSICopy = *LSI;
11550   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11551                                     /*IsInstantiation*/ true);
11552   SavedContext.pop();
11553 
11554   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11555                                    &LSICopy);
11556 }
11557 
11558 template<typename Derived>
11559 StmtResult
11560 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
11561   return TransformStmt(S);
11562 }
11563 
11564 template<typename Derived>
11565 StmtResult
11566 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
11567   // Transform captures.
11568   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11569                                  CEnd = E->capture_end();
11570        C != CEnd; ++C) {
11571     // When we hit the first implicit capture, tell Sema that we've finished
11572     // the list of explicit captures.
11573     if (!C->isImplicit())
11574       continue;
11575 
11576     // Capturing 'this' is trivial.
11577     if (C->capturesThis()) {
11578       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11579                                     /*BuildAndDiagnose*/ true, nullptr,
11580                                     C->getCaptureKind() == LCK_StarThis);
11581       continue;
11582     }
11583     // Captured expression will be recaptured during captured variables
11584     // rebuilding.
11585     if (C->capturesVLAType())
11586       continue;
11587 
11588     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11589     assert(!E->isInitCapture(C) && "implicit init-capture?");
11590 
11591     // Transform the captured variable.
11592     VarDecl *CapturedVar = cast_or_null<VarDecl>(
11593         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
11594     if (!CapturedVar || CapturedVar->isInvalidDecl())
11595       return StmtError();
11596 
11597     // Capture the transformed variable.
11598     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
11599   }
11600 
11601   return S;
11602 }
11603 
11604 template<typename Derived>
11605 ExprResult
11606 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11607                                                   CXXUnresolvedConstructExpr *E) {
11608   TypeSourceInfo *T =
11609       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11610   if (!T)
11611     return ExprError();
11612 
11613   bool ArgumentChanged = false;
11614   SmallVector<Expr*, 8> Args;
11615   Args.reserve(E->arg_size());
11616   {
11617     EnterExpressionEvaluationContext Context(
11618         getSema(), EnterExpressionEvaluationContext::InitList,
11619         E->isListInitialization());
11620     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11621                                     &ArgumentChanged))
11622       return ExprError();
11623   }
11624 
11625   if (!getDerived().AlwaysRebuild() &&
11626       T == E->getTypeSourceInfo() &&
11627       !ArgumentChanged)
11628     return E;
11629 
11630   // FIXME: we're faking the locations of the commas
11631   return getDerived().RebuildCXXUnresolvedConstructExpr(
11632       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11633 }
11634 
11635 template<typename Derived>
11636 ExprResult
11637 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11638                                              CXXDependentScopeMemberExpr *E) {
11639   // Transform the base of the expression.
11640   ExprResult Base((Expr*) nullptr);
11641   Expr *OldBase;
11642   QualType BaseType;
11643   QualType ObjectType;
11644   if (!E->isImplicitAccess()) {
11645     OldBase = E->getBase();
11646     Base = getDerived().TransformExpr(OldBase);
11647     if (Base.isInvalid())
11648       return ExprError();
11649 
11650     // Start the member reference and compute the object's type.
11651     ParsedType ObjectTy;
11652     bool MayBePseudoDestructor = false;
11653     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11654                                                 E->getOperatorLoc(),
11655                                       E->isArrow()? tok::arrow : tok::period,
11656                                                 ObjectTy,
11657                                                 MayBePseudoDestructor);
11658     if (Base.isInvalid())
11659       return ExprError();
11660 
11661     ObjectType = ObjectTy.get();
11662     BaseType = ((Expr*) Base.get())->getType();
11663   } else {
11664     OldBase = nullptr;
11665     BaseType = getDerived().TransformType(E->getBaseType());
11666     ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
11667   }
11668 
11669   // Transform the first part of the nested-name-specifier that qualifies
11670   // the member name.
11671   NamedDecl *FirstQualifierInScope
11672     = getDerived().TransformFirstQualifierInScope(
11673                                             E->getFirstQualifierFoundInScope(),
11674                                             E->getQualifierLoc().getBeginLoc());
11675 
11676   NestedNameSpecifierLoc QualifierLoc;
11677   if (E->getQualifier()) {
11678     QualifierLoc
11679       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11680                                                      ObjectType,
11681                                                      FirstQualifierInScope);
11682     if (!QualifierLoc)
11683       return ExprError();
11684   }
11685 
11686   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11687 
11688   // TODO: If this is a conversion-function-id, verify that the
11689   // destination type name (if present) resolves the same way after
11690   // instantiation as it did in the local scope.
11691 
11692   DeclarationNameInfo NameInfo
11693     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11694   if (!NameInfo.getName())
11695     return ExprError();
11696 
11697   if (!E->hasExplicitTemplateArgs()) {
11698     // This is a reference to a member without an explicitly-specified
11699     // template argument list. Optimize for this common case.
11700     if (!getDerived().AlwaysRebuild() &&
11701         Base.get() == OldBase &&
11702         BaseType == E->getBaseType() &&
11703         QualifierLoc == E->getQualifierLoc() &&
11704         NameInfo.getName() == E->getMember() &&
11705         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11706       return E;
11707 
11708     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11709                                                        BaseType,
11710                                                        E->isArrow(),
11711                                                        E->getOperatorLoc(),
11712                                                        QualifierLoc,
11713                                                        TemplateKWLoc,
11714                                                        FirstQualifierInScope,
11715                                                        NameInfo,
11716                                                        /*TemplateArgs*/nullptr);
11717   }
11718 
11719   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11720   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11721                                               E->getNumTemplateArgs(),
11722                                               TransArgs))
11723     return ExprError();
11724 
11725   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11726                                                      BaseType,
11727                                                      E->isArrow(),
11728                                                      E->getOperatorLoc(),
11729                                                      QualifierLoc,
11730                                                      TemplateKWLoc,
11731                                                      FirstQualifierInScope,
11732                                                      NameInfo,
11733                                                      &TransArgs);
11734 }
11735 
11736 template<typename Derived>
11737 ExprResult
11738 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11739   // Transform the base of the expression.
11740   ExprResult Base((Expr*) nullptr);
11741   QualType BaseType;
11742   if (!Old->isImplicitAccess()) {
11743     Base = getDerived().TransformExpr(Old->getBase());
11744     if (Base.isInvalid())
11745       return ExprError();
11746     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11747                                                      Old->isArrow());
11748     if (Base.isInvalid())
11749       return ExprError();
11750     BaseType = Base.get()->getType();
11751   } else {
11752     BaseType = getDerived().TransformType(Old->getBaseType());
11753   }
11754 
11755   NestedNameSpecifierLoc QualifierLoc;
11756   if (Old->getQualifierLoc()) {
11757     QualifierLoc
11758     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11759     if (!QualifierLoc)
11760       return ExprError();
11761   }
11762 
11763   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11764 
11765   LookupResult R(SemaRef, Old->getMemberNameInfo(),
11766                  Sema::LookupOrdinaryName);
11767 
11768   // Transform the declaration set.
11769   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11770     return ExprError();
11771 
11772   // Determine the naming class.
11773   if (Old->getNamingClass()) {
11774     CXXRecordDecl *NamingClass
11775       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11776                                                           Old->getMemberLoc(),
11777                                                         Old->getNamingClass()));
11778     if (!NamingClass)
11779       return ExprError();
11780 
11781     R.setNamingClass(NamingClass);
11782   }
11783 
11784   TemplateArgumentListInfo TransArgs;
11785   if (Old->hasExplicitTemplateArgs()) {
11786     TransArgs.setLAngleLoc(Old->getLAngleLoc());
11787     TransArgs.setRAngleLoc(Old->getRAngleLoc());
11788     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11789                                                 Old->getNumTemplateArgs(),
11790                                                 TransArgs))
11791       return ExprError();
11792   }
11793 
11794   // FIXME: to do this check properly, we will need to preserve the
11795   // first-qualifier-in-scope here, just in case we had a dependent
11796   // base (and therefore couldn't do the check) and a
11797   // nested-name-qualifier (and therefore could do the lookup).
11798   NamedDecl *FirstQualifierInScope = nullptr;
11799 
11800   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11801                                                   BaseType,
11802                                                   Old->getOperatorLoc(),
11803                                                   Old->isArrow(),
11804                                                   QualifierLoc,
11805                                                   TemplateKWLoc,
11806                                                   FirstQualifierInScope,
11807                                                   R,
11808                                               (Old->hasExplicitTemplateArgs()
11809                                                   ? &TransArgs : nullptr));
11810 }
11811 
11812 template<typename Derived>
11813 ExprResult
11814 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11815   EnterExpressionEvaluationContext Unevaluated(
11816       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11817   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11818   if (SubExpr.isInvalid())
11819     return ExprError();
11820 
11821   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11822     return E;
11823 
11824   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11825 }
11826 
11827 template<typename Derived>
11828 ExprResult
11829 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11830   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11831   if (Pattern.isInvalid())
11832     return ExprError();
11833 
11834   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11835     return E;
11836 
11837   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11838                                            E->getNumExpansions());
11839 }
11840 
11841 template<typename Derived>
11842 ExprResult
11843 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11844   // If E is not value-dependent, then nothing will change when we transform it.
11845   // Note: This is an instantiation-centric view.
11846   if (!E->isValueDependent())
11847     return E;
11848 
11849   EnterExpressionEvaluationContext Unevaluated(
11850       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11851 
11852   ArrayRef<TemplateArgument> PackArgs;
11853   TemplateArgument ArgStorage;
11854 
11855   // Find the argument list to transform.
11856   if (E->isPartiallySubstituted()) {
11857     PackArgs = E->getPartialArguments();
11858   } else if (E->isValueDependent()) {
11859     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
11860     bool ShouldExpand = false;
11861     bool RetainExpansion = false;
11862     Optional<unsigned> NumExpansions;
11863     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
11864                                              Unexpanded,
11865                                              ShouldExpand, RetainExpansion,
11866                                              NumExpansions))
11867       return ExprError();
11868 
11869     // If we need to expand the pack, build a template argument from it and
11870     // expand that.
11871     if (ShouldExpand) {
11872       auto *Pack = E->getPack();
11873       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
11874         ArgStorage = getSema().Context.getPackExpansionType(
11875             getSema().Context.getTypeDeclType(TTPD), None);
11876       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
11877         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
11878       } else {
11879         auto *VD = cast<ValueDecl>(Pack);
11880         ExprResult DRE = getSema().BuildDeclRefExpr(
11881             VD, VD->getType().getNonLValueExprType(getSema().Context),
11882             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
11883             E->getPackLoc());
11884         if (DRE.isInvalid())
11885           return ExprError();
11886         ArgStorage = new (getSema().Context) PackExpansionExpr(
11887             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
11888       }
11889       PackArgs = ArgStorage;
11890     }
11891   }
11892 
11893   // If we're not expanding the pack, just transform the decl.
11894   if (!PackArgs.size()) {
11895     auto *Pack = cast_or_null<NamedDecl>(
11896         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
11897     if (!Pack)
11898       return ExprError();
11899     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
11900                                               E->getPackLoc(),
11901                                               E->getRParenLoc(), None, None);
11902   }
11903 
11904   // Try to compute the result without performing a partial substitution.
11905   Optional<unsigned> Result = 0;
11906   for (const TemplateArgument &Arg : PackArgs) {
11907     if (!Arg.isPackExpansion()) {
11908       Result = *Result + 1;
11909       continue;
11910     }
11911 
11912     TemplateArgumentLoc ArgLoc;
11913     InventTemplateArgumentLoc(Arg, ArgLoc);
11914 
11915     // Find the pattern of the pack expansion.
11916     SourceLocation Ellipsis;
11917     Optional<unsigned> OrigNumExpansions;
11918     TemplateArgumentLoc Pattern =
11919         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
11920                                                           OrigNumExpansions);
11921 
11922     // Substitute under the pack expansion. Do not expand the pack (yet).
11923     TemplateArgumentLoc OutPattern;
11924     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11925     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
11926                                                /*Uneval*/ true))
11927       return true;
11928 
11929     // See if we can determine the number of arguments from the result.
11930     Optional<unsigned> NumExpansions =
11931         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
11932     if (!NumExpansions) {
11933       // No: we must be in an alias template expansion, and we're going to need
11934       // to actually expand the packs.
11935       Result = None;
11936       break;
11937     }
11938 
11939     Result = *Result + *NumExpansions;
11940   }
11941 
11942   // Common case: we could determine the number of expansions without
11943   // substituting.
11944   if (Result)
11945     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11946                                               E->getPackLoc(),
11947                                               E->getRParenLoc(), *Result, None);
11948 
11949   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
11950                                                E->getPackLoc());
11951   {
11952     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
11953     typedef TemplateArgumentLocInventIterator<
11954         Derived, const TemplateArgument*> PackLocIterator;
11955     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
11956                                    PackLocIterator(*this, PackArgs.end()),
11957                                    TransformedPackArgs, /*Uneval*/true))
11958       return ExprError();
11959   }
11960 
11961   // Check whether we managed to fully-expand the pack.
11962   // FIXME: Is it possible for us to do so and not hit the early exit path?
11963   SmallVector<TemplateArgument, 8> Args;
11964   bool PartialSubstitution = false;
11965   for (auto &Loc : TransformedPackArgs.arguments()) {
11966     Args.push_back(Loc.getArgument());
11967     if (Loc.getArgument().isPackExpansion())
11968       PartialSubstitution = true;
11969   }
11970 
11971   if (PartialSubstitution)
11972     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11973                                               E->getPackLoc(),
11974                                               E->getRParenLoc(), None, Args);
11975 
11976   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11977                                             E->getPackLoc(), E->getRParenLoc(),
11978                                             Args.size(), None);
11979 }
11980 
11981 template<typename Derived>
11982 ExprResult
11983 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
11984                                           SubstNonTypeTemplateParmPackExpr *E) {
11985   // Default behavior is to do nothing with this transformation.
11986   return E;
11987 }
11988 
11989 template<typename Derived>
11990 ExprResult
11991 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
11992                                           SubstNonTypeTemplateParmExpr *E) {
11993   // Default behavior is to do nothing with this transformation.
11994   return E;
11995 }
11996 
11997 template<typename Derived>
11998 ExprResult
11999 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12000   // Default behavior is to do nothing with this transformation.
12001   return E;
12002 }
12003 
12004 template<typename Derived>
12005 ExprResult
12006 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12007                                                   MaterializeTemporaryExpr *E) {
12008   return getDerived().TransformExpr(E->GetTemporaryExpr());
12009 }
12010 
12011 template<typename Derived>
12012 ExprResult
12013 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12014   Expr *Pattern = E->getPattern();
12015 
12016   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12017   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12018   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12019 
12020   // Determine whether the set of unexpanded parameter packs can and should
12021   // be expanded.
12022   bool Expand = true;
12023   bool RetainExpansion = false;
12024   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12025                      NumExpansions = OrigNumExpansions;
12026   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12027                                            Pattern->getSourceRange(),
12028                                            Unexpanded,
12029                                            Expand, RetainExpansion,
12030                                            NumExpansions))
12031     return true;
12032 
12033   if (!Expand) {
12034     // Do not expand any packs here, just transform and rebuild a fold
12035     // expression.
12036     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12037 
12038     ExprResult LHS =
12039         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12040     if (LHS.isInvalid())
12041       return true;
12042 
12043     ExprResult RHS =
12044         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12045     if (RHS.isInvalid())
12046       return true;
12047 
12048     if (!getDerived().AlwaysRebuild() &&
12049         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12050       return E;
12051 
12052     return getDerived().RebuildCXXFoldExpr(
12053         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12054         RHS.get(), E->getEndLoc(), NumExpansions);
12055   }
12056 
12057   // The transform has determined that we should perform an elementwise
12058   // expansion of the pattern. Do so.
12059   ExprResult Result = getDerived().TransformExpr(E->getInit());
12060   if (Result.isInvalid())
12061     return true;
12062   bool LeftFold = E->isLeftFold();
12063 
12064   // If we're retaining an expansion for a right fold, it is the innermost
12065   // component and takes the init (if any).
12066   if (!LeftFold && RetainExpansion) {
12067     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12068 
12069     ExprResult Out = getDerived().TransformExpr(Pattern);
12070     if (Out.isInvalid())
12071       return true;
12072 
12073     Result = getDerived().RebuildCXXFoldExpr(
12074         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12075         Result.get(), E->getEndLoc(), OrigNumExpansions);
12076     if (Result.isInvalid())
12077       return true;
12078   }
12079 
12080   for (unsigned I = 0; I != *NumExpansions; ++I) {
12081     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12082         getSema(), LeftFold ? I : *NumExpansions - I - 1);
12083     ExprResult Out = getDerived().TransformExpr(Pattern);
12084     if (Out.isInvalid())
12085       return true;
12086 
12087     if (Out.get()->containsUnexpandedParameterPack()) {
12088       // We still have a pack; retain a pack expansion for this slice.
12089       Result = getDerived().RebuildCXXFoldExpr(
12090           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12091           E->getOperator(), E->getEllipsisLoc(),
12092           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12093           OrigNumExpansions);
12094     } else if (Result.isUsable()) {
12095       // We've got down to a single element; build a binary operator.
12096       Result = getDerived().RebuildBinaryOperator(
12097           E->getEllipsisLoc(), E->getOperator(),
12098           LeftFold ? Result.get() : Out.get(),
12099           LeftFold ? Out.get() : Result.get());
12100     } else
12101       Result = Out;
12102 
12103     if (Result.isInvalid())
12104       return true;
12105   }
12106 
12107   // If we're retaining an expansion for a left fold, it is the outermost
12108   // component and takes the complete expansion so far as its init (if any).
12109   if (LeftFold && RetainExpansion) {
12110     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12111 
12112     ExprResult Out = getDerived().TransformExpr(Pattern);
12113     if (Out.isInvalid())
12114       return true;
12115 
12116     Result = getDerived().RebuildCXXFoldExpr(
12117         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12118         Out.get(), E->getEndLoc(), OrigNumExpansions);
12119     if (Result.isInvalid())
12120       return true;
12121   }
12122 
12123   // If we had no init and an empty pack, and we're not retaining an expansion,
12124   // then produce a fallback value or error.
12125   if (Result.isUnset())
12126     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12127                                                 E->getOperator());
12128 
12129   return Result;
12130 }
12131 
12132 template<typename Derived>
12133 ExprResult
12134 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12135     CXXStdInitializerListExpr *E) {
12136   return getDerived().TransformExpr(E->getSubExpr());
12137 }
12138 
12139 template<typename Derived>
12140 ExprResult
12141 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12142   return SemaRef.MaybeBindToTemporary(E);
12143 }
12144 
12145 template<typename Derived>
12146 ExprResult
12147 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12148   return E;
12149 }
12150 
12151 template<typename Derived>
12152 ExprResult
12153 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12154   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12155   if (SubExpr.isInvalid())
12156     return ExprError();
12157 
12158   if (!getDerived().AlwaysRebuild() &&
12159       SubExpr.get() == E->getSubExpr())
12160     return E;
12161 
12162   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12163 }
12164 
12165 template<typename Derived>
12166 ExprResult
12167 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12168   // Transform each of the elements.
12169   SmallVector<Expr *, 8> Elements;
12170   bool ArgChanged = false;
12171   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12172                                   /*IsCall=*/false, Elements, &ArgChanged))
12173     return ExprError();
12174 
12175   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12176     return SemaRef.MaybeBindToTemporary(E);
12177 
12178   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12179                                               Elements.data(),
12180                                               Elements.size());
12181 }
12182 
12183 template<typename Derived>
12184 ExprResult
12185 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12186                                                     ObjCDictionaryLiteral *E) {
12187   // Transform each of the elements.
12188   SmallVector<ObjCDictionaryElement, 8> Elements;
12189   bool ArgChanged = false;
12190   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12191     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12192 
12193     if (OrigElement.isPackExpansion()) {
12194       // This key/value element is a pack expansion.
12195       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12196       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12197       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12198       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12199 
12200       // Determine whether the set of unexpanded parameter packs can
12201       // and should be expanded.
12202       bool Expand = true;
12203       bool RetainExpansion = false;
12204       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12205       Optional<unsigned> NumExpansions = OrigNumExpansions;
12206       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12207                                OrigElement.Value->getEndLoc());
12208       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12209                                                PatternRange, Unexpanded, Expand,
12210                                                RetainExpansion, NumExpansions))
12211         return ExprError();
12212 
12213       if (!Expand) {
12214         // The transform has determined that we should perform a simple
12215         // transformation on the pack expansion, producing another pack
12216         // expansion.
12217         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12218         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12219         if (Key.isInvalid())
12220           return ExprError();
12221 
12222         if (Key.get() != OrigElement.Key)
12223           ArgChanged = true;
12224 
12225         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12226         if (Value.isInvalid())
12227           return ExprError();
12228 
12229         if (Value.get() != OrigElement.Value)
12230           ArgChanged = true;
12231 
12232         ObjCDictionaryElement Expansion = {
12233           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12234         };
12235         Elements.push_back(Expansion);
12236         continue;
12237       }
12238 
12239       // Record right away that the argument was changed.  This needs
12240       // to happen even if the array expands to nothing.
12241       ArgChanged = true;
12242 
12243       // The transform has determined that we should perform an elementwise
12244       // expansion of the pattern. Do so.
12245       for (unsigned I = 0; I != *NumExpansions; ++I) {
12246         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12247         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12248         if (Key.isInvalid())
12249           return ExprError();
12250 
12251         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12252         if (Value.isInvalid())
12253           return ExprError();
12254 
12255         ObjCDictionaryElement Element = {
12256           Key.get(), Value.get(), SourceLocation(), NumExpansions
12257         };
12258 
12259         // If any unexpanded parameter packs remain, we still have a
12260         // pack expansion.
12261         // FIXME: Can this really happen?
12262         if (Key.get()->containsUnexpandedParameterPack() ||
12263             Value.get()->containsUnexpandedParameterPack())
12264           Element.EllipsisLoc = OrigElement.EllipsisLoc;
12265 
12266         Elements.push_back(Element);
12267       }
12268 
12269       // FIXME: Retain a pack expansion if RetainExpansion is true.
12270 
12271       // We've finished with this pack expansion.
12272       continue;
12273     }
12274 
12275     // Transform and check key.
12276     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12277     if (Key.isInvalid())
12278       return ExprError();
12279 
12280     if (Key.get() != OrigElement.Key)
12281       ArgChanged = true;
12282 
12283     // Transform and check value.
12284     ExprResult Value
12285       = getDerived().TransformExpr(OrigElement.Value);
12286     if (Value.isInvalid())
12287       return ExprError();
12288 
12289     if (Value.get() != OrigElement.Value)
12290       ArgChanged = true;
12291 
12292     ObjCDictionaryElement Element = {
12293       Key.get(), Value.get(), SourceLocation(), None
12294     };
12295     Elements.push_back(Element);
12296   }
12297 
12298   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12299     return SemaRef.MaybeBindToTemporary(E);
12300 
12301   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12302                                                    Elements);
12303 }
12304 
12305 template<typename Derived>
12306 ExprResult
12307 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12308   TypeSourceInfo *EncodedTypeInfo
12309     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12310   if (!EncodedTypeInfo)
12311     return ExprError();
12312 
12313   if (!getDerived().AlwaysRebuild() &&
12314       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12315     return E;
12316 
12317   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12318                                             EncodedTypeInfo,
12319                                             E->getRParenLoc());
12320 }
12321 
12322 template<typename Derived>
12323 ExprResult TreeTransform<Derived>::
12324 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12325   // This is a kind of implicit conversion, and it needs to get dropped
12326   // and recomputed for the same general reasons that ImplicitCastExprs
12327   // do, as well a more specific one: this expression is only valid when
12328   // it appears *immediately* as an argument expression.
12329   return getDerived().TransformExpr(E->getSubExpr());
12330 }
12331 
12332 template<typename Derived>
12333 ExprResult TreeTransform<Derived>::
12334 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12335   TypeSourceInfo *TSInfo
12336     = getDerived().TransformType(E->getTypeInfoAsWritten());
12337   if (!TSInfo)
12338     return ExprError();
12339 
12340   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12341   if (Result.isInvalid())
12342     return ExprError();
12343 
12344   if (!getDerived().AlwaysRebuild() &&
12345       TSInfo == E->getTypeInfoAsWritten() &&
12346       Result.get() == E->getSubExpr())
12347     return E;
12348 
12349   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12350                                       E->getBridgeKeywordLoc(), TSInfo,
12351                                       Result.get());
12352 }
12353 
12354 template <typename Derived>
12355 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12356     ObjCAvailabilityCheckExpr *E) {
12357   return E;
12358 }
12359 
12360 template<typename Derived>
12361 ExprResult
12362 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12363   // Transform arguments.
12364   bool ArgChanged = false;
12365   SmallVector<Expr*, 8> Args;
12366   Args.reserve(E->getNumArgs());
12367   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12368                                   &ArgChanged))
12369     return ExprError();
12370 
12371   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12372     // Class message: transform the receiver type.
12373     TypeSourceInfo *ReceiverTypeInfo
12374       = getDerived().TransformType(E->getClassReceiverTypeInfo());
12375     if (!ReceiverTypeInfo)
12376       return ExprError();
12377 
12378     // If nothing changed, just retain the existing message send.
12379     if (!getDerived().AlwaysRebuild() &&
12380         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12381       return SemaRef.MaybeBindToTemporary(E);
12382 
12383     // Build a new class message send.
12384     SmallVector<SourceLocation, 16> SelLocs;
12385     E->getSelectorLocs(SelLocs);
12386     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12387                                                E->getSelector(),
12388                                                SelLocs,
12389                                                E->getMethodDecl(),
12390                                                E->getLeftLoc(),
12391                                                Args,
12392                                                E->getRightLoc());
12393   }
12394   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12395            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12396     if (!E->getMethodDecl())
12397       return ExprError();
12398 
12399     // Build a new class message send to 'super'.
12400     SmallVector<SourceLocation, 16> SelLocs;
12401     E->getSelectorLocs(SelLocs);
12402     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12403                                                E->getSelector(),
12404                                                SelLocs,
12405                                                E->getReceiverType(),
12406                                                E->getMethodDecl(),
12407                                                E->getLeftLoc(),
12408                                                Args,
12409                                                E->getRightLoc());
12410   }
12411 
12412   // Instance message: transform the receiver
12413   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12414          "Only class and instance messages may be instantiated");
12415   ExprResult Receiver
12416     = getDerived().TransformExpr(E->getInstanceReceiver());
12417   if (Receiver.isInvalid())
12418     return ExprError();
12419 
12420   // If nothing changed, just retain the existing message send.
12421   if (!getDerived().AlwaysRebuild() &&
12422       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12423     return SemaRef.MaybeBindToTemporary(E);
12424 
12425   // Build a new instance message send.
12426   SmallVector<SourceLocation, 16> SelLocs;
12427   E->getSelectorLocs(SelLocs);
12428   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12429                                              E->getSelector(),
12430                                              SelLocs,
12431                                              E->getMethodDecl(),
12432                                              E->getLeftLoc(),
12433                                              Args,
12434                                              E->getRightLoc());
12435 }
12436 
12437 template<typename Derived>
12438 ExprResult
12439 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12440   return E;
12441 }
12442 
12443 template<typename Derived>
12444 ExprResult
12445 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12446   return E;
12447 }
12448 
12449 template<typename Derived>
12450 ExprResult
12451 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12452   // Transform the base expression.
12453   ExprResult Base = getDerived().TransformExpr(E->getBase());
12454   if (Base.isInvalid())
12455     return ExprError();
12456 
12457   // We don't need to transform the ivar; it will never change.
12458 
12459   // If nothing changed, just retain the existing expression.
12460   if (!getDerived().AlwaysRebuild() &&
12461       Base.get() == E->getBase())
12462     return E;
12463 
12464   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12465                                              E->getLocation(),
12466                                              E->isArrow(), E->isFreeIvar());
12467 }
12468 
12469 template<typename Derived>
12470 ExprResult
12471 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12472   // 'super' and types never change. Property never changes. Just
12473   // retain the existing expression.
12474   if (!E->isObjectReceiver())
12475     return E;
12476 
12477   // Transform the base expression.
12478   ExprResult Base = getDerived().TransformExpr(E->getBase());
12479   if (Base.isInvalid())
12480     return ExprError();
12481 
12482   // We don't need to transform the property; it will never change.
12483 
12484   // If nothing changed, just retain the existing expression.
12485   if (!getDerived().AlwaysRebuild() &&
12486       Base.get() == E->getBase())
12487     return E;
12488 
12489   if (E->isExplicitProperty())
12490     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12491                                                    E->getExplicitProperty(),
12492                                                    E->getLocation());
12493 
12494   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12495                                                  SemaRef.Context.PseudoObjectTy,
12496                                                  E->getImplicitPropertyGetter(),
12497                                                  E->getImplicitPropertySetter(),
12498                                                  E->getLocation());
12499 }
12500 
12501 template<typename Derived>
12502 ExprResult
12503 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12504   // Transform the base expression.
12505   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12506   if (Base.isInvalid())
12507     return ExprError();
12508 
12509   // Transform the key expression.
12510   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12511   if (Key.isInvalid())
12512     return ExprError();
12513 
12514   // If nothing changed, just retain the existing expression.
12515   if (!getDerived().AlwaysRebuild() &&
12516       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12517     return E;
12518 
12519   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12520                                                   Base.get(), Key.get(),
12521                                                   E->getAtIndexMethodDecl(),
12522                                                   E->setAtIndexMethodDecl());
12523 }
12524 
12525 template<typename Derived>
12526 ExprResult
12527 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12528   // Transform the base expression.
12529   ExprResult Base = getDerived().TransformExpr(E->getBase());
12530   if (Base.isInvalid())
12531     return ExprError();
12532 
12533   // If nothing changed, just retain the existing expression.
12534   if (!getDerived().AlwaysRebuild() &&
12535       Base.get() == E->getBase())
12536     return E;
12537 
12538   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12539                                          E->getOpLoc(),
12540                                          E->isArrow());
12541 }
12542 
12543 template<typename Derived>
12544 ExprResult
12545 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12546   bool ArgumentChanged = false;
12547   SmallVector<Expr*, 8> SubExprs;
12548   SubExprs.reserve(E->getNumSubExprs());
12549   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12550                                   SubExprs, &ArgumentChanged))
12551     return ExprError();
12552 
12553   if (!getDerived().AlwaysRebuild() &&
12554       !ArgumentChanged)
12555     return E;
12556 
12557   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12558                                                SubExprs,
12559                                                E->getRParenLoc());
12560 }
12561 
12562 template<typename Derived>
12563 ExprResult
12564 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12565   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12566   if (SrcExpr.isInvalid())
12567     return ExprError();
12568 
12569   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12570   if (!Type)
12571     return ExprError();
12572 
12573   if (!getDerived().AlwaysRebuild() &&
12574       Type == E->getTypeSourceInfo() &&
12575       SrcExpr.get() == E->getSrcExpr())
12576     return E;
12577 
12578   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12579                                                SrcExpr.get(), Type,
12580                                                E->getRParenLoc());
12581 }
12582 
12583 template<typename Derived>
12584 ExprResult
12585 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12586   BlockDecl *oldBlock = E->getBlockDecl();
12587 
12588   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12589   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12590 
12591   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12592   blockScope->TheDecl->setBlockMissingReturnType(
12593                          oldBlock->blockMissingReturnType());
12594 
12595   SmallVector<ParmVarDecl*, 4> params;
12596   SmallVector<QualType, 4> paramTypes;
12597 
12598   const FunctionProtoType *exprFunctionType = E->getFunctionType();
12599 
12600   // Parameter substitution.
12601   Sema::ExtParameterInfoBuilder extParamInfos;
12602   if (getDerived().TransformFunctionTypeParams(
12603           E->getCaretLocation(), oldBlock->parameters(), nullptr,
12604           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
12605           extParamInfos)) {
12606     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12607     return ExprError();
12608   }
12609 
12610   QualType exprResultType =
12611       getDerived().TransformType(exprFunctionType->getReturnType());
12612 
12613   auto epi = exprFunctionType->getExtProtoInfo();
12614   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12615 
12616   QualType functionType =
12617     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12618   blockScope->FunctionType = functionType;
12619 
12620   // Set the parameters on the block decl.
12621   if (!params.empty())
12622     blockScope->TheDecl->setParams(params);
12623 
12624   if (!oldBlock->blockMissingReturnType()) {
12625     blockScope->HasImplicitReturnType = false;
12626     blockScope->ReturnType = exprResultType;
12627   }
12628 
12629   // Transform the body
12630   StmtResult body = getDerived().TransformStmt(E->getBody());
12631   if (body.isInvalid()) {
12632     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12633     return ExprError();
12634   }
12635 
12636 #ifndef NDEBUG
12637   // In builds with assertions, make sure that we captured everything we
12638   // captured before.
12639   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12640     for (const auto &I : oldBlock->captures()) {
12641       VarDecl *oldCapture = I.getVariable();
12642 
12643       // Ignore parameter packs.
12644       if (oldCapture->isParameterPack())
12645         continue;
12646 
12647       VarDecl *newCapture =
12648         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12649                                                  oldCapture));
12650       assert(blockScope->CaptureMap.count(newCapture));
12651     }
12652     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12653   }
12654 #endif
12655 
12656   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12657                                     /*Scope=*/nullptr);
12658 }
12659 
12660 template<typename Derived>
12661 ExprResult
12662 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12663   llvm_unreachable("Cannot transform asType expressions yet");
12664 }
12665 
12666 template<typename Derived>
12667 ExprResult
12668 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12669   QualType RetTy = getDerived().TransformType(E->getType());
12670   bool ArgumentChanged = false;
12671   SmallVector<Expr*, 8> SubExprs;
12672   SubExprs.reserve(E->getNumSubExprs());
12673   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12674                                   SubExprs, &ArgumentChanged))
12675     return ExprError();
12676 
12677   if (!getDerived().AlwaysRebuild() &&
12678       !ArgumentChanged)
12679     return E;
12680 
12681   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12682                                         RetTy, E->getOp(), E->getRParenLoc());
12683 }
12684 
12685 //===----------------------------------------------------------------------===//
12686 // Type reconstruction
12687 //===----------------------------------------------------------------------===//
12688 
12689 template<typename Derived>
12690 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12691                                                     SourceLocation Star) {
12692   return SemaRef.BuildPointerType(PointeeType, Star,
12693                                   getDerived().getBaseEntity());
12694 }
12695 
12696 template<typename Derived>
12697 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12698                                                          SourceLocation Star) {
12699   return SemaRef.BuildBlockPointerType(PointeeType, Star,
12700                                        getDerived().getBaseEntity());
12701 }
12702 
12703 template<typename Derived>
12704 QualType
12705 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12706                                              bool WrittenAsLValue,
12707                                              SourceLocation Sigil) {
12708   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12709                                     Sigil, getDerived().getBaseEntity());
12710 }
12711 
12712 template<typename Derived>
12713 QualType
12714 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12715                                                  QualType ClassType,
12716                                                  SourceLocation Sigil) {
12717   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12718                                         getDerived().getBaseEntity());
12719 }
12720 
12721 template<typename Derived>
12722 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12723            const ObjCTypeParamDecl *Decl,
12724            SourceLocation ProtocolLAngleLoc,
12725            ArrayRef<ObjCProtocolDecl *> Protocols,
12726            ArrayRef<SourceLocation> ProtocolLocs,
12727            SourceLocation ProtocolRAngleLoc) {
12728   return SemaRef.BuildObjCTypeParamType(Decl,
12729                                         ProtocolLAngleLoc, Protocols,
12730                                         ProtocolLocs, ProtocolRAngleLoc,
12731                                         /*FailOnError=*/true);
12732 }
12733 
12734 template<typename Derived>
12735 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12736            QualType BaseType,
12737            SourceLocation Loc,
12738            SourceLocation TypeArgsLAngleLoc,
12739            ArrayRef<TypeSourceInfo *> TypeArgs,
12740            SourceLocation TypeArgsRAngleLoc,
12741            SourceLocation ProtocolLAngleLoc,
12742            ArrayRef<ObjCProtocolDecl *> Protocols,
12743            ArrayRef<SourceLocation> ProtocolLocs,
12744            SourceLocation ProtocolRAngleLoc) {
12745   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12746                                      TypeArgs, TypeArgsRAngleLoc,
12747                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
12748                                      ProtocolRAngleLoc,
12749                                      /*FailOnError=*/true);
12750 }
12751 
12752 template<typename Derived>
12753 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12754            QualType PointeeType,
12755            SourceLocation Star) {
12756   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12757 }
12758 
12759 template<typename Derived>
12760 QualType
12761 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12762                                          ArrayType::ArraySizeModifier SizeMod,
12763                                          const llvm::APInt *Size,
12764                                          Expr *SizeExpr,
12765                                          unsigned IndexTypeQuals,
12766                                          SourceRange BracketsRange) {
12767   if (SizeExpr || !Size)
12768     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12769                                   IndexTypeQuals, BracketsRange,
12770                                   getDerived().getBaseEntity());
12771 
12772   QualType Types[] = {
12773     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12774     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12775     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12776   };
12777   const unsigned NumTypes = llvm::array_lengthof(Types);
12778   QualType SizeType;
12779   for (unsigned I = 0; I != NumTypes; ++I)
12780     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12781       SizeType = Types[I];
12782       break;
12783     }
12784 
12785   // Note that we can return a VariableArrayType here in the case where
12786   // the element type was a dependent VariableArrayType.
12787   IntegerLiteral *ArraySize
12788       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12789                                /*FIXME*/BracketsRange.getBegin());
12790   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12791                                 IndexTypeQuals, BracketsRange,
12792                                 getDerived().getBaseEntity());
12793 }
12794 
12795 template<typename Derived>
12796 QualType
12797 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12798                                                  ArrayType::ArraySizeModifier SizeMod,
12799                                                  const llvm::APInt &Size,
12800                                                  unsigned IndexTypeQuals,
12801                                                  SourceRange BracketsRange) {
12802   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
12803                                         IndexTypeQuals, BracketsRange);
12804 }
12805 
12806 template<typename Derived>
12807 QualType
12808 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12809                                           ArrayType::ArraySizeModifier SizeMod,
12810                                                  unsigned IndexTypeQuals,
12811                                                    SourceRange BracketsRange) {
12812   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12813                                        IndexTypeQuals, BracketsRange);
12814 }
12815 
12816 template<typename Derived>
12817 QualType
12818 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12819                                           ArrayType::ArraySizeModifier SizeMod,
12820                                                  Expr *SizeExpr,
12821                                                  unsigned IndexTypeQuals,
12822                                                  SourceRange BracketsRange) {
12823   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12824                                        SizeExpr,
12825                                        IndexTypeQuals, BracketsRange);
12826 }
12827 
12828 template<typename Derived>
12829 QualType
12830 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12831                                           ArrayType::ArraySizeModifier SizeMod,
12832                                                        Expr *SizeExpr,
12833                                                        unsigned IndexTypeQuals,
12834                                                    SourceRange BracketsRange) {
12835   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12836                                        SizeExpr,
12837                                        IndexTypeQuals, BracketsRange);
12838 }
12839 
12840 template <typename Derived>
12841 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
12842     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
12843   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
12844                                           AttributeLoc);
12845 }
12846 
12847 template <typename Derived>
12848 QualType
12849 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12850                                           unsigned NumElements,
12851                                           VectorType::VectorKind VecKind) {
12852   // FIXME: semantic checking!
12853   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12854 }
12855 
12856 template <typename Derived>
12857 QualType TreeTransform<Derived>::RebuildDependentVectorType(
12858     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
12859     VectorType::VectorKind VecKind) {
12860   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
12861 }
12862 
12863 template<typename Derived>
12864 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
12865                                                       unsigned NumElements,
12866                                                  SourceLocation AttributeLoc) {
12867   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
12868                           NumElements, true);
12869   IntegerLiteral *VectorSize
12870     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
12871                              AttributeLoc);
12872   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
12873 }
12874 
12875 template<typename Derived>
12876 QualType
12877 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
12878                                                            Expr *SizeExpr,
12879                                                   SourceLocation AttributeLoc) {
12880   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
12881 }
12882 
12883 template<typename Derived>
12884 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
12885     QualType T,
12886     MutableArrayRef<QualType> ParamTypes,
12887     const FunctionProtoType::ExtProtoInfo &EPI) {
12888   return SemaRef.BuildFunctionType(T, ParamTypes,
12889                                    getDerived().getBaseLocation(),
12890                                    getDerived().getBaseEntity(),
12891                                    EPI);
12892 }
12893 
12894 template<typename Derived>
12895 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
12896   return SemaRef.Context.getFunctionNoProtoType(T);
12897 }
12898 
12899 template<typename Derived>
12900 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
12901                                                             Decl *D) {
12902   assert(D && "no decl found");
12903   if (D->isInvalidDecl()) return QualType();
12904 
12905   // FIXME: Doesn't account for ObjCInterfaceDecl!
12906   TypeDecl *Ty;
12907   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
12908     // A valid resolved using typename pack expansion decl can have multiple
12909     // UsingDecls, but they must each have exactly one type, and it must be
12910     // the same type in every case. But we must have at least one expansion!
12911     if (UPD->expansions().empty()) {
12912       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
12913           << UPD->isCXXClassMember() << UPD;
12914       return QualType();
12915     }
12916 
12917     // We might still have some unresolved types. Try to pick a resolved type
12918     // if we can. The final instantiation will check that the remaining
12919     // unresolved types instantiate to the type we pick.
12920     QualType FallbackT;
12921     QualType T;
12922     for (auto *E : UPD->expansions()) {
12923       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
12924       if (ThisT.isNull())
12925         continue;
12926       else if (ThisT->getAs<UnresolvedUsingType>())
12927         FallbackT = ThisT;
12928       else if (T.isNull())
12929         T = ThisT;
12930       else
12931         assert(getSema().Context.hasSameType(ThisT, T) &&
12932                "mismatched resolved types in using pack expansion");
12933     }
12934     return T.isNull() ? FallbackT : T;
12935   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
12936     assert(Using->hasTypename() &&
12937            "UnresolvedUsingTypenameDecl transformed to non-typename using");
12938 
12939     // A valid resolved using typename decl points to exactly one type decl.
12940     assert(++Using->shadow_begin() == Using->shadow_end());
12941     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
12942   } else {
12943     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
12944            "UnresolvedUsingTypenameDecl transformed to non-using decl");
12945     Ty = cast<UnresolvedUsingTypenameDecl>(D);
12946   }
12947 
12948   return SemaRef.Context.getTypeDeclType(Ty);
12949 }
12950 
12951 template<typename Derived>
12952 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
12953                                                        SourceLocation Loc) {
12954   return SemaRef.BuildTypeofExprType(E, Loc);
12955 }
12956 
12957 template<typename Derived>
12958 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
12959   return SemaRef.Context.getTypeOfType(Underlying);
12960 }
12961 
12962 template<typename Derived>
12963 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
12964                                                      SourceLocation Loc) {
12965   return SemaRef.BuildDecltypeType(E, Loc);
12966 }
12967 
12968 template<typename Derived>
12969 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
12970                                             UnaryTransformType::UTTKind UKind,
12971                                             SourceLocation Loc) {
12972   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
12973 }
12974 
12975 template<typename Derived>
12976 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
12977                                                       TemplateName Template,
12978                                              SourceLocation TemplateNameLoc,
12979                                      TemplateArgumentListInfo &TemplateArgs) {
12980   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
12981 }
12982 
12983 template<typename Derived>
12984 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
12985                                                    SourceLocation KWLoc) {
12986   return SemaRef.BuildAtomicType(ValueType, KWLoc);
12987 }
12988 
12989 template<typename Derived>
12990 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
12991                                                  SourceLocation KWLoc,
12992                                                  bool isReadPipe) {
12993   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
12994                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
12995 }
12996 
12997 template<typename Derived>
12998 TemplateName
12999 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13000                                             bool TemplateKW,
13001                                             TemplateDecl *Template) {
13002   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13003                                                   Template);
13004 }
13005 
13006 template<typename Derived>
13007 TemplateName
13008 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13009                                             SourceLocation TemplateKWLoc,
13010                                             const IdentifierInfo &Name,
13011                                             SourceLocation NameLoc,
13012                                             QualType ObjectType,
13013                                             NamedDecl *FirstQualifierInScope,
13014                                             bool AllowInjectedClassName) {
13015   UnqualifiedId TemplateName;
13016   TemplateName.setIdentifier(&Name, NameLoc);
13017   Sema::TemplateTy Template;
13018   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13019                                        SS, TemplateKWLoc, TemplateName,
13020                                        ParsedType::make(ObjectType),
13021                                        /*EnteringContext=*/false,
13022                                        Template, AllowInjectedClassName);
13023   return Template.get();
13024 }
13025 
13026 template<typename Derived>
13027 TemplateName
13028 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13029                                             SourceLocation TemplateKWLoc,
13030                                             OverloadedOperatorKind Operator,
13031                                             SourceLocation NameLoc,
13032                                             QualType ObjectType,
13033                                             bool AllowInjectedClassName) {
13034   UnqualifiedId Name;
13035   // FIXME: Bogus location information.
13036   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13037   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13038   Sema::TemplateTy Template;
13039   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13040                                        SS, TemplateKWLoc, Name,
13041                                        ParsedType::make(ObjectType),
13042                                        /*EnteringContext=*/false,
13043                                        Template, AllowInjectedClassName);
13044   return Template.get();
13045 }
13046 
13047 template<typename Derived>
13048 ExprResult
13049 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13050                                                    SourceLocation OpLoc,
13051                                                    Expr *OrigCallee,
13052                                                    Expr *First,
13053                                                    Expr *Second) {
13054   Expr *Callee = OrigCallee->IgnoreParenCasts();
13055   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13056 
13057   if (First->getObjectKind() == OK_ObjCProperty) {
13058     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13059     if (BinaryOperator::isAssignmentOp(Opc))
13060       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13061                                                  First, Second);
13062     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13063     if (Result.isInvalid())
13064       return ExprError();
13065     First = Result.get();
13066   }
13067 
13068   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13069     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13070     if (Result.isInvalid())
13071       return ExprError();
13072     Second = Result.get();
13073   }
13074 
13075   // Determine whether this should be a builtin operation.
13076   if (Op == OO_Subscript) {
13077     if (!First->getType()->isOverloadableType() &&
13078         !Second->getType()->isOverloadableType())
13079       return getSema().CreateBuiltinArraySubscriptExpr(
13080           First, Callee->getBeginLoc(), Second, OpLoc);
13081   } else if (Op == OO_Arrow) {
13082     // -> is never a builtin operation.
13083     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13084   } else if (Second == nullptr || isPostIncDec) {
13085     if (!First->getType()->isOverloadableType() ||
13086         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13087       // The argument is not of overloadable type, or this is an expression
13088       // of the form &Class::member, so try to create a built-in unary
13089       // operation.
13090       UnaryOperatorKind Opc
13091         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13092 
13093       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13094     }
13095   } else {
13096     if (!First->getType()->isOverloadableType() &&
13097         !Second->getType()->isOverloadableType()) {
13098       // Neither of the arguments is an overloadable type, so try to
13099       // create a built-in binary operation.
13100       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13101       ExprResult Result
13102         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13103       if (Result.isInvalid())
13104         return ExprError();
13105 
13106       return Result;
13107     }
13108   }
13109 
13110   // Compute the transformed set of functions (and function templates) to be
13111   // used during overload resolution.
13112   UnresolvedSet<16> Functions;
13113   bool RequiresADL;
13114 
13115   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13116     Functions.append(ULE->decls_begin(), ULE->decls_end());
13117     // If the overload could not be resolved in the template definition
13118     // (because we had a dependent argument), ADL is performed as part of
13119     // template instantiation.
13120     RequiresADL = ULE->requiresADL();
13121   } else {
13122     // If we've resolved this to a particular non-member function, just call
13123     // that function. If we resolved it to a member function,
13124     // CreateOverloaded* will find that function for us.
13125     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13126     if (!isa<CXXMethodDecl>(ND))
13127       Functions.addDecl(ND);
13128     RequiresADL = false;
13129   }
13130 
13131   // Add any functions found via argument-dependent lookup.
13132   Expr *Args[2] = { First, Second };
13133   unsigned NumArgs = 1 + (Second != nullptr);
13134 
13135   // Create the overloaded operator invocation for unary operators.
13136   if (NumArgs == 1 || isPostIncDec) {
13137     UnaryOperatorKind Opc
13138       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13139     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13140                                            RequiresADL);
13141   }
13142 
13143   if (Op == OO_Subscript) {
13144     SourceLocation LBrace;
13145     SourceLocation RBrace;
13146 
13147     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13148         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13149         LBrace = SourceLocation::getFromRawEncoding(
13150                     NameLoc.CXXOperatorName.BeginOpNameLoc);
13151         RBrace = SourceLocation::getFromRawEncoding(
13152                     NameLoc.CXXOperatorName.EndOpNameLoc);
13153     } else {
13154       LBrace = Callee->getBeginLoc();
13155       RBrace = OpLoc;
13156     }
13157 
13158     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13159                                                       First, Second);
13160   }
13161 
13162   // Create the overloaded operator invocation for binary operators.
13163   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13164   ExprResult Result = SemaRef.CreateOverloadedBinOp(
13165       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13166   if (Result.isInvalid())
13167     return ExprError();
13168 
13169   return Result;
13170 }
13171 
13172 template<typename Derived>
13173 ExprResult
13174 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13175                                                      SourceLocation OperatorLoc,
13176                                                        bool isArrow,
13177                                                        CXXScopeSpec &SS,
13178                                                      TypeSourceInfo *ScopeType,
13179                                                        SourceLocation CCLoc,
13180                                                        SourceLocation TildeLoc,
13181                                         PseudoDestructorTypeStorage Destroyed) {
13182   QualType BaseType = Base->getType();
13183   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13184       (!isArrow && !BaseType->getAs<RecordType>()) ||
13185       (isArrow && BaseType->getAs<PointerType>() &&
13186        !BaseType->getAs<PointerType>()->getPointeeType()
13187                                               ->template getAs<RecordType>())){
13188     // This pseudo-destructor expression is still a pseudo-destructor.
13189     return SemaRef.BuildPseudoDestructorExpr(
13190         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13191         CCLoc, TildeLoc, Destroyed);
13192   }
13193 
13194   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13195   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13196                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13197   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13198   NameInfo.setNamedTypeInfo(DestroyedType);
13199 
13200   // The scope type is now known to be a valid nested name specifier
13201   // component. Tack it on to the end of the nested name specifier.
13202   if (ScopeType) {
13203     if (!ScopeType->getType()->getAs<TagType>()) {
13204       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13205                      diag::err_expected_class_or_namespace)
13206           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13207       return ExprError();
13208     }
13209     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13210               CCLoc);
13211   }
13212 
13213   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13214   return getSema().BuildMemberReferenceExpr(Base, BaseType,
13215                                             OperatorLoc, isArrow,
13216                                             SS, TemplateKWLoc,
13217                                             /*FIXME: FirstQualifier*/ nullptr,
13218                                             NameInfo,
13219                                             /*TemplateArgs*/ nullptr,
13220                                             /*S*/nullptr);
13221 }
13222 
13223 template<typename Derived>
13224 StmtResult
13225 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13226   SourceLocation Loc = S->getBeginLoc();
13227   CapturedDecl *CD = S->getCapturedDecl();
13228   unsigned NumParams = CD->getNumParams();
13229   unsigned ContextParamPos = CD->getContextParamPosition();
13230   SmallVector<Sema::CapturedParamNameType, 4> Params;
13231   for (unsigned I = 0; I < NumParams; ++I) {
13232     if (I != ContextParamPos) {
13233       Params.push_back(
13234              std::make_pair(
13235                   CD->getParam(I)->getName(),
13236                   getDerived().TransformType(CD->getParam(I)->getType())));
13237     } else {
13238       Params.push_back(std::make_pair(StringRef(), QualType()));
13239     }
13240   }
13241   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13242                                      S->getCapturedRegionKind(), Params);
13243   StmtResult Body;
13244   {
13245     Sema::CompoundScopeRAII CompoundScope(getSema());
13246     Body = getDerived().TransformStmt(S->getCapturedStmt());
13247   }
13248 
13249   if (Body.isInvalid()) {
13250     getSema().ActOnCapturedRegionError();
13251     return StmtError();
13252   }
13253 
13254   return getSema().ActOnCapturedRegionEnd(Body.get());
13255 }
13256 
13257 } // end namespace clang
13258 
13259 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
13260