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