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