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 using namespace llvm::omp;
41 
42 namespace clang {
43 using namespace sema;
44 
45 /// A semantic tree transformation that allows one to transform one
46 /// abstract syntax tree into another.
47 ///
48 /// A new tree transformation is defined by creating a new subclass \c X of
49 /// \c TreeTransform<X> and then overriding certain operations to provide
50 /// behavior specific to that transformation. For example, template
51 /// instantiation is implemented as a tree transformation where the
52 /// transformation of TemplateTypeParmType nodes involves substituting the
53 /// template arguments for their corresponding template parameters; a similar
54 /// transformation is performed for non-type template parameters and
55 /// template template parameters.
56 ///
57 /// This tree-transformation template uses static polymorphism to allow
58 /// subclasses to customize any of its operations. Thus, a subclass can
59 /// override any of the transformation or rebuild operators by providing an
60 /// operation with the same signature as the default implementation. The
61 /// overriding function should not be virtual.
62 ///
63 /// Semantic tree transformations are split into two stages, either of which
64 /// can be replaced by a subclass. The "transform" step transforms an AST node
65 /// or the parts of an AST node using the various transformation functions,
66 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
67 /// node of the appropriate kind from the pieces. The default transformation
68 /// routines recursively transform the operands to composite AST nodes (e.g.,
69 /// the pointee type of a PointerType node) and, if any of those operand nodes
70 /// were changed by the transformation, invokes the rebuild operation to create
71 /// a new AST node.
72 ///
73 /// Subclasses can customize the transformation at various levels. The
74 /// most coarse-grained transformations involve replacing TransformType(),
75 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
76 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
77 /// new implementations.
78 ///
79 /// For more fine-grained transformations, subclasses can replace any of the
80 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
81 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
82 /// replacing TransformTemplateTypeParmType() allows template instantiation
83 /// to substitute template arguments for their corresponding template
84 /// parameters. Additionally, subclasses can override the \c RebuildXXX
85 /// functions to control how AST nodes are rebuilt when their operands change.
86 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
87 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
88 /// be able to use more efficient rebuild steps.
89 ///
90 /// There are a handful of other functions that can be overridden, allowing one
91 /// to avoid traversing nodes that don't need any transformation
92 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
93 /// operands have not changed (\c AlwaysRebuild()), and customize the
94 /// default locations and entity names used for type-checking
95 /// (\c getBaseLocation(), \c getBaseEntity()).
96 template<typename Derived>
97 class TreeTransform {
98   /// Private RAII object that helps us forget and then re-remember
99   /// the template argument corresponding to a partially-substituted parameter
100   /// pack.
101   class ForgetPartiallySubstitutedPackRAII {
102     Derived &Self;
103     TemplateArgument Old;
104 
105   public:
106     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
107       Old = Self.ForgetPartiallySubstitutedPack();
108     }
109 
110     ~ForgetPartiallySubstitutedPackRAII() {
111       Self.RememberPartiallySubstitutedPack(Old);
112     }
113   };
114 
115 protected:
116   Sema &SemaRef;
117 
118   /// The set of local declarations that have been transformed, for
119   /// cases where we are forced to build new declarations within the transformer
120   /// rather than in the subclass (e.g., lambda closure types).
121   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
122 
123 public:
124   /// Initializes a new tree transformer.
125   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
126 
127   /// Retrieves a reference to the derived class.
128   Derived &getDerived() { return static_cast<Derived&>(*this); }
129 
130   /// Retrieves a reference to the derived class.
131   const Derived &getDerived() const {
132     return static_cast<const Derived&>(*this);
133   }
134 
135   static inline ExprResult Owned(Expr *E) { return E; }
136   static inline StmtResult Owned(Stmt *S) { return S; }
137 
138   /// Retrieves a reference to the semantic analysis object used for
139   /// this tree transform.
140   Sema &getSema() const { return SemaRef; }
141 
142   /// Whether the transformation should always rebuild AST nodes, even
143   /// if none of the children have changed.
144   ///
145   /// Subclasses may override this function to specify when the transformation
146   /// should rebuild all AST nodes.
147   ///
148   /// We must always rebuild all AST nodes when performing variadic template
149   /// pack expansion, in order to avoid violating the AST invariant that each
150   /// statement node appears at most once in its containing declaration.
151   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
152 
153   /// Whether the transformation is forming an expression or statement that
154   /// replaces the original. In this case, we'll reuse mangling numbers from
155   /// existing lambdas.
156   bool ReplacingOriginal() { return false; }
157 
158   /// Returns the location of the entity being transformed, if that
159   /// information was not available elsewhere in the AST.
160   ///
161   /// By default, returns no source-location information. Subclasses can
162   /// provide an alternative implementation that provides better location
163   /// information.
164   SourceLocation getBaseLocation() { return SourceLocation(); }
165 
166   /// Returns the name of the entity being transformed, if that
167   /// information was not available elsewhere in the AST.
168   ///
169   /// By default, returns an empty name. Subclasses can provide an alternative
170   /// implementation with a more precise name.
171   DeclarationName getBaseEntity() { return DeclarationName(); }
172 
173   /// Sets the "base" location and entity when that
174   /// information is known based on another transformation.
175   ///
176   /// By default, the source location and entity are ignored. Subclasses can
177   /// override this function to provide a customized implementation.
178   void setBase(SourceLocation Loc, DeclarationName Entity) { }
179 
180   /// RAII object that temporarily sets the base location and entity
181   /// used for reporting diagnostics in types.
182   class TemporaryBase {
183     TreeTransform &Self;
184     SourceLocation OldLocation;
185     DeclarationName OldEntity;
186 
187   public:
188     TemporaryBase(TreeTransform &Self, SourceLocation Location,
189                   DeclarationName Entity) : Self(Self) {
190       OldLocation = Self.getDerived().getBaseLocation();
191       OldEntity = Self.getDerived().getBaseEntity();
192 
193       if (Location.isValid())
194         Self.getDerived().setBase(Location, Entity);
195     }
196 
197     ~TemporaryBase() {
198       Self.getDerived().setBase(OldLocation, OldEntity);
199     }
200   };
201 
202   /// Determine whether the given type \p T has already been
203   /// transformed.
204   ///
205   /// Subclasses can provide an alternative implementation of this routine
206   /// to short-circuit evaluation when it is known that a given type will
207   /// not change. For example, template instantiation need not traverse
208   /// non-dependent types.
209   bool AlreadyTransformed(QualType T) {
210     return T.isNull();
211   }
212 
213   /// Determine whether the given call argument should be dropped, e.g.,
214   /// because it is a default argument.
215   ///
216   /// Subclasses can provide an alternative implementation of this routine to
217   /// determine which kinds of call arguments get dropped. By default,
218   /// CXXDefaultArgument nodes are dropped (prior to transformation).
219   bool DropCallArgument(Expr *E) {
220     return E->isDefaultArgument();
221   }
222 
223   /// Determine whether we should expand a pack expansion with the
224   /// given set of parameter packs into separate arguments by repeatedly
225   /// transforming the pattern.
226   ///
227   /// By default, the transformer never tries to expand pack expansions.
228   /// Subclasses can override this routine to provide different behavior.
229   ///
230   /// \param EllipsisLoc The location of the ellipsis that identifies the
231   /// pack expansion.
232   ///
233   /// \param PatternRange The source range that covers the entire pattern of
234   /// the pack expansion.
235   ///
236   /// \param Unexpanded The set of unexpanded parameter packs within the
237   /// pattern.
238   ///
239   /// \param ShouldExpand Will be set to \c true if the transformer should
240   /// expand the corresponding pack expansions into separate arguments. When
241   /// set, \c NumExpansions must also be set.
242   ///
243   /// \param RetainExpansion Whether the caller should add an unexpanded
244   /// pack expansion after all of the expanded arguments. This is used
245   /// when extending explicitly-specified template argument packs per
246   /// C++0x [temp.arg.explicit]p9.
247   ///
248   /// \param NumExpansions The number of separate arguments that will be in
249   /// the expanded form of the corresponding pack expansion. This is both an
250   /// input and an output parameter, which can be set by the caller if the
251   /// number of expansions is known a priori (e.g., due to a prior substitution)
252   /// and will be set by the callee when the number of expansions is known.
253   /// The callee must set this value when \c ShouldExpand is \c true; it may
254   /// set this value in other cases.
255   ///
256   /// \returns true if an error occurred (e.g., because the parameter packs
257   /// are to be instantiated with arguments of different lengths), false
258   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
259   /// must be set.
260   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
261                                SourceRange PatternRange,
262                                ArrayRef<UnexpandedParameterPack> Unexpanded,
263                                bool &ShouldExpand,
264                                bool &RetainExpansion,
265                                Optional<unsigned> &NumExpansions) {
266     ShouldExpand = false;
267     return false;
268   }
269 
270   /// "Forget" about the partially-substituted pack template argument,
271   /// when performing an instantiation that must preserve the parameter pack
272   /// use.
273   ///
274   /// This routine is meant to be overridden by the template instantiator.
275   TemplateArgument ForgetPartiallySubstitutedPack() {
276     return TemplateArgument();
277   }
278 
279   /// "Remember" the partially-substituted pack template argument
280   /// after performing an instantiation that must preserve the parameter pack
281   /// use.
282   ///
283   /// This routine is meant to be overridden by the template instantiator.
284   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
285 
286   /// Note to the derived class when a function parameter pack is
287   /// being expanded.
288   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
289 
290   /// Transforms the given type into another type.
291   ///
292   /// By default, this routine transforms a type by creating a
293   /// TypeSourceInfo for it and delegating to the appropriate
294   /// function.  This is expensive, but we don't mind, because
295   /// this method is deprecated anyway;  all users should be
296   /// switched to storing TypeSourceInfos.
297   ///
298   /// \returns the transformed type.
299   QualType TransformType(QualType T);
300 
301   /// Transforms the given type-with-location into a new
302   /// type-with-location.
303   ///
304   /// By default, this routine transforms a type by delegating to the
305   /// appropriate TransformXXXType to build a new type.  Subclasses
306   /// may override this function (to take over all type
307   /// transformations) or some set of the TransformXXXType functions
308   /// to alter the transformation.
309   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
310 
311   /// Transform the given type-with-location into a new
312   /// type, collecting location information in the given builder
313   /// as necessary.
314   ///
315   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
316 
317   /// Transform a type that is permitted to produce a
318   /// DeducedTemplateSpecializationType.
319   ///
320   /// This is used in the (relatively rare) contexts where it is acceptable
321   /// for transformation to produce a class template type with deduced
322   /// template arguments.
323   /// @{
324   QualType TransformTypeWithDeducedTST(QualType T);
325   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
326   /// @}
327 
328   /// The reason why the value of a statement is not discarded, if any.
329   enum StmtDiscardKind {
330     SDK_Discarded,
331     SDK_NotDiscarded,
332     SDK_StmtExprResult,
333   };
334 
335   /// Transform the given statement.
336   ///
337   /// By default, this routine transforms a statement by delegating to the
338   /// appropriate TransformXXXStmt function to transform a specific kind of
339   /// statement or the TransformExpr() function to transform an expression.
340   /// Subclasses may override this function to transform statements using some
341   /// other mechanism.
342   ///
343   /// \returns the transformed statement.
344   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
345 
346   /// Transform the given statement.
347   ///
348   /// By default, this routine transforms a statement by delegating to the
349   /// appropriate TransformOMPXXXClause function to transform a specific kind
350   /// of clause. Subclasses may override this function to transform statements
351   /// using some other mechanism.
352   ///
353   /// \returns the transformed OpenMP clause.
354   OMPClause *TransformOMPClause(OMPClause *S);
355 
356   /// Transform the given attribute.
357   ///
358   /// By default, this routine transforms a statement by delegating to the
359   /// appropriate TransformXXXAttr function to transform a specific kind
360   /// of attribute. Subclasses may override this function to transform
361   /// attributed statements using some other mechanism.
362   ///
363   /// \returns the transformed attribute
364   const Attr *TransformAttr(const Attr *S);
365 
366 /// Transform the specified attribute.
367 ///
368 /// Subclasses should override the transformation of attributes with a pragma
369 /// spelling to transform expressions stored within the attribute.
370 ///
371 /// \returns the transformed attribute.
372 #define ATTR(X)
373 #define PRAGMA_SPELLING_ATTR(X)                                                \
374   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
375 #include "clang/Basic/AttrList.inc"
376 
377   /// Transform the given expression.
378   ///
379   /// By default, this routine transforms an expression by delegating to the
380   /// appropriate TransformXXXExpr function to build a new expression.
381   /// Subclasses may override this function to transform expressions using some
382   /// other mechanism.
383   ///
384   /// \returns the transformed expression.
385   ExprResult TransformExpr(Expr *E);
386 
387   /// Transform the given initializer.
388   ///
389   /// By default, this routine transforms an initializer by stripping off the
390   /// semantic nodes added by initialization, then passing the result to
391   /// TransformExpr or TransformExprs.
392   ///
393   /// \returns the transformed initializer.
394   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
395 
396   /// Transform the given list of expressions.
397   ///
398   /// This routine transforms a list of expressions by invoking
399   /// \c TransformExpr() for each subexpression. However, it also provides
400   /// support for variadic templates by expanding any pack expansions (if the
401   /// derived class permits such expansion) along the way. When pack expansions
402   /// are present, the number of outputs may not equal the number of inputs.
403   ///
404   /// \param Inputs The set of expressions to be transformed.
405   ///
406   /// \param NumInputs The number of expressions in \c Inputs.
407   ///
408   /// \param IsCall If \c true, then this transform is being performed on
409   /// function-call arguments, and any arguments that should be dropped, will
410   /// be.
411   ///
412   /// \param Outputs The transformed input expressions will be added to this
413   /// vector.
414   ///
415   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
416   /// due to transformation.
417   ///
418   /// \returns true if an error occurred, false otherwise.
419   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
420                       SmallVectorImpl<Expr *> &Outputs,
421                       bool *ArgChanged = nullptr);
422 
423   /// Transform the given declaration, which is referenced from a type
424   /// or expression.
425   ///
426   /// By default, acts as the identity function on declarations, unless the
427   /// transformer has had to transform the declaration itself. Subclasses
428   /// may override this function to provide alternate behavior.
429   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
430     llvm::DenseMap<Decl *, Decl *>::iterator Known
431       = TransformedLocalDecls.find(D);
432     if (Known != TransformedLocalDecls.end())
433       return Known->second;
434 
435     return D;
436   }
437 
438   /// Transform the specified condition.
439   ///
440   /// By default, this transforms the variable and expression and rebuilds
441   /// the condition.
442   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
443                                            Expr *Expr,
444                                            Sema::ConditionKind Kind);
445 
446   /// Transform the attributes associated with the given declaration and
447   /// place them on the new declaration.
448   ///
449   /// By default, this operation does nothing. Subclasses may override this
450   /// behavior to transform attributes.
451   void transformAttrs(Decl *Old, Decl *New) { }
452 
453   /// Note that a local declaration has been transformed by this
454   /// transformer.
455   ///
456   /// Local declarations are typically transformed via a call to
457   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
458   /// the transformer itself has to transform the declarations. This routine
459   /// can be overridden by a subclass that keeps track of such mappings.
460   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
461     assert(New.size() == 1 &&
462            "must override transformedLocalDecl if performing pack expansion");
463     TransformedLocalDecls[Old] = New.front();
464   }
465 
466   /// Transform the definition of the given declaration.
467   ///
468   /// By default, invokes TransformDecl() to transform the declaration.
469   /// Subclasses may override this function to provide alternate behavior.
470   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
471     return getDerived().TransformDecl(Loc, D);
472   }
473 
474   /// Transform the given declaration, which was the first part of a
475   /// nested-name-specifier in a member access expression.
476   ///
477   /// This specific declaration transformation only applies to the first
478   /// identifier in a nested-name-specifier of a member access expression, e.g.,
479   /// the \c T in \c x->T::member
480   ///
481   /// By default, invokes TransformDecl() to transform the declaration.
482   /// Subclasses may override this function to provide alternate behavior.
483   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
484     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
485   }
486 
487   /// Transform the set of declarations in an OverloadExpr.
488   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
489                                   LookupResult &R);
490 
491   /// Transform the given nested-name-specifier with source-location
492   /// information.
493   ///
494   /// By default, transforms all of the types and declarations within the
495   /// nested-name-specifier. Subclasses may override this function to provide
496   /// alternate behavior.
497   NestedNameSpecifierLoc
498   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
499                                   QualType ObjectType = QualType(),
500                                   NamedDecl *FirstQualifierInScope = nullptr);
501 
502   /// Transform the given declaration name.
503   ///
504   /// By default, transforms the types of conversion function, constructor,
505   /// and destructor names and then (if needed) rebuilds the declaration name.
506   /// Identifiers and selectors are returned unmodified. Sublcasses may
507   /// override this function to provide alternate behavior.
508   DeclarationNameInfo
509   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
510 
511   /// Transform the given template name.
512   ///
513   /// \param SS The nested-name-specifier that qualifies the template
514   /// name. This nested-name-specifier must already have been transformed.
515   ///
516   /// \param Name The template name to transform.
517   ///
518   /// \param NameLoc The source location of the template name.
519   ///
520   /// \param ObjectType If we're translating a template name within a member
521   /// access expression, this is the type of the object whose member template
522   /// is being referenced.
523   ///
524   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
525   /// also refers to a name within the current (lexical) scope, this is the
526   /// declaration it refers to.
527   ///
528   /// By default, transforms the template name by transforming the declarations
529   /// and nested-name-specifiers that occur within the template name.
530   /// Subclasses may override this function to provide alternate behavior.
531   TemplateName
532   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
533                         SourceLocation NameLoc,
534                         QualType ObjectType = QualType(),
535                         NamedDecl *FirstQualifierInScope = nullptr,
536                         bool AllowInjectedClassName = false);
537 
538   /// Transform the given template argument.
539   ///
540   /// By default, this operation transforms the type, expression, or
541   /// declaration stored within the template argument and constructs a
542   /// new template argument from the transformed result. Subclasses may
543   /// override this function to provide alternate behavior.
544   ///
545   /// Returns true if there was an error.
546   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
547                                  TemplateArgumentLoc &Output,
548                                  bool Uneval = false);
549 
550   /// Transform the given set of template arguments.
551   ///
552   /// By default, this operation transforms all of the template arguments
553   /// in the input set using \c TransformTemplateArgument(), and appends
554   /// the transformed arguments to the output list.
555   ///
556   /// Note that this overload of \c TransformTemplateArguments() is merely
557   /// a convenience function. Subclasses that wish to override this behavior
558   /// should override the iterator-based member template version.
559   ///
560   /// \param Inputs The set of template arguments to be transformed.
561   ///
562   /// \param NumInputs The number of template arguments in \p Inputs.
563   ///
564   /// \param Outputs The set of transformed template arguments output by this
565   /// routine.
566   ///
567   /// Returns true if an error occurred.
568   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
569                                   unsigned NumInputs,
570                                   TemplateArgumentListInfo &Outputs,
571                                   bool Uneval = false) {
572     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
573                                       Uneval);
574   }
575 
576   /// Transform the given set of template arguments.
577   ///
578   /// By default, this operation transforms all of the template arguments
579   /// in the input set using \c TransformTemplateArgument(), and appends
580   /// the transformed arguments to the output list.
581   ///
582   /// \param First An iterator to the first template argument.
583   ///
584   /// \param Last An iterator one step past the last template argument.
585   ///
586   /// \param Outputs The set of transformed template arguments output by this
587   /// routine.
588   ///
589   /// Returns true if an error occurred.
590   template<typename InputIterator>
591   bool TransformTemplateArguments(InputIterator First,
592                                   InputIterator Last,
593                                   TemplateArgumentListInfo &Outputs,
594                                   bool Uneval = false);
595 
596   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
597   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
598                                  TemplateArgumentLoc &ArgLoc);
599 
600   /// Fakes up a TypeSourceInfo for a type.
601   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
602     return SemaRef.Context.getTrivialTypeSourceInfo(T,
603                        getDerived().getBaseLocation());
604   }
605 
606 #define ABSTRACT_TYPELOC(CLASS, PARENT)
607 #define TYPELOC(CLASS, PARENT)                                   \
608   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
609 #include "clang/AST/TypeLocNodes.def"
610 
611   template<typename Fn>
612   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
613                                       FunctionProtoTypeLoc TL,
614                                       CXXRecordDecl *ThisContext,
615                                       Qualifiers ThisTypeQuals,
616                                       Fn TransformExceptionSpec);
617 
618   bool TransformExceptionSpec(SourceLocation Loc,
619                               FunctionProtoType::ExceptionSpecInfo &ESI,
620                               SmallVectorImpl<QualType> &Exceptions,
621                               bool &Changed);
622 
623   StmtResult TransformSEHHandler(Stmt *Handler);
624 
625   QualType
626   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
627                                       TemplateSpecializationTypeLoc TL,
628                                       TemplateName Template);
629 
630   QualType
631   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
632                                       DependentTemplateSpecializationTypeLoc TL,
633                                                TemplateName Template,
634                                                CXXScopeSpec &SS);
635 
636   QualType TransformDependentTemplateSpecializationType(
637       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
638       NestedNameSpecifierLoc QualifierLoc);
639 
640   /// Transforms the parameters of a function type into the
641   /// given vectors.
642   ///
643   /// The result vectors should be kept in sync; null entries in the
644   /// variables vector are acceptable.
645   ///
646   /// Return true on error.
647   bool TransformFunctionTypeParams(
648       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
649       const QualType *ParamTypes,
650       const FunctionProtoType::ExtParameterInfo *ParamInfos,
651       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
652       Sema::ExtParameterInfoBuilder &PInfos);
653 
654   /// Transforms a single function-type parameter.  Return null
655   /// on error.
656   ///
657   /// \param indexAdjustment - A number to add to the parameter's
658   ///   scope index;  can be negative
659   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
660                                           int indexAdjustment,
661                                           Optional<unsigned> NumExpansions,
662                                           bool ExpectParameterPack);
663 
664   /// Transform the body of a lambda-expression.
665   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
666   /// Alternative implementation of TransformLambdaBody that skips transforming
667   /// the body.
668   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
669 
670   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
671 
672   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
673   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
674 
675   TemplateParameterList *TransformTemplateParameterList(
676         TemplateParameterList *TPL) {
677     return TPL;
678   }
679 
680   ExprResult TransformAddressOfOperand(Expr *E);
681 
682   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
683                                                 bool IsAddressOfOperand,
684                                                 TypeSourceInfo **RecoveryTSI);
685 
686   ExprResult TransformParenDependentScopeDeclRefExpr(
687       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
688       TypeSourceInfo **RecoveryTSI);
689 
690   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
691 
692 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
693 // amount of stack usage with clang.
694 #define STMT(Node, Parent)                        \
695   LLVM_ATTRIBUTE_NOINLINE \
696   StmtResult Transform##Node(Node *S);
697 #define VALUESTMT(Node, Parent)                   \
698   LLVM_ATTRIBUTE_NOINLINE \
699   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
700 #define EXPR(Node, Parent)                        \
701   LLVM_ATTRIBUTE_NOINLINE \
702   ExprResult Transform##Node(Node *E);
703 #define ABSTRACT_STMT(Stmt)
704 #include "clang/AST/StmtNodes.inc"
705 
706 #define OPENMP_CLAUSE(Name, Class)                        \
707   LLVM_ATTRIBUTE_NOINLINE \
708   OMPClause *Transform ## Class(Class *S);
709 #include "clang/Basic/OpenMPKinds.def"
710 
711   /// Build a new qualified type given its unqualified type and type location.
712   ///
713   /// By default, this routine adds type qualifiers only to types that can
714   /// have qualifiers, and silently suppresses those qualifiers that are not
715   /// permitted. Subclasses may override this routine to provide different
716   /// behavior.
717   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
718 
719   /// Build a new pointer type given its pointee type.
720   ///
721   /// By default, performs semantic analysis when building the pointer type.
722   /// Subclasses may override this routine to provide different behavior.
723   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
724 
725   /// Build a new block pointer type given its pointee type.
726   ///
727   /// By default, performs semantic analysis when building the block pointer
728   /// type. Subclasses may override this routine to provide different behavior.
729   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
730 
731   /// Build a new reference type given the type it references.
732   ///
733   /// By default, performs semantic analysis when building the
734   /// reference type. Subclasses may override this routine to provide
735   /// different behavior.
736   ///
737   /// \param LValue whether the type was written with an lvalue sigil
738   /// or an rvalue sigil.
739   QualType RebuildReferenceType(QualType ReferentType,
740                                 bool LValue,
741                                 SourceLocation Sigil);
742 
743   /// Build a new member pointer type given the pointee type and the
744   /// class type it refers into.
745   ///
746   /// By default, performs semantic analysis when building the member pointer
747   /// type. Subclasses may override this routine to provide different behavior.
748   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
749                                     SourceLocation Sigil);
750 
751   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
752                                     SourceLocation ProtocolLAngleLoc,
753                                     ArrayRef<ObjCProtocolDecl *> Protocols,
754                                     ArrayRef<SourceLocation> ProtocolLocs,
755                                     SourceLocation ProtocolRAngleLoc);
756 
757   /// Build an Objective-C object type.
758   ///
759   /// By default, performs semantic analysis when building the object type.
760   /// Subclasses may override this routine to provide different behavior.
761   QualType RebuildObjCObjectType(QualType BaseType,
762                                  SourceLocation Loc,
763                                  SourceLocation TypeArgsLAngleLoc,
764                                  ArrayRef<TypeSourceInfo *> TypeArgs,
765                                  SourceLocation TypeArgsRAngleLoc,
766                                  SourceLocation ProtocolLAngleLoc,
767                                  ArrayRef<ObjCProtocolDecl *> Protocols,
768                                  ArrayRef<SourceLocation> ProtocolLocs,
769                                  SourceLocation ProtocolRAngleLoc);
770 
771   /// Build a new Objective-C object pointer type given the pointee type.
772   ///
773   /// By default, directly builds the pointer type, with no additional semantic
774   /// analysis.
775   QualType RebuildObjCObjectPointerType(QualType PointeeType,
776                                         SourceLocation Star);
777 
778   /// Build a new array type given the element type, size
779   /// modifier, size of the array (if known), size expression, and index type
780   /// qualifiers.
781   ///
782   /// By default, performs semantic analysis when building the array type.
783   /// Subclasses may override this routine to provide different behavior.
784   /// Also by default, all of the other Rebuild*Array
785   QualType RebuildArrayType(QualType ElementType,
786                             ArrayType::ArraySizeModifier SizeMod,
787                             const llvm::APInt *Size,
788                             Expr *SizeExpr,
789                             unsigned IndexTypeQuals,
790                             SourceRange BracketsRange);
791 
792   /// Build a new constant array type given the element type, size
793   /// modifier, (known) size of the array, and index type qualifiers.
794   ///
795   /// By default, performs semantic analysis when building the array type.
796   /// Subclasses may override this routine to provide different behavior.
797   QualType RebuildConstantArrayType(QualType ElementType,
798                                     ArrayType::ArraySizeModifier SizeMod,
799                                     const llvm::APInt &Size,
800                                     Expr *SizeExpr,
801                                     unsigned IndexTypeQuals,
802                                     SourceRange BracketsRange);
803 
804   /// Build a new incomplete array type given the element type, size
805   /// modifier, and index type qualifiers.
806   ///
807   /// By default, performs semantic analysis when building the array type.
808   /// Subclasses may override this routine to provide different behavior.
809   QualType RebuildIncompleteArrayType(QualType ElementType,
810                                       ArrayType::ArraySizeModifier SizeMod,
811                                       unsigned IndexTypeQuals,
812                                       SourceRange BracketsRange);
813 
814   /// Build a new variable-length array type given the element type,
815   /// size modifier, size expression, and index type qualifiers.
816   ///
817   /// By default, performs semantic analysis when building the array type.
818   /// Subclasses may override this routine to provide different behavior.
819   QualType RebuildVariableArrayType(QualType ElementType,
820                                     ArrayType::ArraySizeModifier SizeMod,
821                                     Expr *SizeExpr,
822                                     unsigned IndexTypeQuals,
823                                     SourceRange BracketsRange);
824 
825   /// Build a new dependent-sized array type given the element type,
826   /// size modifier, size expression, and index type qualifiers.
827   ///
828   /// By default, performs semantic analysis when building the array type.
829   /// Subclasses may override this routine to provide different behavior.
830   QualType RebuildDependentSizedArrayType(QualType ElementType,
831                                           ArrayType::ArraySizeModifier SizeMod,
832                                           Expr *SizeExpr,
833                                           unsigned IndexTypeQuals,
834                                           SourceRange BracketsRange);
835 
836   /// Build a new vector type given the element type and
837   /// number of elements.
838   ///
839   /// By default, performs semantic analysis when building the vector type.
840   /// Subclasses may override this routine to provide different behavior.
841   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
842                              VectorType::VectorKind VecKind);
843 
844   /// Build a new potentially dependently-sized extended vector type
845   /// given the element type and number of elements.
846   ///
847   /// By default, performs semantic analysis when building the vector type.
848   /// Subclasses may override this routine to provide different behavior.
849   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
850                                            SourceLocation AttributeLoc,
851                                            VectorType::VectorKind);
852 
853   /// Build a new extended vector type given the element type and
854   /// number of elements.
855   ///
856   /// By default, performs semantic analysis when building the vector type.
857   /// Subclasses may override this routine to provide different behavior.
858   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
859                                 SourceLocation AttributeLoc);
860 
861   /// Build a new potentially dependently-sized extended vector type
862   /// given the element type and number of elements.
863   ///
864   /// By default, performs semantic analysis when building the vector type.
865   /// Subclasses may override this routine to provide different behavior.
866   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
867                                               Expr *SizeExpr,
868                                               SourceLocation AttributeLoc);
869 
870   /// Build a new DependentAddressSpaceType or return the pointee
871   /// type variable with the correct address space (retrieved from
872   /// AddrSpaceExpr) applied to it. The former will be returned in cases
873   /// where the address space remains dependent.
874   ///
875   /// By default, performs semantic analysis when building the type with address
876   /// space applied. Subclasses may override this routine to provide different
877   /// behavior.
878   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
879                                             Expr *AddrSpaceExpr,
880                                             SourceLocation AttributeLoc);
881 
882   /// Build a new function type.
883   ///
884   /// By default, performs semantic analysis when building the function type.
885   /// Subclasses may override this routine to provide different behavior.
886   QualType RebuildFunctionProtoType(QualType T,
887                                     MutableArrayRef<QualType> ParamTypes,
888                                     const FunctionProtoType::ExtProtoInfo &EPI);
889 
890   /// Build a new unprototyped function type.
891   QualType RebuildFunctionNoProtoType(QualType ResultType);
892 
893   /// Rebuild an unresolved typename type, given the decl that
894   /// the UnresolvedUsingTypenameDecl was transformed to.
895   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
896 
897   /// Build a new typedef type.
898   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
899     return SemaRef.Context.getTypeDeclType(Typedef);
900   }
901 
902   /// Build a new MacroDefined type.
903   QualType RebuildMacroQualifiedType(QualType T,
904                                      const IdentifierInfo *MacroII) {
905     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
906   }
907 
908   /// Build a new class/struct/union type.
909   QualType RebuildRecordType(RecordDecl *Record) {
910     return SemaRef.Context.getTypeDeclType(Record);
911   }
912 
913   /// Build a new Enum type.
914   QualType RebuildEnumType(EnumDecl *Enum) {
915     return SemaRef.Context.getTypeDeclType(Enum);
916   }
917 
918   /// Build a new typeof(expr) type.
919   ///
920   /// By default, performs semantic analysis when building the typeof type.
921   /// Subclasses may override this routine to provide different behavior.
922   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
923 
924   /// Build a new typeof(type) type.
925   ///
926   /// By default, builds a new TypeOfType with the given underlying type.
927   QualType RebuildTypeOfType(QualType Underlying);
928 
929   /// Build a new unary transform type.
930   QualType RebuildUnaryTransformType(QualType BaseType,
931                                      UnaryTransformType::UTTKind UKind,
932                                      SourceLocation Loc);
933 
934   /// Build a new C++11 decltype type.
935   ///
936   /// By default, performs semantic analysis when building the decltype type.
937   /// Subclasses may override this routine to provide different behavior.
938   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
939 
940   /// Build a new C++11 auto type.
941   ///
942   /// By default, builds a new AutoType with the given deduced type.
943   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
944     // Note, IsDependent is always false here: we implicitly convert an 'auto'
945     // which has been deduced to a dependent type into an undeduced 'auto', so
946     // that we'll retry deduction after the transformation.
947     return SemaRef.Context.getAutoType(Deduced, Keyword,
948                                        /*IsDependent*/ false);
949   }
950 
951   /// By default, builds a new DeducedTemplateSpecializationType with the given
952   /// deduced type.
953   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
954       QualType Deduced) {
955     return SemaRef.Context.getDeducedTemplateSpecializationType(
956         Template, Deduced, /*IsDependent*/ false);
957   }
958 
959   /// Build a new template specialization type.
960   ///
961   /// By default, performs semantic analysis when building the template
962   /// specialization type. Subclasses may override this routine to provide
963   /// different behavior.
964   QualType RebuildTemplateSpecializationType(TemplateName Template,
965                                              SourceLocation TemplateLoc,
966                                              TemplateArgumentListInfo &Args);
967 
968   /// Build a new parenthesized type.
969   ///
970   /// By default, builds a new ParenType type from the inner type.
971   /// Subclasses may override this routine to provide different behavior.
972   QualType RebuildParenType(QualType InnerType) {
973     return SemaRef.BuildParenType(InnerType);
974   }
975 
976   /// Build a new qualified name type.
977   ///
978   /// By default, builds a new ElaboratedType type from the keyword,
979   /// the nested-name-specifier and the named type.
980   /// Subclasses may override this routine to provide different behavior.
981   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
982                                  ElaboratedTypeKeyword Keyword,
983                                  NestedNameSpecifierLoc QualifierLoc,
984                                  QualType Named) {
985     return SemaRef.Context.getElaboratedType(Keyword,
986                                          QualifierLoc.getNestedNameSpecifier(),
987                                              Named);
988   }
989 
990   /// Build a new typename type that refers to a template-id.
991   ///
992   /// By default, builds a new DependentNameType type from the
993   /// nested-name-specifier and the given type. Subclasses may override
994   /// this routine to provide different behavior.
995   QualType RebuildDependentTemplateSpecializationType(
996                                           ElaboratedTypeKeyword Keyword,
997                                           NestedNameSpecifierLoc QualifierLoc,
998                                           SourceLocation TemplateKWLoc,
999                                           const IdentifierInfo *Name,
1000                                           SourceLocation NameLoc,
1001                                           TemplateArgumentListInfo &Args,
1002                                           bool AllowInjectedClassName) {
1003     // Rebuild the template name.
1004     // TODO: avoid TemplateName abstraction
1005     CXXScopeSpec SS;
1006     SS.Adopt(QualifierLoc);
1007     TemplateName InstName = getDerived().RebuildTemplateName(
1008         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1009         AllowInjectedClassName);
1010 
1011     if (InstName.isNull())
1012       return QualType();
1013 
1014     // If it's still dependent, make a dependent specialization.
1015     if (InstName.getAsDependentTemplateName())
1016       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1017                                           QualifierLoc.getNestedNameSpecifier(),
1018                                                                     Name,
1019                                                                     Args);
1020 
1021     // Otherwise, make an elaborated type wrapping a non-dependent
1022     // specialization.
1023     QualType T =
1024     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1025     if (T.isNull()) return QualType();
1026 
1027     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1028       return T;
1029 
1030     return SemaRef.Context.getElaboratedType(Keyword,
1031                                        QualifierLoc.getNestedNameSpecifier(),
1032                                              T);
1033   }
1034 
1035   /// Build a new typename type that refers to an identifier.
1036   ///
1037   /// By default, performs semantic analysis when building the typename type
1038   /// (or elaborated type). Subclasses may override this routine to provide
1039   /// different behavior.
1040   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1041                                     SourceLocation KeywordLoc,
1042                                     NestedNameSpecifierLoc QualifierLoc,
1043                                     const IdentifierInfo *Id,
1044                                     SourceLocation IdLoc,
1045                                     bool DeducedTSTContext) {
1046     CXXScopeSpec SS;
1047     SS.Adopt(QualifierLoc);
1048 
1049     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1050       // If the name is still dependent, just build a new dependent name type.
1051       if (!SemaRef.computeDeclContext(SS))
1052         return SemaRef.Context.getDependentNameType(Keyword,
1053                                           QualifierLoc.getNestedNameSpecifier(),
1054                                                     Id);
1055     }
1056 
1057     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1058       QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1059                                              *Id, IdLoc);
1060       // If a dependent name resolves to a deduced template specialization type,
1061       // check that we're in one of the syntactic contexts permitting it.
1062       if (!DeducedTSTContext) {
1063         if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1064                 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1065           SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1066             << (int)SemaRef.getTemplateNameKindForDiagnostics(
1067                    Deduced->getTemplateName())
1068             << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1069           if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1070             SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1071           return QualType();
1072         }
1073       }
1074       return T;
1075     }
1076 
1077     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1078 
1079     // We had a dependent elaborated-type-specifier that has been transformed
1080     // into a non-dependent elaborated-type-specifier. Find the tag we're
1081     // referring to.
1082     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1083     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1084     if (!DC)
1085       return QualType();
1086 
1087     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1088       return QualType();
1089 
1090     TagDecl *Tag = nullptr;
1091     SemaRef.LookupQualifiedName(Result, DC);
1092     switch (Result.getResultKind()) {
1093       case LookupResult::NotFound:
1094       case LookupResult::NotFoundInCurrentInstantiation:
1095         break;
1096 
1097       case LookupResult::Found:
1098         Tag = Result.getAsSingle<TagDecl>();
1099         break;
1100 
1101       case LookupResult::FoundOverloaded:
1102       case LookupResult::FoundUnresolvedValue:
1103         llvm_unreachable("Tag lookup cannot find non-tags");
1104 
1105       case LookupResult::Ambiguous:
1106         // Let the LookupResult structure handle ambiguities.
1107         return QualType();
1108     }
1109 
1110     if (!Tag) {
1111       // Check where the name exists but isn't a tag type and use that to emit
1112       // better diagnostics.
1113       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1114       SemaRef.LookupQualifiedName(Result, DC);
1115       switch (Result.getResultKind()) {
1116         case LookupResult::Found:
1117         case LookupResult::FoundOverloaded:
1118         case LookupResult::FoundUnresolvedValue: {
1119           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1120           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1121           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1122                                                                << NTK << Kind;
1123           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1124           break;
1125         }
1126         default:
1127           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1128               << Kind << Id << DC << QualifierLoc.getSourceRange();
1129           break;
1130       }
1131       return QualType();
1132     }
1133 
1134     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1135                                               IdLoc, Id)) {
1136       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1137       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1138       return QualType();
1139     }
1140 
1141     // Build the elaborated-type-specifier type.
1142     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1143     return SemaRef.Context.getElaboratedType(Keyword,
1144                                          QualifierLoc.getNestedNameSpecifier(),
1145                                              T);
1146   }
1147 
1148   /// Build a new pack expansion type.
1149   ///
1150   /// By default, builds a new PackExpansionType type from the given pattern.
1151   /// Subclasses may override this routine to provide different behavior.
1152   QualType RebuildPackExpansionType(QualType Pattern,
1153                                     SourceRange PatternRange,
1154                                     SourceLocation EllipsisLoc,
1155                                     Optional<unsigned> NumExpansions) {
1156     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1157                                         NumExpansions);
1158   }
1159 
1160   /// Build a new atomic type given its value type.
1161   ///
1162   /// By default, performs semantic analysis when building the atomic type.
1163   /// Subclasses may override this routine to provide different behavior.
1164   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1165 
1166   /// Build a new pipe type given its value type.
1167   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1168                            bool isReadPipe);
1169 
1170   /// Build a new template name given a nested name specifier, a flag
1171   /// indicating whether the "template" keyword was provided, and the template
1172   /// that the template name refers to.
1173   ///
1174   /// By default, builds the new template name directly. Subclasses may override
1175   /// this routine to provide different behavior.
1176   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1177                                    bool TemplateKW,
1178                                    TemplateDecl *Template);
1179 
1180   /// Build a new template name given a nested name specifier and the
1181   /// name that is referred to as a template.
1182   ///
1183   /// By default, performs semantic analysis to determine whether the name can
1184   /// be resolved to a specific template, then builds the appropriate kind of
1185   /// template name. Subclasses may override this routine to provide different
1186   /// behavior.
1187   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1188                                    SourceLocation TemplateKWLoc,
1189                                    const IdentifierInfo &Name,
1190                                    SourceLocation NameLoc, QualType ObjectType,
1191                                    NamedDecl *FirstQualifierInScope,
1192                                    bool AllowInjectedClassName);
1193 
1194   /// Build a new template name given a nested name specifier and the
1195   /// overloaded operator name that is referred to as a template.
1196   ///
1197   /// By default, performs semantic analysis to determine whether the name can
1198   /// be resolved to a specific template, then builds the appropriate kind of
1199   /// template name. Subclasses may override this routine to provide different
1200   /// behavior.
1201   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1202                                    SourceLocation TemplateKWLoc,
1203                                    OverloadedOperatorKind Operator,
1204                                    SourceLocation NameLoc, QualType ObjectType,
1205                                    bool AllowInjectedClassName);
1206 
1207   /// Build a new template name given a template template parameter pack
1208   /// and the
1209   ///
1210   /// By default, performs semantic analysis to determine whether the name can
1211   /// be resolved to a specific template, then builds the appropriate kind of
1212   /// template name. Subclasses may override this routine to provide different
1213   /// behavior.
1214   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1215                                    const TemplateArgument &ArgPack) {
1216     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1217   }
1218 
1219   /// Build a new compound statement.
1220   ///
1221   /// By default, performs semantic analysis to build the new statement.
1222   /// Subclasses may override this routine to provide different behavior.
1223   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1224                                        MultiStmtArg Statements,
1225                                        SourceLocation RBraceLoc,
1226                                        bool IsStmtExpr) {
1227     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1228                                        IsStmtExpr);
1229   }
1230 
1231   /// Build a new case statement.
1232   ///
1233   /// By default, performs semantic analysis to build the new statement.
1234   /// Subclasses may override this routine to provide different behavior.
1235   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1236                                    Expr *LHS,
1237                                    SourceLocation EllipsisLoc,
1238                                    Expr *RHS,
1239                                    SourceLocation ColonLoc) {
1240     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1241                                    ColonLoc);
1242   }
1243 
1244   /// Attach the body to a new case statement.
1245   ///
1246   /// By default, performs semantic analysis to build the new statement.
1247   /// Subclasses may override this routine to provide different behavior.
1248   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1249     getSema().ActOnCaseStmtBody(S, Body);
1250     return S;
1251   }
1252 
1253   /// Build a new default statement.
1254   ///
1255   /// By default, performs semantic analysis to build the new statement.
1256   /// Subclasses may override this routine to provide different behavior.
1257   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1258                                       SourceLocation ColonLoc,
1259                                       Stmt *SubStmt) {
1260     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1261                                       /*CurScope=*/nullptr);
1262   }
1263 
1264   /// Build a new label statement.
1265   ///
1266   /// By default, performs semantic analysis to build the new statement.
1267   /// Subclasses may override this routine to provide different behavior.
1268   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1269                               SourceLocation ColonLoc, Stmt *SubStmt) {
1270     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1271   }
1272 
1273   /// Build a new label statement.
1274   ///
1275   /// By default, performs semantic analysis to build the new statement.
1276   /// Subclasses may override this routine to provide different behavior.
1277   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1278                                    ArrayRef<const Attr*> Attrs,
1279                                    Stmt *SubStmt) {
1280     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1281   }
1282 
1283   /// Build a new "if" statement.
1284   ///
1285   /// By default, performs semantic analysis to build the new statement.
1286   /// Subclasses may override this routine to provide different behavior.
1287   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1288                            Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1289                            SourceLocation ElseLoc, Stmt *Else) {
1290     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1291                                  ElseLoc, Else);
1292   }
1293 
1294   /// Start building a new switch statement.
1295   ///
1296   /// By default, performs semantic analysis to build the new statement.
1297   /// Subclasses may override this routine to provide different behavior.
1298   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1299                                     Sema::ConditionResult Cond) {
1300     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1301   }
1302 
1303   /// Attach the body to the switch statement.
1304   ///
1305   /// By default, performs semantic analysis to build the new statement.
1306   /// Subclasses may override this routine to provide different behavior.
1307   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1308                                    Stmt *Switch, Stmt *Body) {
1309     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1310   }
1311 
1312   /// Build a new while statement.
1313   ///
1314   /// By default, performs semantic analysis to build the new statement.
1315   /// Subclasses may override this routine to provide different behavior.
1316   StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1317                               Sema::ConditionResult Cond, Stmt *Body) {
1318     return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1319   }
1320 
1321   /// Build a new do-while statement.
1322   ///
1323   /// By default, performs semantic analysis to build the new statement.
1324   /// Subclasses may override this routine to provide different behavior.
1325   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1326                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1327                            Expr *Cond, SourceLocation RParenLoc) {
1328     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1329                                  Cond, RParenLoc);
1330   }
1331 
1332   /// Build a new for statement.
1333   ///
1334   /// By default, performs semantic analysis to build the new statement.
1335   /// Subclasses may override this routine to provide different behavior.
1336   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1337                             Stmt *Init, Sema::ConditionResult Cond,
1338                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1339                             Stmt *Body) {
1340     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1341                                   Inc, RParenLoc, Body);
1342   }
1343 
1344   /// Build a new goto statement.
1345   ///
1346   /// By default, performs semantic analysis to build the new statement.
1347   /// Subclasses may override this routine to provide different behavior.
1348   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1349                              LabelDecl *Label) {
1350     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1351   }
1352 
1353   /// Build a new indirect goto statement.
1354   ///
1355   /// By default, performs semantic analysis to build the new statement.
1356   /// Subclasses may override this routine to provide different behavior.
1357   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1358                                      SourceLocation StarLoc,
1359                                      Expr *Target) {
1360     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1361   }
1362 
1363   /// Build a new return statement.
1364   ///
1365   /// By default, performs semantic analysis to build the new statement.
1366   /// Subclasses may override this routine to provide different behavior.
1367   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1368     return getSema().BuildReturnStmt(ReturnLoc, Result);
1369   }
1370 
1371   /// Build a new declaration statement.
1372   ///
1373   /// By default, performs semantic analysis to build the new statement.
1374   /// Subclasses may override this routine to provide different behavior.
1375   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1376                              SourceLocation StartLoc, SourceLocation EndLoc) {
1377     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1378     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1379   }
1380 
1381   /// Build a new inline asm statement.
1382   ///
1383   /// By default, performs semantic analysis to build the new statement.
1384   /// Subclasses may override this routine to provide different behavior.
1385   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1386                                bool IsVolatile, unsigned NumOutputs,
1387                                unsigned NumInputs, IdentifierInfo **Names,
1388                                MultiExprArg Constraints, MultiExprArg Exprs,
1389                                Expr *AsmString, MultiExprArg Clobbers,
1390                                unsigned NumLabels,
1391                                SourceLocation RParenLoc) {
1392     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1393                                      NumInputs, Names, Constraints, Exprs,
1394                                      AsmString, Clobbers, NumLabels, RParenLoc);
1395   }
1396 
1397   /// Build a new MS style inline asm statement.
1398   ///
1399   /// By default, performs semantic analysis to build the new statement.
1400   /// Subclasses may override this routine to provide different behavior.
1401   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1402                               ArrayRef<Token> AsmToks,
1403                               StringRef AsmString,
1404                               unsigned NumOutputs, unsigned NumInputs,
1405                               ArrayRef<StringRef> Constraints,
1406                               ArrayRef<StringRef> Clobbers,
1407                               ArrayRef<Expr*> Exprs,
1408                               SourceLocation EndLoc) {
1409     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1410                                     NumOutputs, NumInputs,
1411                                     Constraints, Clobbers, Exprs, EndLoc);
1412   }
1413 
1414   /// Build a new co_return statement.
1415   ///
1416   /// By default, performs semantic analysis to build the new statement.
1417   /// Subclasses may override this routine to provide different behavior.
1418   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1419                                  bool IsImplicit) {
1420     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1421   }
1422 
1423   /// Build a new co_await expression.
1424   ///
1425   /// By default, performs semantic analysis to build the new expression.
1426   /// Subclasses may override this routine to provide different behavior.
1427   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1428                                 bool IsImplicit) {
1429     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1430   }
1431 
1432   /// Build a new co_await expression.
1433   ///
1434   /// By default, performs semantic analysis to build the new expression.
1435   /// Subclasses may override this routine to provide different behavior.
1436   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1437                                          Expr *Result,
1438                                          UnresolvedLookupExpr *Lookup) {
1439     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1440   }
1441 
1442   /// Build a new co_yield expression.
1443   ///
1444   /// By default, performs semantic analysis to build the new expression.
1445   /// Subclasses may override this routine to provide different behavior.
1446   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1447     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1448   }
1449 
1450   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1451     return getSema().BuildCoroutineBodyStmt(Args);
1452   }
1453 
1454   /// Build a new Objective-C \@try statement.
1455   ///
1456   /// By default, performs semantic analysis to build the new statement.
1457   /// Subclasses may override this routine to provide different behavior.
1458   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1459                                         Stmt *TryBody,
1460                                         MultiStmtArg CatchStmts,
1461                                         Stmt *Finally) {
1462     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1463                                         Finally);
1464   }
1465 
1466   /// Rebuild an Objective-C exception declaration.
1467   ///
1468   /// By default, performs semantic analysis to build the new declaration.
1469   /// Subclasses may override this routine to provide different behavior.
1470   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1471                                     TypeSourceInfo *TInfo, QualType T) {
1472     return getSema().BuildObjCExceptionDecl(TInfo, T,
1473                                             ExceptionDecl->getInnerLocStart(),
1474                                             ExceptionDecl->getLocation(),
1475                                             ExceptionDecl->getIdentifier());
1476   }
1477 
1478   /// Build a new Objective-C \@catch statement.
1479   ///
1480   /// By default, performs semantic analysis to build the new statement.
1481   /// Subclasses may override this routine to provide different behavior.
1482   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1483                                           SourceLocation RParenLoc,
1484                                           VarDecl *Var,
1485                                           Stmt *Body) {
1486     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1487                                           Var, Body);
1488   }
1489 
1490   /// Build a new Objective-C \@finally statement.
1491   ///
1492   /// By default, performs semantic analysis to build the new statement.
1493   /// Subclasses may override this routine to provide different behavior.
1494   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1495                                             Stmt *Body) {
1496     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1497   }
1498 
1499   /// Build a new Objective-C \@throw statement.
1500   ///
1501   /// By default, performs semantic analysis to build the new statement.
1502   /// Subclasses may override this routine to provide different behavior.
1503   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1504                                           Expr *Operand) {
1505     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1506   }
1507 
1508   /// Build a new OpenMP executable directive.
1509   ///
1510   /// By default, performs semantic analysis to build the new statement.
1511   /// Subclasses may override this routine to provide different behavior.
1512   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1513                                            DeclarationNameInfo DirName,
1514                                            OpenMPDirectiveKind CancelRegion,
1515                                            ArrayRef<OMPClause *> Clauses,
1516                                            Stmt *AStmt, SourceLocation StartLoc,
1517                                            SourceLocation EndLoc) {
1518     return getSema().ActOnOpenMPExecutableDirective(
1519         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1520   }
1521 
1522   /// Build a new OpenMP 'if' clause.
1523   ///
1524   /// By default, performs semantic analysis to build the new OpenMP clause.
1525   /// Subclasses may override this routine to provide different behavior.
1526   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1527                                 Expr *Condition, SourceLocation StartLoc,
1528                                 SourceLocation LParenLoc,
1529                                 SourceLocation NameModifierLoc,
1530                                 SourceLocation ColonLoc,
1531                                 SourceLocation EndLoc) {
1532     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1533                                          LParenLoc, NameModifierLoc, ColonLoc,
1534                                          EndLoc);
1535   }
1536 
1537   /// Build a new OpenMP 'final' clause.
1538   ///
1539   /// By default, performs semantic analysis to build the new OpenMP clause.
1540   /// Subclasses may override this routine to provide different behavior.
1541   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1542                                    SourceLocation LParenLoc,
1543                                    SourceLocation EndLoc) {
1544     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1545                                             EndLoc);
1546   }
1547 
1548   /// Build a new OpenMP 'num_threads' clause.
1549   ///
1550   /// By default, performs semantic analysis to build the new OpenMP clause.
1551   /// Subclasses may override this routine to provide different behavior.
1552   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1553                                         SourceLocation StartLoc,
1554                                         SourceLocation LParenLoc,
1555                                         SourceLocation EndLoc) {
1556     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1557                                                  LParenLoc, EndLoc);
1558   }
1559 
1560   /// Build a new OpenMP 'safelen' clause.
1561   ///
1562   /// By default, performs semantic analysis to build the new OpenMP clause.
1563   /// Subclasses may override this routine to provide different behavior.
1564   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1565                                      SourceLocation LParenLoc,
1566                                      SourceLocation EndLoc) {
1567     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1568   }
1569 
1570   /// Build a new OpenMP 'simdlen' clause.
1571   ///
1572   /// By default, performs semantic analysis to build the new OpenMP clause.
1573   /// Subclasses may override this routine to provide different behavior.
1574   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1575                                      SourceLocation LParenLoc,
1576                                      SourceLocation EndLoc) {
1577     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1578   }
1579 
1580   /// Build a new OpenMP 'allocator' clause.
1581   ///
1582   /// By default, performs semantic analysis to build the new OpenMP clause.
1583   /// Subclasses may override this routine to provide different behavior.
1584   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1585                                        SourceLocation LParenLoc,
1586                                        SourceLocation EndLoc) {
1587     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1588   }
1589 
1590   /// Build a new OpenMP 'collapse' clause.
1591   ///
1592   /// By default, performs semantic analysis to build the new OpenMP clause.
1593   /// Subclasses may override this routine to provide different behavior.
1594   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1595                                       SourceLocation LParenLoc,
1596                                       SourceLocation EndLoc) {
1597     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1598                                                EndLoc);
1599   }
1600 
1601   /// Build a new OpenMP 'default' clause.
1602   ///
1603   /// By default, performs semantic analysis to build the new OpenMP clause.
1604   /// Subclasses may override this routine to provide different behavior.
1605   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1606                                      SourceLocation KindKwLoc,
1607                                      SourceLocation StartLoc,
1608                                      SourceLocation LParenLoc,
1609                                      SourceLocation EndLoc) {
1610     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1611                                               StartLoc, LParenLoc, EndLoc);
1612   }
1613 
1614   /// Build a new OpenMP 'proc_bind' clause.
1615   ///
1616   /// By default, performs semantic analysis to build the new OpenMP clause.
1617   /// Subclasses may override this routine to provide different behavior.
1618   OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1619                                       SourceLocation KindKwLoc,
1620                                       SourceLocation StartLoc,
1621                                       SourceLocation LParenLoc,
1622                                       SourceLocation EndLoc) {
1623     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1624                                                StartLoc, LParenLoc, EndLoc);
1625   }
1626 
1627   /// Build a new OpenMP 'schedule' clause.
1628   ///
1629   /// By default, performs semantic analysis to build the new OpenMP clause.
1630   /// Subclasses may override this routine to provide different behavior.
1631   OMPClause *RebuildOMPScheduleClause(
1632       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1633       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1634       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1635       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1636     return getSema().ActOnOpenMPScheduleClause(
1637         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1638         CommaLoc, EndLoc);
1639   }
1640 
1641   /// Build a new OpenMP 'ordered' clause.
1642   ///
1643   /// By default, performs semantic analysis to build the new OpenMP clause.
1644   /// Subclasses may override this routine to provide different behavior.
1645   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1646                                      SourceLocation EndLoc,
1647                                      SourceLocation LParenLoc, Expr *Num) {
1648     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1649   }
1650 
1651   /// Build a new OpenMP 'private' clause.
1652   ///
1653   /// By default, performs semantic analysis to build the new OpenMP clause.
1654   /// Subclasses may override this routine to provide different behavior.
1655   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1656                                      SourceLocation StartLoc,
1657                                      SourceLocation LParenLoc,
1658                                      SourceLocation EndLoc) {
1659     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1660                                               EndLoc);
1661   }
1662 
1663   /// Build a new OpenMP 'firstprivate' clause.
1664   ///
1665   /// By default, performs semantic analysis to build the new OpenMP clause.
1666   /// Subclasses may override this routine to provide different behavior.
1667   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1668                                           SourceLocation StartLoc,
1669                                           SourceLocation LParenLoc,
1670                                           SourceLocation EndLoc) {
1671     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1672                                                    EndLoc);
1673   }
1674 
1675   /// Build a new OpenMP 'lastprivate' clause.
1676   ///
1677   /// By default, performs semantic analysis to build the new OpenMP clause.
1678   /// Subclasses may override this routine to provide different behavior.
1679   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1680                                          SourceLocation StartLoc,
1681                                          SourceLocation LParenLoc,
1682                                          SourceLocation EndLoc) {
1683     return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1684                                                   EndLoc);
1685   }
1686 
1687   /// Build a new OpenMP 'shared' clause.
1688   ///
1689   /// By default, performs semantic analysis to build the new OpenMP clause.
1690   /// Subclasses may override this routine to provide different behavior.
1691   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1692                                     SourceLocation StartLoc,
1693                                     SourceLocation LParenLoc,
1694                                     SourceLocation EndLoc) {
1695     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1696                                              EndLoc);
1697   }
1698 
1699   /// Build a new OpenMP 'reduction' clause.
1700   ///
1701   /// By default, performs semantic analysis to build the new statement.
1702   /// Subclasses may override this routine to provide different behavior.
1703   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1704                                        SourceLocation StartLoc,
1705                                        SourceLocation LParenLoc,
1706                                        SourceLocation ColonLoc,
1707                                        SourceLocation EndLoc,
1708                                        CXXScopeSpec &ReductionIdScopeSpec,
1709                                        const DeclarationNameInfo &ReductionId,
1710                                        ArrayRef<Expr *> UnresolvedReductions) {
1711     return getSema().ActOnOpenMPReductionClause(
1712         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1713         ReductionId, UnresolvedReductions);
1714   }
1715 
1716   /// Build a new OpenMP 'task_reduction' clause.
1717   ///
1718   /// By default, performs semantic analysis to build the new statement.
1719   /// Subclasses may override this routine to provide different behavior.
1720   OMPClause *RebuildOMPTaskReductionClause(
1721       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1722       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1723       CXXScopeSpec &ReductionIdScopeSpec,
1724       const DeclarationNameInfo &ReductionId,
1725       ArrayRef<Expr *> UnresolvedReductions) {
1726     return getSema().ActOnOpenMPTaskReductionClause(
1727         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1728         ReductionId, UnresolvedReductions);
1729   }
1730 
1731   /// Build a new OpenMP 'in_reduction' clause.
1732   ///
1733   /// By default, performs semantic analysis to build the new statement.
1734   /// Subclasses may override this routine to provide different behavior.
1735   OMPClause *
1736   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1737                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1738                               SourceLocation EndLoc,
1739                               CXXScopeSpec &ReductionIdScopeSpec,
1740                               const DeclarationNameInfo &ReductionId,
1741                               ArrayRef<Expr *> UnresolvedReductions) {
1742     return getSema().ActOnOpenMPInReductionClause(
1743         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1744         ReductionId, UnresolvedReductions);
1745   }
1746 
1747   /// Build a new OpenMP 'linear' clause.
1748   ///
1749   /// By default, performs semantic analysis to build the new OpenMP clause.
1750   /// Subclasses may override this routine to provide different behavior.
1751   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1752                                     SourceLocation StartLoc,
1753                                     SourceLocation LParenLoc,
1754                                     OpenMPLinearClauseKind Modifier,
1755                                     SourceLocation ModifierLoc,
1756                                     SourceLocation ColonLoc,
1757                                     SourceLocation EndLoc) {
1758     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1759                                              Modifier, ModifierLoc, ColonLoc,
1760                                              EndLoc);
1761   }
1762 
1763   /// Build a new OpenMP 'aligned' clause.
1764   ///
1765   /// By default, performs semantic analysis to build the new OpenMP clause.
1766   /// Subclasses may override this routine to provide different behavior.
1767   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1768                                      SourceLocation StartLoc,
1769                                      SourceLocation LParenLoc,
1770                                      SourceLocation ColonLoc,
1771                                      SourceLocation EndLoc) {
1772     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1773                                               LParenLoc, ColonLoc, EndLoc);
1774   }
1775 
1776   /// Build a new OpenMP 'copyin' clause.
1777   ///
1778   /// By default, performs semantic analysis to build the new OpenMP clause.
1779   /// Subclasses may override this routine to provide different behavior.
1780   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1781                                     SourceLocation StartLoc,
1782                                     SourceLocation LParenLoc,
1783                                     SourceLocation EndLoc) {
1784     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1785                                              EndLoc);
1786   }
1787 
1788   /// Build a new OpenMP 'copyprivate' clause.
1789   ///
1790   /// By default, performs semantic analysis to build the new OpenMP clause.
1791   /// Subclasses may override this routine to provide different behavior.
1792   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1793                                          SourceLocation StartLoc,
1794                                          SourceLocation LParenLoc,
1795                                          SourceLocation EndLoc) {
1796     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1797                                                   EndLoc);
1798   }
1799 
1800   /// Build a new OpenMP 'flush' pseudo clause.
1801   ///
1802   /// By default, performs semantic analysis to build the new OpenMP clause.
1803   /// Subclasses may override this routine to provide different behavior.
1804   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1805                                    SourceLocation StartLoc,
1806                                    SourceLocation LParenLoc,
1807                                    SourceLocation EndLoc) {
1808     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1809                                             EndLoc);
1810   }
1811 
1812   /// Build a new OpenMP 'depend' pseudo clause.
1813   ///
1814   /// By default, performs semantic analysis to build the new OpenMP clause.
1815   /// Subclasses may override this routine to provide different behavior.
1816   OMPClause *
1817   RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1818                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1819                          SourceLocation StartLoc, SourceLocation LParenLoc,
1820                          SourceLocation EndLoc) {
1821     return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1822                                              StartLoc, LParenLoc, EndLoc);
1823   }
1824 
1825   /// Build a new OpenMP 'device' clause.
1826   ///
1827   /// By default, performs semantic analysis to build the new statement.
1828   /// Subclasses may override this routine to provide different behavior.
1829   OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1830                                     SourceLocation LParenLoc,
1831                                     SourceLocation EndLoc) {
1832     return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1833                                              EndLoc);
1834   }
1835 
1836   /// Build a new OpenMP 'map' clause.
1837   ///
1838   /// By default, performs semantic analysis to build the new OpenMP clause.
1839   /// Subclasses may override this routine to provide different behavior.
1840   OMPClause *RebuildOMPMapClause(
1841       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1842       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1843       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1844       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1845       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1846       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1847     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1848                                           MapperIdScopeSpec, MapperId, MapType,
1849                                           IsMapTypeImplicit, MapLoc, ColonLoc,
1850                                           VarList, Locs, UnresolvedMappers);
1851   }
1852 
1853   /// Build a new OpenMP 'allocate' clause.
1854   ///
1855   /// By default, performs semantic analysis to build the new OpenMP clause.
1856   /// Subclasses may override this routine to provide different behavior.
1857   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1858                                       SourceLocation StartLoc,
1859                                       SourceLocation LParenLoc,
1860                                       SourceLocation ColonLoc,
1861                                       SourceLocation EndLoc) {
1862     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1863                                                LParenLoc, ColonLoc, EndLoc);
1864   }
1865 
1866   /// Build a new OpenMP 'num_teams' clause.
1867   ///
1868   /// By default, performs semantic analysis to build the new statement.
1869   /// Subclasses may override this routine to provide different behavior.
1870   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1871                                       SourceLocation LParenLoc,
1872                                       SourceLocation EndLoc) {
1873     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1874                                                EndLoc);
1875   }
1876 
1877   /// Build a new OpenMP 'thread_limit' clause.
1878   ///
1879   /// By default, performs semantic analysis to build the new statement.
1880   /// Subclasses may override this routine to provide different behavior.
1881   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1882                                          SourceLocation StartLoc,
1883                                          SourceLocation LParenLoc,
1884                                          SourceLocation EndLoc) {
1885     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1886                                                   LParenLoc, EndLoc);
1887   }
1888 
1889   /// Build a new OpenMP 'priority' clause.
1890   ///
1891   /// By default, performs semantic analysis to build the new statement.
1892   /// Subclasses may override this routine to provide different behavior.
1893   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1894                                       SourceLocation LParenLoc,
1895                                       SourceLocation EndLoc) {
1896     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1897                                                EndLoc);
1898   }
1899 
1900   /// Build a new OpenMP 'grainsize' clause.
1901   ///
1902   /// By default, performs semantic analysis to build the new statement.
1903   /// Subclasses may override this routine to provide different behavior.
1904   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1905                                        SourceLocation LParenLoc,
1906                                        SourceLocation EndLoc) {
1907     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1908                                                 EndLoc);
1909   }
1910 
1911   /// Build a new OpenMP 'num_tasks' clause.
1912   ///
1913   /// By default, performs semantic analysis to build the new statement.
1914   /// Subclasses may override this routine to provide different behavior.
1915   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1916                                       SourceLocation LParenLoc,
1917                                       SourceLocation EndLoc) {
1918     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1919                                                EndLoc);
1920   }
1921 
1922   /// Build a new OpenMP 'hint' clause.
1923   ///
1924   /// By default, performs semantic analysis to build the new statement.
1925   /// Subclasses may override this routine to provide different behavior.
1926   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1927                                   SourceLocation LParenLoc,
1928                                   SourceLocation EndLoc) {
1929     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1930   }
1931 
1932   /// Build a new OpenMP 'dist_schedule' clause.
1933   ///
1934   /// By default, performs semantic analysis to build the new OpenMP clause.
1935   /// Subclasses may override this routine to provide different behavior.
1936   OMPClause *
1937   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1938                                Expr *ChunkSize, SourceLocation StartLoc,
1939                                SourceLocation LParenLoc, SourceLocation KindLoc,
1940                                SourceLocation CommaLoc, SourceLocation EndLoc) {
1941     return getSema().ActOnOpenMPDistScheduleClause(
1942         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1943   }
1944 
1945   /// Build a new OpenMP 'to' clause.
1946   ///
1947   /// By default, performs semantic analysis to build the new statement.
1948   /// Subclasses may override this routine to provide different behavior.
1949   OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1950                                 CXXScopeSpec &MapperIdScopeSpec,
1951                                 DeclarationNameInfo &MapperId,
1952                                 const OMPVarListLocTy &Locs,
1953                                 ArrayRef<Expr *> UnresolvedMappers) {
1954     return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1955                                          Locs, UnresolvedMappers);
1956   }
1957 
1958   /// Build a new OpenMP 'from' clause.
1959   ///
1960   /// By default, performs semantic analysis to build the new statement.
1961   /// Subclasses may override this routine to provide different behavior.
1962   OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1963                                   CXXScopeSpec &MapperIdScopeSpec,
1964                                   DeclarationNameInfo &MapperId,
1965                                   const OMPVarListLocTy &Locs,
1966                                   ArrayRef<Expr *> UnresolvedMappers) {
1967     return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1968                                            Locs, UnresolvedMappers);
1969   }
1970 
1971   /// Build a new OpenMP 'use_device_ptr' clause.
1972   ///
1973   /// By default, performs semantic analysis to build the new OpenMP clause.
1974   /// Subclasses may override this routine to provide different behavior.
1975   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1976                                           const OMPVarListLocTy &Locs) {
1977     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1978   }
1979 
1980   /// Build a new OpenMP 'is_device_ptr' clause.
1981   ///
1982   /// By default, performs semantic analysis to build the new OpenMP clause.
1983   /// Subclasses may override this routine to provide different behavior.
1984   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1985                                          const OMPVarListLocTy &Locs) {
1986     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1987   }
1988 
1989   /// Build a new OpenMP 'defaultmap' clause.
1990   ///
1991   /// By default, performs semantic analysis to build the new OpenMP clause.
1992   /// Subclasses may override this routine to provide different behavior.
1993   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
1994                                         OpenMPDefaultmapClauseKind Kind,
1995                                         SourceLocation StartLoc,
1996                                         SourceLocation LParenLoc,
1997                                         SourceLocation MLoc,
1998                                         SourceLocation KindLoc,
1999                                         SourceLocation EndLoc) {
2000     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2001                                                  MLoc, KindLoc, EndLoc);
2002   }
2003 
2004   /// Rebuild the operand to an Objective-C \@synchronized statement.
2005   ///
2006   /// By default, performs semantic analysis to build the new statement.
2007   /// Subclasses may override this routine to provide different behavior.
2008   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2009                                               Expr *object) {
2010     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2011   }
2012 
2013   /// Build a new Objective-C \@synchronized statement.
2014   ///
2015   /// By default, performs semantic analysis to build the new statement.
2016   /// Subclasses may override this routine to provide different behavior.
2017   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2018                                            Expr *Object, Stmt *Body) {
2019     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2020   }
2021 
2022   /// Build a new Objective-C \@autoreleasepool statement.
2023   ///
2024   /// By default, performs semantic analysis to build the new statement.
2025   /// Subclasses may override this routine to provide different behavior.
2026   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2027                                             Stmt *Body) {
2028     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2029   }
2030 
2031   /// Build a new Objective-C fast enumeration statement.
2032   ///
2033   /// By default, performs semantic analysis to build the new statement.
2034   /// Subclasses may override this routine to provide different behavior.
2035   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2036                                           Stmt *Element,
2037                                           Expr *Collection,
2038                                           SourceLocation RParenLoc,
2039                                           Stmt *Body) {
2040     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2041                                                 Element,
2042                                                 Collection,
2043                                                 RParenLoc);
2044     if (ForEachStmt.isInvalid())
2045       return StmtError();
2046 
2047     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2048   }
2049 
2050   /// Build a new C++ exception declaration.
2051   ///
2052   /// By default, performs semantic analysis to build the new decaration.
2053   /// Subclasses may override this routine to provide different behavior.
2054   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2055                                 TypeSourceInfo *Declarator,
2056                                 SourceLocation StartLoc,
2057                                 SourceLocation IdLoc,
2058                                 IdentifierInfo *Id) {
2059     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2060                                                        StartLoc, IdLoc, Id);
2061     if (Var)
2062       getSema().CurContext->addDecl(Var);
2063     return Var;
2064   }
2065 
2066   /// Build a new C++ catch statement.
2067   ///
2068   /// By default, performs semantic analysis to build the new statement.
2069   /// Subclasses may override this routine to provide different behavior.
2070   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2071                                  VarDecl *ExceptionDecl,
2072                                  Stmt *Handler) {
2073     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2074                                                       Handler));
2075   }
2076 
2077   /// Build a new C++ try statement.
2078   ///
2079   /// By default, performs semantic analysis to build the new statement.
2080   /// Subclasses may override this routine to provide different behavior.
2081   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2082                                ArrayRef<Stmt *> Handlers) {
2083     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2084   }
2085 
2086   /// Build a new C++0x range-based for statement.
2087   ///
2088   /// By default, performs semantic analysis to build the new statement.
2089   /// Subclasses may override this routine to provide different behavior.
2090   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2091                                     SourceLocation CoawaitLoc, Stmt *Init,
2092                                     SourceLocation ColonLoc, Stmt *Range,
2093                                     Stmt *Begin, Stmt *End, Expr *Cond,
2094                                     Expr *Inc, Stmt *LoopVar,
2095                                     SourceLocation RParenLoc) {
2096     // If we've just learned that the range is actually an Objective-C
2097     // collection, treat this as an Objective-C fast enumeration loop.
2098     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2099       if (RangeStmt->isSingleDecl()) {
2100         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2101           if (RangeVar->isInvalidDecl())
2102             return StmtError();
2103 
2104           Expr *RangeExpr = RangeVar->getInit();
2105           if (!RangeExpr->isTypeDependent() &&
2106               RangeExpr->getType()->isObjCObjectPointerType()) {
2107             // FIXME: Support init-statements in Objective-C++20 ranged for
2108             // statement.
2109             if (Init) {
2110               return SemaRef.Diag(Init->getBeginLoc(),
2111                                   diag::err_objc_for_range_init_stmt)
2112                          << Init->getSourceRange();
2113             }
2114             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2115                                                         RangeExpr, RParenLoc);
2116           }
2117         }
2118       }
2119     }
2120 
2121     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2122                                           Range, Begin, End, Cond, Inc, LoopVar,
2123                                           RParenLoc, Sema::BFRK_Rebuild);
2124   }
2125 
2126   /// Build a new C++0x range-based for statement.
2127   ///
2128   /// By default, performs semantic analysis to build the new statement.
2129   /// Subclasses may override this routine to provide different behavior.
2130   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2131                                           bool IsIfExists,
2132                                           NestedNameSpecifierLoc QualifierLoc,
2133                                           DeclarationNameInfo NameInfo,
2134                                           Stmt *Nested) {
2135     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2136                                                 QualifierLoc, NameInfo, Nested);
2137   }
2138 
2139   /// Attach body to a C++0x range-based for statement.
2140   ///
2141   /// By default, performs semantic analysis to finish the new statement.
2142   /// Subclasses may override this routine to provide different behavior.
2143   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2144     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2145   }
2146 
2147   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2148                                Stmt *TryBlock, Stmt *Handler) {
2149     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2150   }
2151 
2152   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2153                                   Stmt *Block) {
2154     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2155   }
2156 
2157   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2158     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2159   }
2160 
2161   /// Build a new predefined expression.
2162   ///
2163   /// By default, performs semantic analysis to build the new expression.
2164   /// Subclasses may override this routine to provide different behavior.
2165   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2166                                    PredefinedExpr::IdentKind IK) {
2167     return getSema().BuildPredefinedExpr(Loc, IK);
2168   }
2169 
2170   /// Build a new expression that references a declaration.
2171   ///
2172   /// By default, performs semantic analysis to build the new expression.
2173   /// Subclasses may override this routine to provide different behavior.
2174   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2175                                         LookupResult &R,
2176                                         bool RequiresADL) {
2177     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2178   }
2179 
2180 
2181   /// Build a new expression that references a declaration.
2182   ///
2183   /// By default, performs semantic analysis to build the new expression.
2184   /// Subclasses may override this routine to provide different behavior.
2185   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2186                                 ValueDecl *VD,
2187                                 const DeclarationNameInfo &NameInfo,
2188                                 NamedDecl *Found,
2189                                 TemplateArgumentListInfo *TemplateArgs) {
2190     CXXScopeSpec SS;
2191     SS.Adopt(QualifierLoc);
2192     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2193                                               TemplateArgs);
2194   }
2195 
2196   /// Build a new expression in parentheses.
2197   ///
2198   /// By default, performs semantic analysis to build the new expression.
2199   /// Subclasses may override this routine to provide different behavior.
2200   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2201                                     SourceLocation RParen) {
2202     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2203   }
2204 
2205   /// Build a new pseudo-destructor expression.
2206   ///
2207   /// By default, performs semantic analysis to build the new expression.
2208   /// Subclasses may override this routine to provide different behavior.
2209   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2210                                             SourceLocation OperatorLoc,
2211                                             bool isArrow,
2212                                             CXXScopeSpec &SS,
2213                                             TypeSourceInfo *ScopeType,
2214                                             SourceLocation CCLoc,
2215                                             SourceLocation TildeLoc,
2216                                         PseudoDestructorTypeStorage Destroyed);
2217 
2218   /// Build a new unary operator expression.
2219   ///
2220   /// By default, performs semantic analysis to build the new expression.
2221   /// Subclasses may override this routine to provide different behavior.
2222   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2223                                         UnaryOperatorKind Opc,
2224                                         Expr *SubExpr) {
2225     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2226   }
2227 
2228   /// Build a new builtin offsetof expression.
2229   ///
2230   /// By default, performs semantic analysis to build the new expression.
2231   /// Subclasses may override this routine to provide different behavior.
2232   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2233                                  TypeSourceInfo *Type,
2234                                  ArrayRef<Sema::OffsetOfComponent> Components,
2235                                  SourceLocation RParenLoc) {
2236     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2237                                           RParenLoc);
2238   }
2239 
2240   /// Build a new sizeof, alignof or vec_step expression with a
2241   /// type argument.
2242   ///
2243   /// By default, performs semantic analysis to build the new expression.
2244   /// Subclasses may override this routine to provide different behavior.
2245   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2246                                          SourceLocation OpLoc,
2247                                          UnaryExprOrTypeTrait ExprKind,
2248                                          SourceRange R) {
2249     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2250   }
2251 
2252   /// Build a new sizeof, alignof or vec step expression with an
2253   /// expression argument.
2254   ///
2255   /// By default, performs semantic analysis to build the new expression.
2256   /// Subclasses may override this routine to provide different behavior.
2257   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2258                                          UnaryExprOrTypeTrait ExprKind,
2259                                          SourceRange R) {
2260     ExprResult Result
2261       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2262     if (Result.isInvalid())
2263       return ExprError();
2264 
2265     return Result;
2266   }
2267 
2268   /// Build a new array subscript expression.
2269   ///
2270   /// By default, performs semantic analysis to build the new expression.
2271   /// Subclasses may override this routine to provide different behavior.
2272   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2273                                              SourceLocation LBracketLoc,
2274                                              Expr *RHS,
2275                                              SourceLocation RBracketLoc) {
2276     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2277                                              LBracketLoc, RHS,
2278                                              RBracketLoc);
2279   }
2280 
2281   /// Build a new array section expression.
2282   ///
2283   /// By default, performs semantic analysis to build the new expression.
2284   /// Subclasses may override this routine to provide different behavior.
2285   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2286                                         Expr *LowerBound,
2287                                         SourceLocation ColonLoc, Expr *Length,
2288                                         SourceLocation RBracketLoc) {
2289     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2290                                               ColonLoc, Length, RBracketLoc);
2291   }
2292 
2293   /// Build a new call expression.
2294   ///
2295   /// By default, performs semantic analysis to build the new expression.
2296   /// Subclasses may override this routine to provide different behavior.
2297   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2298                                    MultiExprArg Args,
2299                                    SourceLocation RParenLoc,
2300                                    Expr *ExecConfig = nullptr) {
2301     return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2302                                    RParenLoc, ExecConfig);
2303   }
2304 
2305   /// Build a new member access expression.
2306   ///
2307   /// By default, performs semantic analysis to build the new expression.
2308   /// Subclasses may override this routine to provide different behavior.
2309   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2310                                bool isArrow,
2311                                NestedNameSpecifierLoc QualifierLoc,
2312                                SourceLocation TemplateKWLoc,
2313                                const DeclarationNameInfo &MemberNameInfo,
2314                                ValueDecl *Member,
2315                                NamedDecl *FoundDecl,
2316                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2317                                NamedDecl *FirstQualifierInScope) {
2318     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2319                                                                       isArrow);
2320     if (!Member->getDeclName()) {
2321       // We have a reference to an unnamed field.  This is always the
2322       // base of an anonymous struct/union member access, i.e. the
2323       // field is always of record type.
2324       assert(Member->getType()->isRecordType() &&
2325              "unnamed member not of record type?");
2326 
2327       BaseResult =
2328         getSema().PerformObjectMemberConversion(BaseResult.get(),
2329                                                 QualifierLoc.getNestedNameSpecifier(),
2330                                                 FoundDecl, Member);
2331       if (BaseResult.isInvalid())
2332         return ExprError();
2333       Base = BaseResult.get();
2334 
2335       CXXScopeSpec EmptySS;
2336       return getSema().BuildFieldReferenceExpr(
2337           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2338           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2339     }
2340 
2341     CXXScopeSpec SS;
2342     SS.Adopt(QualifierLoc);
2343 
2344     Base = BaseResult.get();
2345     QualType BaseType = Base->getType();
2346 
2347     if (isArrow && !BaseType->isPointerType())
2348       return ExprError();
2349 
2350     // FIXME: this involves duplicating earlier analysis in a lot of
2351     // cases; we should avoid this when possible.
2352     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2353     R.addDecl(FoundDecl);
2354     R.resolveKind();
2355 
2356     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2357                                               SS, TemplateKWLoc,
2358                                               FirstQualifierInScope,
2359                                               R, ExplicitTemplateArgs,
2360                                               /*S*/nullptr);
2361   }
2362 
2363   /// Build a new binary operator expression.
2364   ///
2365   /// By default, performs semantic analysis to build the new expression.
2366   /// Subclasses may override this routine to provide different behavior.
2367   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2368                                          BinaryOperatorKind Opc,
2369                                          Expr *LHS, Expr *RHS) {
2370     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2371   }
2372 
2373   /// Build a new rewritten operator expression.
2374   ///
2375   /// By default, performs semantic analysis to build the new expression.
2376   /// Subclasses may override this routine to provide different behavior.
2377   ExprResult RebuildCXXRewrittenBinaryOperator(
2378       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2379       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2380     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2381                                            RHS, /*RequiresADL*/false);
2382   }
2383 
2384   /// Build a new conditional operator expression.
2385   ///
2386   /// By default, performs semantic analysis to build the new expression.
2387   /// Subclasses may override this routine to provide different behavior.
2388   ExprResult RebuildConditionalOperator(Expr *Cond,
2389                                         SourceLocation QuestionLoc,
2390                                         Expr *LHS,
2391                                         SourceLocation ColonLoc,
2392                                         Expr *RHS) {
2393     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2394                                         LHS, RHS);
2395   }
2396 
2397   /// Build a new C-style cast expression.
2398   ///
2399   /// By default, performs semantic analysis to build the new expression.
2400   /// Subclasses may override this routine to provide different behavior.
2401   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2402                                          TypeSourceInfo *TInfo,
2403                                          SourceLocation RParenLoc,
2404                                          Expr *SubExpr) {
2405     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2406                                          SubExpr);
2407   }
2408 
2409   /// Build a new compound literal expression.
2410   ///
2411   /// By default, performs semantic analysis to build the new expression.
2412   /// Subclasses may override this routine to provide different behavior.
2413   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2414                                               TypeSourceInfo *TInfo,
2415                                               SourceLocation RParenLoc,
2416                                               Expr *Init) {
2417     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2418                                               Init);
2419   }
2420 
2421   /// Build a new extended vector element access expression.
2422   ///
2423   /// By default, performs semantic analysis to build the new expression.
2424   /// Subclasses may override this routine to provide different behavior.
2425   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2426                                                SourceLocation OpLoc,
2427                                                SourceLocation AccessorLoc,
2428                                                IdentifierInfo &Accessor) {
2429 
2430     CXXScopeSpec SS;
2431     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2432     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2433                                               OpLoc, /*IsArrow*/ false,
2434                                               SS, SourceLocation(),
2435                                               /*FirstQualifierInScope*/ nullptr,
2436                                               NameInfo,
2437                                               /* TemplateArgs */ nullptr,
2438                                               /*S*/ nullptr);
2439   }
2440 
2441   /// Build a new initializer list expression.
2442   ///
2443   /// By default, performs semantic analysis to build the new expression.
2444   /// Subclasses may override this routine to provide different behavior.
2445   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2446                              MultiExprArg Inits,
2447                              SourceLocation RBraceLoc) {
2448     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2449   }
2450 
2451   /// Build a new designated initializer expression.
2452   ///
2453   /// By default, performs semantic analysis to build the new expression.
2454   /// Subclasses may override this routine to provide different behavior.
2455   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2456                                              MultiExprArg ArrayExprs,
2457                                              SourceLocation EqualOrColonLoc,
2458                                              bool GNUSyntax,
2459                                              Expr *Init) {
2460     ExprResult Result
2461       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2462                                            Init);
2463     if (Result.isInvalid())
2464       return ExprError();
2465 
2466     return Result;
2467   }
2468 
2469   /// Build a new value-initialized expression.
2470   ///
2471   /// By default, builds the implicit value initialization without performing
2472   /// any semantic analysis. Subclasses may override this routine to provide
2473   /// different behavior.
2474   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2475     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2476   }
2477 
2478   /// Build a new \c va_arg expression.
2479   ///
2480   /// By default, performs semantic analysis to build the new expression.
2481   /// Subclasses may override this routine to provide different behavior.
2482   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2483                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2484                                     SourceLocation RParenLoc) {
2485     return getSema().BuildVAArgExpr(BuiltinLoc,
2486                                     SubExpr, TInfo,
2487                                     RParenLoc);
2488   }
2489 
2490   /// Build a new expression list in parentheses.
2491   ///
2492   /// By default, performs semantic analysis to build the new expression.
2493   /// Subclasses may override this routine to provide different behavior.
2494   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2495                                   MultiExprArg SubExprs,
2496                                   SourceLocation RParenLoc) {
2497     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2498   }
2499 
2500   /// Build a new address-of-label expression.
2501   ///
2502   /// By default, performs semantic analysis, using the name of the label
2503   /// rather than attempting to map the label statement itself.
2504   /// Subclasses may override this routine to provide different behavior.
2505   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2506                                   SourceLocation LabelLoc, LabelDecl *Label) {
2507     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2508   }
2509 
2510   /// Build a new GNU statement expression.
2511   ///
2512   /// By default, performs semantic analysis to build the new expression.
2513   /// Subclasses may override this routine to provide different behavior.
2514   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2515                                    Stmt *SubStmt,
2516                                    SourceLocation RParenLoc) {
2517     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2518   }
2519 
2520   /// Build a new __builtin_choose_expr expression.
2521   ///
2522   /// By default, performs semantic analysis to build the new expression.
2523   /// Subclasses may override this routine to provide different behavior.
2524   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2525                                      Expr *Cond, Expr *LHS, Expr *RHS,
2526                                      SourceLocation RParenLoc) {
2527     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2528                                    Cond, LHS, RHS,
2529                                    RParenLoc);
2530   }
2531 
2532   /// Build a new generic selection expression.
2533   ///
2534   /// By default, performs semantic analysis to build the new expression.
2535   /// Subclasses may override this routine to provide different behavior.
2536   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2537                                          SourceLocation DefaultLoc,
2538                                          SourceLocation RParenLoc,
2539                                          Expr *ControllingExpr,
2540                                          ArrayRef<TypeSourceInfo *> Types,
2541                                          ArrayRef<Expr *> Exprs) {
2542     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2543                                                 ControllingExpr, Types, Exprs);
2544   }
2545 
2546   /// Build a new overloaded operator call expression.
2547   ///
2548   /// By default, performs semantic analysis to build the new expression.
2549   /// The semantic analysis provides the behavior of template instantiation,
2550   /// copying with transformations that turn what looks like an overloaded
2551   /// operator call into a use of a builtin operator, performing
2552   /// argument-dependent lookup, etc. Subclasses may override this routine to
2553   /// provide different behavior.
2554   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2555                                               SourceLocation OpLoc,
2556                                               Expr *Callee,
2557                                               Expr *First,
2558                                               Expr *Second);
2559 
2560   /// Build a new C++ "named" cast expression, such as static_cast or
2561   /// reinterpret_cast.
2562   ///
2563   /// By default, this routine dispatches to one of the more-specific routines
2564   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2565   /// Subclasses may override this routine to provide different behavior.
2566   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2567                                            Stmt::StmtClass Class,
2568                                            SourceLocation LAngleLoc,
2569                                            TypeSourceInfo *TInfo,
2570                                            SourceLocation RAngleLoc,
2571                                            SourceLocation LParenLoc,
2572                                            Expr *SubExpr,
2573                                            SourceLocation RParenLoc) {
2574     switch (Class) {
2575     case Stmt::CXXStaticCastExprClass:
2576       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2577                                                    RAngleLoc, LParenLoc,
2578                                                    SubExpr, RParenLoc);
2579 
2580     case Stmt::CXXDynamicCastExprClass:
2581       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2582                                                     RAngleLoc, LParenLoc,
2583                                                     SubExpr, RParenLoc);
2584 
2585     case Stmt::CXXReinterpretCastExprClass:
2586       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2587                                                         RAngleLoc, LParenLoc,
2588                                                         SubExpr,
2589                                                         RParenLoc);
2590 
2591     case Stmt::CXXConstCastExprClass:
2592       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2593                                                    RAngleLoc, LParenLoc,
2594                                                    SubExpr, RParenLoc);
2595 
2596     default:
2597       llvm_unreachable("Invalid C++ named cast");
2598     }
2599   }
2600 
2601   /// Build a new C++ static_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 RebuildCXXStaticCastExpr(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_static_cast,
2613                                        TInfo, SubExpr,
2614                                        SourceRange(LAngleLoc, RAngleLoc),
2615                                        SourceRange(LParenLoc, RParenLoc));
2616   }
2617 
2618   /// Build a new C++ dynamic_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 RebuildCXXDynamicCastExpr(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_dynamic_cast,
2630                                        TInfo, SubExpr,
2631                                        SourceRange(LAngleLoc, RAngleLoc),
2632                                        SourceRange(LParenLoc, RParenLoc));
2633   }
2634 
2635   /// Build a new C++ reinterpret_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 RebuildCXXReinterpretCastExpr(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_reinterpret_cast,
2647                                        TInfo, SubExpr,
2648                                        SourceRange(LAngleLoc, RAngleLoc),
2649                                        SourceRange(LParenLoc, RParenLoc));
2650   }
2651 
2652   /// Build a new C++ const_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 RebuildCXXConstCastExpr(SourceLocation OpLoc,
2657                                            SourceLocation LAngleLoc,
2658                                            TypeSourceInfo *TInfo,
2659                                            SourceLocation RAngleLoc,
2660                                            SourceLocation LParenLoc,
2661                                            Expr *SubExpr,
2662                                            SourceLocation RParenLoc) {
2663     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2664                                        TInfo, SubExpr,
2665                                        SourceRange(LAngleLoc, RAngleLoc),
2666                                        SourceRange(LParenLoc, RParenLoc));
2667   }
2668 
2669   /// Build a new C++ functional-style cast expression.
2670   ///
2671   /// By default, performs semantic analysis to build the new expression.
2672   /// Subclasses may override this routine to provide different behavior.
2673   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2674                                           SourceLocation LParenLoc,
2675                                           Expr *Sub,
2676                                           SourceLocation RParenLoc,
2677                                           bool ListInitialization) {
2678     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2679                                                MultiExprArg(&Sub, 1), RParenLoc,
2680                                                ListInitialization);
2681   }
2682 
2683   /// Build a new C++ __builtin_bit_cast expression.
2684   ///
2685   /// By default, performs semantic analysis to build the new expression.
2686   /// Subclasses may override this routine to provide different behavior.
2687   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2688                                        TypeSourceInfo *TSI, Expr *Sub,
2689                                        SourceLocation RParenLoc) {
2690     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2691   }
2692 
2693   /// Build a new C++ typeid(type) expression.
2694   ///
2695   /// By default, performs semantic analysis to build the new expression.
2696   /// Subclasses may override this routine to provide different behavior.
2697   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2698                                         SourceLocation TypeidLoc,
2699                                         TypeSourceInfo *Operand,
2700                                         SourceLocation RParenLoc) {
2701     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2702                                     RParenLoc);
2703   }
2704 
2705 
2706   /// Build a new C++ typeid(expr) expression.
2707   ///
2708   /// By default, performs semantic analysis to build the new expression.
2709   /// Subclasses may override this routine to provide different behavior.
2710   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2711                                         SourceLocation TypeidLoc,
2712                                         Expr *Operand,
2713                                         SourceLocation RParenLoc) {
2714     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2715                                     RParenLoc);
2716   }
2717 
2718   /// Build a new C++ __uuidof(type) expression.
2719   ///
2720   /// By default, performs semantic analysis to build the new expression.
2721   /// Subclasses may override this routine to provide different behavior.
2722   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2723                                         SourceLocation TypeidLoc,
2724                                         TypeSourceInfo *Operand,
2725                                         SourceLocation RParenLoc) {
2726     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2727                                     RParenLoc);
2728   }
2729 
2730   /// Build a new C++ __uuidof(expr) expression.
2731   ///
2732   /// By default, performs semantic analysis to build the new expression.
2733   /// Subclasses may override this routine to provide different behavior.
2734   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2735                                         SourceLocation TypeidLoc,
2736                                         Expr *Operand,
2737                                         SourceLocation RParenLoc) {
2738     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2739                                     RParenLoc);
2740   }
2741 
2742   /// Build a new C++ "this" expression.
2743   ///
2744   /// By default, builds a new "this" expression without performing any
2745   /// semantic analysis. Subclasses may override this routine to provide
2746   /// different behavior.
2747   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2748                                 QualType ThisType,
2749                                 bool isImplicit) {
2750     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2751   }
2752 
2753   /// Build a new C++ throw expression.
2754   ///
2755   /// By default, performs semantic analysis to build the new expression.
2756   /// Subclasses may override this routine to provide different behavior.
2757   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2758                                  bool IsThrownVariableInScope) {
2759     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2760   }
2761 
2762   /// Build a new C++ default-argument expression.
2763   ///
2764   /// By default, builds a new default-argument expression, which does not
2765   /// require any semantic analysis. Subclasses may override this routine to
2766   /// provide different behavior.
2767   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2768     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2769                                      getSema().CurContext);
2770   }
2771 
2772   /// Build a new C++11 default-initialization expression.
2773   ///
2774   /// By default, builds a new default field initialization expression, which
2775   /// does not require any semantic analysis. Subclasses may override this
2776   /// routine to provide different behavior.
2777   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2778                                        FieldDecl *Field) {
2779     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2780                                       getSema().CurContext);
2781   }
2782 
2783   /// Build a new C++ zero-initialization expression.
2784   ///
2785   /// By default, performs semantic analysis to build the new expression.
2786   /// Subclasses may override this routine to provide different behavior.
2787   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2788                                            SourceLocation LParenLoc,
2789                                            SourceLocation RParenLoc) {
2790     return getSema().BuildCXXTypeConstructExpr(
2791         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2792   }
2793 
2794   /// Build a new C++ "new" expression.
2795   ///
2796   /// By default, performs semantic analysis to build the new expression.
2797   /// Subclasses may override this routine to provide different behavior.
2798   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2799                                bool UseGlobal,
2800                                SourceLocation PlacementLParen,
2801                                MultiExprArg PlacementArgs,
2802                                SourceLocation PlacementRParen,
2803                                SourceRange TypeIdParens,
2804                                QualType AllocatedType,
2805                                TypeSourceInfo *AllocatedTypeInfo,
2806                                Optional<Expr *> ArraySize,
2807                                SourceRange DirectInitRange,
2808                                Expr *Initializer) {
2809     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2810                                  PlacementLParen,
2811                                  PlacementArgs,
2812                                  PlacementRParen,
2813                                  TypeIdParens,
2814                                  AllocatedType,
2815                                  AllocatedTypeInfo,
2816                                  ArraySize,
2817                                  DirectInitRange,
2818                                  Initializer);
2819   }
2820 
2821   /// Build a new C++ "delete" expression.
2822   ///
2823   /// By default, performs semantic analysis to build the new expression.
2824   /// Subclasses may override this routine to provide different behavior.
2825   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2826                                         bool IsGlobalDelete,
2827                                         bool IsArrayForm,
2828                                         Expr *Operand) {
2829     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2830                                     Operand);
2831   }
2832 
2833   /// Build a new type trait expression.
2834   ///
2835   /// By default, performs semantic analysis to build the new expression.
2836   /// Subclasses may override this routine to provide different behavior.
2837   ExprResult RebuildTypeTrait(TypeTrait Trait,
2838                               SourceLocation StartLoc,
2839                               ArrayRef<TypeSourceInfo *> Args,
2840                               SourceLocation RParenLoc) {
2841     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2842   }
2843 
2844   /// Build a new array type trait expression.
2845   ///
2846   /// By default, performs semantic analysis to build the new expression.
2847   /// Subclasses may override this routine to provide different behavior.
2848   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2849                                    SourceLocation StartLoc,
2850                                    TypeSourceInfo *TSInfo,
2851                                    Expr *DimExpr,
2852                                    SourceLocation RParenLoc) {
2853     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2854   }
2855 
2856   /// Build a new expression trait expression.
2857   ///
2858   /// By default, performs semantic analysis to build the new expression.
2859   /// Subclasses may override this routine to provide different behavior.
2860   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2861                                    SourceLocation StartLoc,
2862                                    Expr *Queried,
2863                                    SourceLocation RParenLoc) {
2864     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2865   }
2866 
2867   /// Build a new (previously unresolved) declaration reference
2868   /// expression.
2869   ///
2870   /// By default, performs semantic analysis to build the new expression.
2871   /// Subclasses may override this routine to provide different behavior.
2872   ExprResult RebuildDependentScopeDeclRefExpr(
2873                                           NestedNameSpecifierLoc QualifierLoc,
2874                                           SourceLocation TemplateKWLoc,
2875                                        const DeclarationNameInfo &NameInfo,
2876                               const TemplateArgumentListInfo *TemplateArgs,
2877                                           bool IsAddressOfOperand,
2878                                           TypeSourceInfo **RecoveryTSI) {
2879     CXXScopeSpec SS;
2880     SS.Adopt(QualifierLoc);
2881 
2882     if (TemplateArgs || TemplateKWLoc.isValid())
2883       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2884                                                     TemplateArgs);
2885 
2886     return getSema().BuildQualifiedDeclarationNameExpr(
2887         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2888   }
2889 
2890   /// Build a new template-id expression.
2891   ///
2892   /// By default, performs semantic analysis to build the new expression.
2893   /// Subclasses may override this routine to provide different behavior.
2894   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2895                                    SourceLocation TemplateKWLoc,
2896                                    LookupResult &R,
2897                                    bool RequiresADL,
2898                               const TemplateArgumentListInfo *TemplateArgs) {
2899     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2900                                          TemplateArgs);
2901   }
2902 
2903   /// Build a new object-construction expression.
2904   ///
2905   /// By default, performs semantic analysis to build the new expression.
2906   /// Subclasses may override this routine to provide different behavior.
2907   ExprResult RebuildCXXConstructExpr(QualType T,
2908                                      SourceLocation Loc,
2909                                      CXXConstructorDecl *Constructor,
2910                                      bool IsElidable,
2911                                      MultiExprArg Args,
2912                                      bool HadMultipleCandidates,
2913                                      bool ListInitialization,
2914                                      bool StdInitListInitialization,
2915                                      bool RequiresZeroInit,
2916                              CXXConstructExpr::ConstructionKind ConstructKind,
2917                                      SourceRange ParenRange) {
2918     SmallVector<Expr*, 8> ConvertedArgs;
2919     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2920                                           ConvertedArgs))
2921       return ExprError();
2922 
2923     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2924                                            IsElidable,
2925                                            ConvertedArgs,
2926                                            HadMultipleCandidates,
2927                                            ListInitialization,
2928                                            StdInitListInitialization,
2929                                            RequiresZeroInit, ConstructKind,
2930                                            ParenRange);
2931   }
2932 
2933   /// Build a new implicit construction via inherited constructor
2934   /// expression.
2935   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2936                                              CXXConstructorDecl *Constructor,
2937                                              bool ConstructsVBase,
2938                                              bool InheritedFromVBase) {
2939     return new (getSema().Context) CXXInheritedCtorInitExpr(
2940         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2941   }
2942 
2943   /// Build a new object-construction expression.
2944   ///
2945   /// By default, performs semantic analysis to build the new expression.
2946   /// Subclasses may override this routine to provide different behavior.
2947   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2948                                            SourceLocation LParenOrBraceLoc,
2949                                            MultiExprArg Args,
2950                                            SourceLocation RParenOrBraceLoc,
2951                                            bool ListInitialization) {
2952     return getSema().BuildCXXTypeConstructExpr(
2953         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2954   }
2955 
2956   /// Build a new object-construction expression.
2957   ///
2958   /// By default, performs semantic analysis to build the new expression.
2959   /// Subclasses may override this routine to provide different behavior.
2960   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2961                                                SourceLocation LParenLoc,
2962                                                MultiExprArg Args,
2963                                                SourceLocation RParenLoc,
2964                                                bool ListInitialization) {
2965     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2966                                                RParenLoc, ListInitialization);
2967   }
2968 
2969   /// Build a new member reference expression.
2970   ///
2971   /// By default, performs semantic analysis to build the new expression.
2972   /// Subclasses may override this routine to provide different behavior.
2973   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2974                                                 QualType BaseType,
2975                                                 bool IsArrow,
2976                                                 SourceLocation OperatorLoc,
2977                                           NestedNameSpecifierLoc QualifierLoc,
2978                                                 SourceLocation TemplateKWLoc,
2979                                             NamedDecl *FirstQualifierInScope,
2980                                    const DeclarationNameInfo &MemberNameInfo,
2981                               const TemplateArgumentListInfo *TemplateArgs) {
2982     CXXScopeSpec SS;
2983     SS.Adopt(QualifierLoc);
2984 
2985     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2986                                             OperatorLoc, IsArrow,
2987                                             SS, TemplateKWLoc,
2988                                             FirstQualifierInScope,
2989                                             MemberNameInfo,
2990                                             TemplateArgs, /*S*/nullptr);
2991   }
2992 
2993   /// Build a new member reference expression.
2994   ///
2995   /// By default, performs semantic analysis to build the new expression.
2996   /// Subclasses may override this routine to provide different behavior.
2997   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2998                                          SourceLocation OperatorLoc,
2999                                          bool IsArrow,
3000                                          NestedNameSpecifierLoc QualifierLoc,
3001                                          SourceLocation TemplateKWLoc,
3002                                          NamedDecl *FirstQualifierInScope,
3003                                          LookupResult &R,
3004                                 const TemplateArgumentListInfo *TemplateArgs) {
3005     CXXScopeSpec SS;
3006     SS.Adopt(QualifierLoc);
3007 
3008     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3009                                             OperatorLoc, IsArrow,
3010                                             SS, TemplateKWLoc,
3011                                             FirstQualifierInScope,
3012                                             R, TemplateArgs, /*S*/nullptr);
3013   }
3014 
3015   /// Build a new noexcept expression.
3016   ///
3017   /// By default, performs semantic analysis to build the new expression.
3018   /// Subclasses may override this routine to provide different behavior.
3019   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3020     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3021   }
3022 
3023   /// Build a new expression to compute the length of a parameter pack.
3024   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3025                                    NamedDecl *Pack,
3026                                    SourceLocation PackLoc,
3027                                    SourceLocation RParenLoc,
3028                                    Optional<unsigned> Length,
3029                                    ArrayRef<TemplateArgument> PartialArgs) {
3030     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3031                                   RParenLoc, Length, PartialArgs);
3032   }
3033 
3034   /// Build a new expression representing a call to a source location
3035   ///  builtin.
3036   ///
3037   /// By default, performs semantic analysis to build the new expression.
3038   /// Subclasses may override this routine to provide different behavior.
3039   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3040                                   SourceLocation BuiltinLoc,
3041                                   SourceLocation RPLoc,
3042                                   DeclContext *ParentContext) {
3043     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3044   }
3045 
3046   /// Build a new Objective-C boxed expression.
3047   ///
3048   /// By default, performs semantic analysis to build the new expression.
3049   /// Subclasses may override this routine to provide different behavior.
3050   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3051       SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc,
3052       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3053       TemplateArgumentListInfo *TALI) {
3054     CXXScopeSpec SS;
3055     SS.Adopt(NNS);
3056     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3057                                                          ConceptNameLoc,
3058                                                          FoundDecl,
3059                                                          NamedConcept, TALI);
3060     if (Result.isInvalid())
3061       return ExprError();
3062     return Result;
3063   }
3064 
3065     /// \brief Build a new Objective-C boxed expression.
3066   ///
3067   /// By default, performs semantic analysis to build the new expression.
3068   /// Subclasses may override this routine to provide different behavior.
3069   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3070     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3071   }
3072 
3073   /// Build a new Objective-C array literal.
3074   ///
3075   /// By default, performs semantic analysis to build the new expression.
3076   /// Subclasses may override this routine to provide different behavior.
3077   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3078                                      Expr **Elements, unsigned NumElements) {
3079     return getSema().BuildObjCArrayLiteral(Range,
3080                                            MultiExprArg(Elements, NumElements));
3081   }
3082 
3083   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3084                                          Expr *Base, Expr *Key,
3085                                          ObjCMethodDecl *getterMethod,
3086                                          ObjCMethodDecl *setterMethod) {
3087     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3088                                                    getterMethod, setterMethod);
3089   }
3090 
3091   /// Build a new Objective-C dictionary literal.
3092   ///
3093   /// By default, performs semantic analysis to build the new expression.
3094   /// Subclasses may override this routine to provide different behavior.
3095   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3096                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3097     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3098   }
3099 
3100   /// Build a new Objective-C \@encode expression.
3101   ///
3102   /// By default, performs semantic analysis to build the new expression.
3103   /// Subclasses may override this routine to provide different behavior.
3104   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3105                                          TypeSourceInfo *EncodeTypeInfo,
3106                                          SourceLocation RParenLoc) {
3107     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3108   }
3109 
3110   /// Build a new Objective-C class message.
3111   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3112                                           Selector Sel,
3113                                           ArrayRef<SourceLocation> SelectorLocs,
3114                                           ObjCMethodDecl *Method,
3115                                           SourceLocation LBracLoc,
3116                                           MultiExprArg Args,
3117                                           SourceLocation RBracLoc) {
3118     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3119                                      ReceiverTypeInfo->getType(),
3120                                      /*SuperLoc=*/SourceLocation(),
3121                                      Sel, Method, LBracLoc, SelectorLocs,
3122                                      RBracLoc, Args);
3123   }
3124 
3125   /// Build a new Objective-C instance message.
3126   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3127                                           Selector Sel,
3128                                           ArrayRef<SourceLocation> SelectorLocs,
3129                                           ObjCMethodDecl *Method,
3130                                           SourceLocation LBracLoc,
3131                                           MultiExprArg Args,
3132                                           SourceLocation RBracLoc) {
3133     return SemaRef.BuildInstanceMessage(Receiver,
3134                                         Receiver->getType(),
3135                                         /*SuperLoc=*/SourceLocation(),
3136                                         Sel, Method, LBracLoc, SelectorLocs,
3137                                         RBracLoc, Args);
3138   }
3139 
3140   /// Build a new Objective-C instance/class message to 'super'.
3141   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3142                                     Selector Sel,
3143                                     ArrayRef<SourceLocation> SelectorLocs,
3144                                     QualType SuperType,
3145                                     ObjCMethodDecl *Method,
3146                                     SourceLocation LBracLoc,
3147                                     MultiExprArg Args,
3148                                     SourceLocation RBracLoc) {
3149     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3150                                           SuperType,
3151                                           SuperLoc,
3152                                           Sel, Method, LBracLoc, SelectorLocs,
3153                                           RBracLoc, Args)
3154                                       : SemaRef.BuildClassMessage(nullptr,
3155                                           SuperType,
3156                                           SuperLoc,
3157                                           Sel, Method, LBracLoc, SelectorLocs,
3158                                           RBracLoc, Args);
3159 
3160 
3161   }
3162 
3163   /// Build a new Objective-C ivar reference expression.
3164   ///
3165   /// By default, performs semantic analysis to build the new expression.
3166   /// Subclasses may override this routine to provide different behavior.
3167   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3168                                           SourceLocation IvarLoc,
3169                                           bool IsArrow, bool IsFreeIvar) {
3170     CXXScopeSpec SS;
3171     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3172     ExprResult Result = getSema().BuildMemberReferenceExpr(
3173         BaseArg, BaseArg->getType(),
3174         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3175         /*FirstQualifierInScope=*/nullptr, NameInfo,
3176         /*TemplateArgs=*/nullptr,
3177         /*S=*/nullptr);
3178     if (IsFreeIvar && Result.isUsable())
3179       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3180     return Result;
3181   }
3182 
3183   /// Build a new Objective-C property reference expression.
3184   ///
3185   /// By default, performs semantic analysis to build the new expression.
3186   /// Subclasses may override this routine to provide different behavior.
3187   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3188                                         ObjCPropertyDecl *Property,
3189                                         SourceLocation PropertyLoc) {
3190     CXXScopeSpec SS;
3191     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3192     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3193                                               /*FIXME:*/PropertyLoc,
3194                                               /*IsArrow=*/false,
3195                                               SS, SourceLocation(),
3196                                               /*FirstQualifierInScope=*/nullptr,
3197                                               NameInfo,
3198                                               /*TemplateArgs=*/nullptr,
3199                                               /*S=*/nullptr);
3200   }
3201 
3202   /// Build a new Objective-C property reference expression.
3203   ///
3204   /// By default, performs semantic analysis to build the new expression.
3205   /// Subclasses may override this routine to provide different behavior.
3206   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3207                                         ObjCMethodDecl *Getter,
3208                                         ObjCMethodDecl *Setter,
3209                                         SourceLocation PropertyLoc) {
3210     // Since these expressions can only be value-dependent, we do not
3211     // need to perform semantic analysis again.
3212     return Owned(
3213       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3214                                                   VK_LValue, OK_ObjCProperty,
3215                                                   PropertyLoc, Base));
3216   }
3217 
3218   /// Build a new Objective-C "isa" 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 RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3223                                 SourceLocation OpLoc, bool IsArrow) {
3224     CXXScopeSpec SS;
3225     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3226     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3227                                               OpLoc, IsArrow,
3228                                               SS, SourceLocation(),
3229                                               /*FirstQualifierInScope=*/nullptr,
3230                                               NameInfo,
3231                                               /*TemplateArgs=*/nullptr,
3232                                               /*S=*/nullptr);
3233   }
3234 
3235   /// Build a new shuffle vector expression.
3236   ///
3237   /// By default, performs semantic analysis to build the new expression.
3238   /// Subclasses may override this routine to provide different behavior.
3239   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3240                                       MultiExprArg SubExprs,
3241                                       SourceLocation RParenLoc) {
3242     // Find the declaration for __builtin_shufflevector
3243     const IdentifierInfo &Name
3244       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3245     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3246     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3247     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3248 
3249     // Build a reference to the __builtin_shufflevector builtin
3250     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3251     Expr *Callee = new (SemaRef.Context)
3252         DeclRefExpr(SemaRef.Context, Builtin, false,
3253                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3254     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3255     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3256                                        CK_BuiltinFnToFnPtr).get();
3257 
3258     // Build the CallExpr
3259     ExprResult TheCall = CallExpr::Create(
3260         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3261         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3262 
3263     // Type-check the __builtin_shufflevector expression.
3264     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3265   }
3266 
3267   /// Build a new convert vector expression.
3268   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3269                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3270                                       SourceLocation RParenLoc) {
3271     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3272                                          BuiltinLoc, RParenLoc);
3273   }
3274 
3275   /// Build a new template argument pack expansion.
3276   ///
3277   /// By default, performs semantic analysis to build a new pack expansion
3278   /// for a template argument. Subclasses may override this routine to provide
3279   /// different behavior.
3280   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3281                                            SourceLocation EllipsisLoc,
3282                                            Optional<unsigned> NumExpansions) {
3283     switch (Pattern.getArgument().getKind()) {
3284     case TemplateArgument::Expression: {
3285       ExprResult Result
3286         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3287                                        EllipsisLoc, NumExpansions);
3288       if (Result.isInvalid())
3289         return TemplateArgumentLoc();
3290 
3291       return TemplateArgumentLoc(Result.get(), Result.get());
3292     }
3293 
3294     case TemplateArgument::Template:
3295       return TemplateArgumentLoc(TemplateArgument(
3296                                           Pattern.getArgument().getAsTemplate(),
3297                                                   NumExpansions),
3298                                  Pattern.getTemplateQualifierLoc(),
3299                                  Pattern.getTemplateNameLoc(),
3300                                  EllipsisLoc);
3301 
3302     case TemplateArgument::Null:
3303     case TemplateArgument::Integral:
3304     case TemplateArgument::Declaration:
3305     case TemplateArgument::Pack:
3306     case TemplateArgument::TemplateExpansion:
3307     case TemplateArgument::NullPtr:
3308       llvm_unreachable("Pack expansion pattern has no parameter packs");
3309 
3310     case TemplateArgument::Type:
3311       if (TypeSourceInfo *Expansion
3312             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3313                                            EllipsisLoc,
3314                                            NumExpansions))
3315         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3316                                    Expansion);
3317       break;
3318     }
3319 
3320     return TemplateArgumentLoc();
3321   }
3322 
3323   /// Build a new expression pack expansion.
3324   ///
3325   /// By default, performs semantic analysis to build a new pack expansion
3326   /// for an expression. Subclasses may override this routine to provide
3327   /// different behavior.
3328   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3329                                   Optional<unsigned> NumExpansions) {
3330     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3331   }
3332 
3333   /// Build a new C++1z fold-expression.
3334   ///
3335   /// By default, performs semantic analysis in order to build a new fold
3336   /// expression.
3337   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3338                                 BinaryOperatorKind Operator,
3339                                 SourceLocation EllipsisLoc, Expr *RHS,
3340                                 SourceLocation RParenLoc,
3341                                 Optional<unsigned> NumExpansions) {
3342     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3343                                       RHS, RParenLoc, NumExpansions);
3344   }
3345 
3346   /// Build an empty C++1z fold-expression with the given operator.
3347   ///
3348   /// By default, produces the fallback value for the fold-expression, or
3349   /// produce an error if there is no fallback value.
3350   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3351                                      BinaryOperatorKind Operator) {
3352     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3353   }
3354 
3355   /// Build a new atomic operation expression.
3356   ///
3357   /// By default, performs semantic analysis to build the new expression.
3358   /// Subclasses may override this routine to provide different behavior.
3359   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3360                                AtomicExpr::AtomicOp Op,
3361                                SourceLocation RParenLoc) {
3362     // Use this for all of the locations, since we don't know the difference
3363     // between the call and the expr at this point.
3364     SourceRange Range{BuiltinLoc, RParenLoc};
3365     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3366                                      Sema::AtomicArgumentOrder::AST);
3367   }
3368 
3369 private:
3370   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3371                                      QualType ObjectType,
3372                                      NamedDecl *FirstQualifierInScope,
3373                                      CXXScopeSpec &SS);
3374 
3375   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3376                                              QualType ObjectType,
3377                                              NamedDecl *FirstQualifierInScope,
3378                                              CXXScopeSpec &SS);
3379 
3380   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3381                                             NamedDecl *FirstQualifierInScope,
3382                                             CXXScopeSpec &SS);
3383 
3384   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3385                                       DependentNameTypeLoc TL,
3386                                       bool DeducibleTSTContext);
3387 };
3388 
3389 template <typename Derived>
3390 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3391   if (!S)
3392     return S;
3393 
3394   switch (S->getStmtClass()) {
3395   case Stmt::NoStmtClass: break;
3396 
3397   // Transform individual statement nodes
3398   // Pass SDK into statements that can produce a value
3399 #define STMT(Node, Parent)                                              \
3400   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3401 #define VALUESTMT(Node, Parent)                                         \
3402   case Stmt::Node##Class:                                               \
3403     return getDerived().Transform##Node(cast<Node>(S), SDK);
3404 #define ABSTRACT_STMT(Node)
3405 #define EXPR(Node, Parent)
3406 #include "clang/AST/StmtNodes.inc"
3407 
3408   // Transform expressions by calling TransformExpr.
3409 #define STMT(Node, Parent)
3410 #define ABSTRACT_STMT(Stmt)
3411 #define EXPR(Node, Parent) case Stmt::Node##Class:
3412 #include "clang/AST/StmtNodes.inc"
3413     {
3414       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3415 
3416       if (SDK == SDK_StmtExprResult)
3417         E = getSema().ActOnStmtExprResult(E);
3418       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3419     }
3420   }
3421 
3422   return S;
3423 }
3424 
3425 template<typename Derived>
3426 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3427   if (!S)
3428     return S;
3429 
3430   switch (S->getClauseKind()) {
3431   default: break;
3432   // Transform individual clause nodes
3433 #define OPENMP_CLAUSE(Name, Class)                                             \
3434   case OMPC_ ## Name :                                                         \
3435     return getDerived().Transform ## Class(cast<Class>(S));
3436 #include "clang/Basic/OpenMPKinds.def"
3437   }
3438 
3439   return S;
3440 }
3441 
3442 
3443 template<typename Derived>
3444 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3445   if (!E)
3446     return E;
3447 
3448   switch (E->getStmtClass()) {
3449     case Stmt::NoStmtClass: break;
3450 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3451 #define ABSTRACT_STMT(Stmt)
3452 #define EXPR(Node, Parent)                                              \
3453     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3454 #include "clang/AST/StmtNodes.inc"
3455   }
3456 
3457   return E;
3458 }
3459 
3460 template<typename Derived>
3461 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3462                                                         bool NotCopyInit) {
3463   // Initializers are instantiated like expressions, except that various outer
3464   // layers are stripped.
3465   if (!Init)
3466     return Init;
3467 
3468   if (auto *FE = dyn_cast<FullExpr>(Init))
3469     Init = FE->getSubExpr();
3470 
3471   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3472     Init = AIL->getCommonExpr();
3473 
3474   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3475     Init = MTE->getSubExpr();
3476 
3477   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3478     Init = Binder->getSubExpr();
3479 
3480   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3481     Init = ICE->getSubExprAsWritten();
3482 
3483   if (CXXStdInitializerListExpr *ILE =
3484           dyn_cast<CXXStdInitializerListExpr>(Init))
3485     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3486 
3487   // If this is copy-initialization, we only need to reconstruct
3488   // InitListExprs. Other forms of copy-initialization will be a no-op if
3489   // the initializer is already the right type.
3490   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3491   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3492     return getDerived().TransformExpr(Init);
3493 
3494   // Revert value-initialization back to empty parens.
3495   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3496     SourceRange Parens = VIE->getSourceRange();
3497     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3498                                              Parens.getEnd());
3499   }
3500 
3501   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3502   if (isa<ImplicitValueInitExpr>(Init))
3503     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3504                                              SourceLocation());
3505 
3506   // Revert initialization by constructor back to a parenthesized or braced list
3507   // of expressions. Any other form of initializer can just be reused directly.
3508   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3509     return getDerived().TransformExpr(Init);
3510 
3511   // If the initialization implicitly converted an initializer list to a
3512   // std::initializer_list object, unwrap the std::initializer_list too.
3513   if (Construct && Construct->isStdInitListInitialization())
3514     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3515 
3516   // Enter a list-init context if this was list initialization.
3517   EnterExpressionEvaluationContext Context(
3518       getSema(), EnterExpressionEvaluationContext::InitList,
3519       Construct->isListInitialization());
3520 
3521   SmallVector<Expr*, 8> NewArgs;
3522   bool ArgChanged = false;
3523   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3524                                   /*IsCall*/true, NewArgs, &ArgChanged))
3525     return ExprError();
3526 
3527   // If this was list initialization, revert to syntactic list form.
3528   if (Construct->isListInitialization())
3529     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3530                                         Construct->getEndLoc());
3531 
3532   // Build a ParenListExpr to represent anything else.
3533   SourceRange Parens = Construct->getParenOrBraceRange();
3534   if (Parens.isInvalid()) {
3535     // This was a variable declaration's initialization for which no initializer
3536     // was specified.
3537     assert(NewArgs.empty() &&
3538            "no parens or braces but have direct init with arguments?");
3539     return ExprEmpty();
3540   }
3541   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3542                                            Parens.getEnd());
3543 }
3544 
3545 template<typename Derived>
3546 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3547                                             unsigned NumInputs,
3548                                             bool IsCall,
3549                                       SmallVectorImpl<Expr *> &Outputs,
3550                                             bool *ArgChanged) {
3551   for (unsigned I = 0; I != NumInputs; ++I) {
3552     // If requested, drop call arguments that need to be dropped.
3553     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3554       if (ArgChanged)
3555         *ArgChanged = true;
3556 
3557       break;
3558     }
3559 
3560     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3561       Expr *Pattern = Expansion->getPattern();
3562 
3563       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3564       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3565       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3566 
3567       // Determine whether the set of unexpanded parameter packs can and should
3568       // be expanded.
3569       bool Expand = true;
3570       bool RetainExpansion = false;
3571       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3572       Optional<unsigned> NumExpansions = OrigNumExpansions;
3573       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3574                                                Pattern->getSourceRange(),
3575                                                Unexpanded,
3576                                                Expand, RetainExpansion,
3577                                                NumExpansions))
3578         return true;
3579 
3580       if (!Expand) {
3581         // The transform has determined that we should perform a simple
3582         // transformation on the pack expansion, producing another pack
3583         // expansion.
3584         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3585         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3586         if (OutPattern.isInvalid())
3587           return true;
3588 
3589         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3590                                                 Expansion->getEllipsisLoc(),
3591                                                            NumExpansions);
3592         if (Out.isInvalid())
3593           return true;
3594 
3595         if (ArgChanged)
3596           *ArgChanged = true;
3597         Outputs.push_back(Out.get());
3598         continue;
3599       }
3600 
3601       // Record right away that the argument was changed.  This needs
3602       // to happen even if the array expands to nothing.
3603       if (ArgChanged) *ArgChanged = true;
3604 
3605       // The transform has determined that we should perform an elementwise
3606       // expansion of the pattern. Do so.
3607       for (unsigned I = 0; I != *NumExpansions; ++I) {
3608         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3609         ExprResult Out = getDerived().TransformExpr(Pattern);
3610         if (Out.isInvalid())
3611           return true;
3612 
3613         if (Out.get()->containsUnexpandedParameterPack()) {
3614           Out = getDerived().RebuildPackExpansion(
3615               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3616           if (Out.isInvalid())
3617             return true;
3618         }
3619 
3620         Outputs.push_back(Out.get());
3621       }
3622 
3623       // If we're supposed to retain a pack expansion, do so by temporarily
3624       // forgetting the partially-substituted parameter pack.
3625       if (RetainExpansion) {
3626         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3627 
3628         ExprResult Out = getDerived().TransformExpr(Pattern);
3629         if (Out.isInvalid())
3630           return true;
3631 
3632         Out = getDerived().RebuildPackExpansion(
3633             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3634         if (Out.isInvalid())
3635           return true;
3636 
3637         Outputs.push_back(Out.get());
3638       }
3639 
3640       continue;
3641     }
3642 
3643     ExprResult Result =
3644       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3645              : getDerived().TransformExpr(Inputs[I]);
3646     if (Result.isInvalid())
3647       return true;
3648 
3649     if (Result.get() != Inputs[I] && ArgChanged)
3650       *ArgChanged = true;
3651 
3652     Outputs.push_back(Result.get());
3653   }
3654 
3655   return false;
3656 }
3657 
3658 template <typename Derived>
3659 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3660     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3661   if (Var) {
3662     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3663         getDerived().TransformDefinition(Var->getLocation(), Var));
3664 
3665     if (!ConditionVar)
3666       return Sema::ConditionError();
3667 
3668     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3669   }
3670 
3671   if (Expr) {
3672     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3673 
3674     if (CondExpr.isInvalid())
3675       return Sema::ConditionError();
3676 
3677     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3678   }
3679 
3680   return Sema::ConditionResult();
3681 }
3682 
3683 template<typename Derived>
3684 NestedNameSpecifierLoc
3685 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3686                                                     NestedNameSpecifierLoc NNS,
3687                                                      QualType ObjectType,
3688                                              NamedDecl *FirstQualifierInScope) {
3689   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3690   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3691        Qualifier = Qualifier.getPrefix())
3692     Qualifiers.push_back(Qualifier);
3693 
3694   CXXScopeSpec SS;
3695   while (!Qualifiers.empty()) {
3696     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3697     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3698 
3699     switch (QNNS->getKind()) {
3700     case NestedNameSpecifier::Identifier: {
3701       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3702                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3703       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3704                                               SS, FirstQualifierInScope, false))
3705         return NestedNameSpecifierLoc();
3706     }
3707       break;
3708 
3709     case NestedNameSpecifier::Namespace: {
3710       NamespaceDecl *NS
3711         = cast_or_null<NamespaceDecl>(
3712                                     getDerived().TransformDecl(
3713                                                           Q.getLocalBeginLoc(),
3714                                                        QNNS->getAsNamespace()));
3715       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3716       break;
3717     }
3718 
3719     case NestedNameSpecifier::NamespaceAlias: {
3720       NamespaceAliasDecl *Alias
3721         = cast_or_null<NamespaceAliasDecl>(
3722                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3723                                                  QNNS->getAsNamespaceAlias()));
3724       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3725                 Q.getLocalEndLoc());
3726       break;
3727     }
3728 
3729     case NestedNameSpecifier::Global:
3730       // There is no meaningful transformation that one could perform on the
3731       // global scope.
3732       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3733       break;
3734 
3735     case NestedNameSpecifier::Super: {
3736       CXXRecordDecl *RD =
3737           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3738               SourceLocation(), QNNS->getAsRecordDecl()));
3739       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3740       break;
3741     }
3742 
3743     case NestedNameSpecifier::TypeSpecWithTemplate:
3744     case NestedNameSpecifier::TypeSpec: {
3745       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3746                                               FirstQualifierInScope, SS);
3747 
3748       if (!TL)
3749         return NestedNameSpecifierLoc();
3750 
3751       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3752           (SemaRef.getLangOpts().CPlusPlus11 &&
3753            TL.getType()->isEnumeralType())) {
3754         assert(!TL.getType().hasLocalQualifiers() &&
3755                "Can't get cv-qualifiers here");
3756         if (TL.getType()->isEnumeralType())
3757           SemaRef.Diag(TL.getBeginLoc(),
3758                        diag::warn_cxx98_compat_enum_nested_name_spec);
3759         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3760                   Q.getLocalEndLoc());
3761         break;
3762       }
3763       // If the nested-name-specifier is an invalid type def, don't emit an
3764       // error because a previous error should have already been emitted.
3765       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3766       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3767         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3768           << TL.getType() << SS.getRange();
3769       }
3770       return NestedNameSpecifierLoc();
3771     }
3772     }
3773 
3774     // The qualifier-in-scope and object type only apply to the leftmost entity.
3775     FirstQualifierInScope = nullptr;
3776     ObjectType = QualType();
3777   }
3778 
3779   // Don't rebuild the nested-name-specifier if we don't have to.
3780   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3781       !getDerived().AlwaysRebuild())
3782     return NNS;
3783 
3784   // If we can re-use the source-location data from the original
3785   // nested-name-specifier, do so.
3786   if (SS.location_size() == NNS.getDataLength() &&
3787       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3788     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3789 
3790   // Allocate new nested-name-specifier location information.
3791   return SS.getWithLocInContext(SemaRef.Context);
3792 }
3793 
3794 template<typename Derived>
3795 DeclarationNameInfo
3796 TreeTransform<Derived>
3797 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3798   DeclarationName Name = NameInfo.getName();
3799   if (!Name)
3800     return DeclarationNameInfo();
3801 
3802   switch (Name.getNameKind()) {
3803   case DeclarationName::Identifier:
3804   case DeclarationName::ObjCZeroArgSelector:
3805   case DeclarationName::ObjCOneArgSelector:
3806   case DeclarationName::ObjCMultiArgSelector:
3807   case DeclarationName::CXXOperatorName:
3808   case DeclarationName::CXXLiteralOperatorName:
3809   case DeclarationName::CXXUsingDirective:
3810     return NameInfo;
3811 
3812   case DeclarationName::CXXDeductionGuideName: {
3813     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3814     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3815         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3816     if (!NewTemplate)
3817       return DeclarationNameInfo();
3818 
3819     DeclarationNameInfo NewNameInfo(NameInfo);
3820     NewNameInfo.setName(
3821         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3822     return NewNameInfo;
3823   }
3824 
3825   case DeclarationName::CXXConstructorName:
3826   case DeclarationName::CXXDestructorName:
3827   case DeclarationName::CXXConversionFunctionName: {
3828     TypeSourceInfo *NewTInfo;
3829     CanQualType NewCanTy;
3830     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3831       NewTInfo = getDerived().TransformType(OldTInfo);
3832       if (!NewTInfo)
3833         return DeclarationNameInfo();
3834       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3835     }
3836     else {
3837       NewTInfo = nullptr;
3838       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3839       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3840       if (NewT.isNull())
3841         return DeclarationNameInfo();
3842       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3843     }
3844 
3845     DeclarationName NewName
3846       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3847                                                            NewCanTy);
3848     DeclarationNameInfo NewNameInfo(NameInfo);
3849     NewNameInfo.setName(NewName);
3850     NewNameInfo.setNamedTypeInfo(NewTInfo);
3851     return NewNameInfo;
3852   }
3853   }
3854 
3855   llvm_unreachable("Unknown name kind.");
3856 }
3857 
3858 template<typename Derived>
3859 TemplateName
3860 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3861                                               TemplateName Name,
3862                                               SourceLocation NameLoc,
3863                                               QualType ObjectType,
3864                                               NamedDecl *FirstQualifierInScope,
3865                                               bool AllowInjectedClassName) {
3866   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3867     TemplateDecl *Template = QTN->getTemplateDecl();
3868     assert(Template && "qualified template name must refer to a template");
3869 
3870     TemplateDecl *TransTemplate
3871       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3872                                                               Template));
3873     if (!TransTemplate)
3874       return TemplateName();
3875 
3876     if (!getDerived().AlwaysRebuild() &&
3877         SS.getScopeRep() == QTN->getQualifier() &&
3878         TransTemplate == Template)
3879       return Name;
3880 
3881     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3882                                             TransTemplate);
3883   }
3884 
3885   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3886     if (SS.getScopeRep()) {
3887       // These apply to the scope specifier, not the template.
3888       ObjectType = QualType();
3889       FirstQualifierInScope = nullptr;
3890     }
3891 
3892     if (!getDerived().AlwaysRebuild() &&
3893         SS.getScopeRep() == DTN->getQualifier() &&
3894         ObjectType.isNull())
3895       return Name;
3896 
3897     // FIXME: Preserve the location of the "template" keyword.
3898     SourceLocation TemplateKWLoc = NameLoc;
3899 
3900     if (DTN->isIdentifier()) {
3901       return getDerived().RebuildTemplateName(SS,
3902                                               TemplateKWLoc,
3903                                               *DTN->getIdentifier(),
3904                                               NameLoc,
3905                                               ObjectType,
3906                                               FirstQualifierInScope,
3907                                               AllowInjectedClassName);
3908     }
3909 
3910     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3911                                             DTN->getOperator(), NameLoc,
3912                                             ObjectType, AllowInjectedClassName);
3913   }
3914 
3915   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3916     TemplateDecl *TransTemplate
3917       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3918                                                               Template));
3919     if (!TransTemplate)
3920       return TemplateName();
3921 
3922     if (!getDerived().AlwaysRebuild() &&
3923         TransTemplate == Template)
3924       return Name;
3925 
3926     return TemplateName(TransTemplate);
3927   }
3928 
3929   if (SubstTemplateTemplateParmPackStorage *SubstPack
3930       = Name.getAsSubstTemplateTemplateParmPack()) {
3931     TemplateTemplateParmDecl *TransParam
3932     = cast_or_null<TemplateTemplateParmDecl>(
3933             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3934     if (!TransParam)
3935       return TemplateName();
3936 
3937     if (!getDerived().AlwaysRebuild() &&
3938         TransParam == SubstPack->getParameterPack())
3939       return Name;
3940 
3941     return getDerived().RebuildTemplateName(TransParam,
3942                                             SubstPack->getArgumentPack());
3943   }
3944 
3945   // These should be getting filtered out before they reach the AST.
3946   llvm_unreachable("overloaded function decl survived to here");
3947 }
3948 
3949 template<typename Derived>
3950 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3951                                          const TemplateArgument &Arg,
3952                                          TemplateArgumentLoc &Output) {
3953   SourceLocation Loc = getDerived().getBaseLocation();
3954   switch (Arg.getKind()) {
3955   case TemplateArgument::Null:
3956     llvm_unreachable("null template argument in TreeTransform");
3957     break;
3958 
3959   case TemplateArgument::Type:
3960     Output = TemplateArgumentLoc(Arg,
3961                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3962 
3963     break;
3964 
3965   case TemplateArgument::Template:
3966   case TemplateArgument::TemplateExpansion: {
3967     NestedNameSpecifierLocBuilder Builder;
3968     TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3969     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3970       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3971     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3972       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3973 
3974     if (Arg.getKind() == TemplateArgument::Template)
3975       Output = TemplateArgumentLoc(Arg,
3976                                    Builder.getWithLocInContext(SemaRef.Context),
3977                                    Loc);
3978     else
3979       Output = TemplateArgumentLoc(Arg,
3980                                    Builder.getWithLocInContext(SemaRef.Context),
3981                                    Loc, Loc);
3982 
3983     break;
3984   }
3985 
3986   case TemplateArgument::Expression:
3987     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3988     break;
3989 
3990   case TemplateArgument::Declaration:
3991   case TemplateArgument::Integral:
3992   case TemplateArgument::Pack:
3993   case TemplateArgument::NullPtr:
3994     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3995     break;
3996   }
3997 }
3998 
3999 template<typename Derived>
4000 bool TreeTransform<Derived>::TransformTemplateArgument(
4001                                          const TemplateArgumentLoc &Input,
4002                                          TemplateArgumentLoc &Output, bool Uneval) {
4003   const TemplateArgument &Arg = Input.getArgument();
4004   switch (Arg.getKind()) {
4005   case TemplateArgument::Null:
4006   case TemplateArgument::Integral:
4007   case TemplateArgument::Pack:
4008   case TemplateArgument::Declaration:
4009   case TemplateArgument::NullPtr:
4010     llvm_unreachable("Unexpected TemplateArgument");
4011 
4012   case TemplateArgument::Type: {
4013     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4014     if (!DI)
4015       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4016 
4017     DI = getDerived().TransformType(DI);
4018     if (!DI) return true;
4019 
4020     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4021     return false;
4022   }
4023 
4024   case TemplateArgument::Template: {
4025     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4026     if (QualifierLoc) {
4027       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4028       if (!QualifierLoc)
4029         return true;
4030     }
4031 
4032     CXXScopeSpec SS;
4033     SS.Adopt(QualifierLoc);
4034     TemplateName Template
4035       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
4036                                            Input.getTemplateNameLoc());
4037     if (Template.isNull())
4038       return true;
4039 
4040     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
4041                                  Input.getTemplateNameLoc());
4042     return false;
4043   }
4044 
4045   case TemplateArgument::TemplateExpansion:
4046     llvm_unreachable("Caller should expand pack expansions");
4047 
4048   case TemplateArgument::Expression: {
4049     // Template argument expressions are constant expressions.
4050     EnterExpressionEvaluationContext Unevaluated(
4051         getSema(),
4052         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4053                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4054         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4055         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4056 
4057     Expr *InputExpr = Input.getSourceExpression();
4058     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4059 
4060     ExprResult E = getDerived().TransformExpr(InputExpr);
4061     E = SemaRef.ActOnConstantExpression(E);
4062     if (E.isInvalid()) return true;
4063     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4064     return false;
4065   }
4066   }
4067 
4068   // Work around bogus GCC warning
4069   return true;
4070 }
4071 
4072 /// Iterator adaptor that invents template argument location information
4073 /// for each of the template arguments in its underlying iterator.
4074 template<typename Derived, typename InputIterator>
4075 class TemplateArgumentLocInventIterator {
4076   TreeTransform<Derived> &Self;
4077   InputIterator Iter;
4078 
4079 public:
4080   typedef TemplateArgumentLoc value_type;
4081   typedef TemplateArgumentLoc reference;
4082   typedef typename std::iterator_traits<InputIterator>::difference_type
4083     difference_type;
4084   typedef std::input_iterator_tag iterator_category;
4085 
4086   class pointer {
4087     TemplateArgumentLoc Arg;
4088 
4089   public:
4090     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4091 
4092     const TemplateArgumentLoc *operator->() const { return &Arg; }
4093   };
4094 
4095   TemplateArgumentLocInventIterator() { }
4096 
4097   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4098                                              InputIterator Iter)
4099     : Self(Self), Iter(Iter) { }
4100 
4101   TemplateArgumentLocInventIterator &operator++() {
4102     ++Iter;
4103     return *this;
4104   }
4105 
4106   TemplateArgumentLocInventIterator operator++(int) {
4107     TemplateArgumentLocInventIterator Old(*this);
4108     ++(*this);
4109     return Old;
4110   }
4111 
4112   reference operator*() const {
4113     TemplateArgumentLoc Result;
4114     Self.InventTemplateArgumentLoc(*Iter, Result);
4115     return Result;
4116   }
4117 
4118   pointer operator->() const { return pointer(**this); }
4119 
4120   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4121                          const TemplateArgumentLocInventIterator &Y) {
4122     return X.Iter == Y.Iter;
4123   }
4124 
4125   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4126                          const TemplateArgumentLocInventIterator &Y) {
4127     return X.Iter != Y.Iter;
4128   }
4129 };
4130 
4131 template<typename Derived>
4132 template<typename InputIterator>
4133 bool TreeTransform<Derived>::TransformTemplateArguments(
4134     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4135     bool Uneval) {
4136   for (; First != Last; ++First) {
4137     TemplateArgumentLoc Out;
4138     TemplateArgumentLoc In = *First;
4139 
4140     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4141       // Unpack argument packs, which we translate them into separate
4142       // arguments.
4143       // FIXME: We could do much better if we could guarantee that the
4144       // TemplateArgumentLocInfo for the pack expansion would be usable for
4145       // all of the template arguments in the argument pack.
4146       typedef TemplateArgumentLocInventIterator<Derived,
4147                                                 TemplateArgument::pack_iterator>
4148         PackLocIterator;
4149       if (TransformTemplateArguments(PackLocIterator(*this,
4150                                                  In.getArgument().pack_begin()),
4151                                      PackLocIterator(*this,
4152                                                    In.getArgument().pack_end()),
4153                                      Outputs, Uneval))
4154         return true;
4155 
4156       continue;
4157     }
4158 
4159     if (In.getArgument().isPackExpansion()) {
4160       // We have a pack expansion, for which we will be substituting into
4161       // the pattern.
4162       SourceLocation Ellipsis;
4163       Optional<unsigned> OrigNumExpansions;
4164       TemplateArgumentLoc Pattern
4165         = getSema().getTemplateArgumentPackExpansionPattern(
4166               In, Ellipsis, OrigNumExpansions);
4167 
4168       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4169       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4170       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4171 
4172       // Determine whether the set of unexpanded parameter packs can and should
4173       // be expanded.
4174       bool Expand = true;
4175       bool RetainExpansion = false;
4176       Optional<unsigned> NumExpansions = OrigNumExpansions;
4177       if (getDerived().TryExpandParameterPacks(Ellipsis,
4178                                                Pattern.getSourceRange(),
4179                                                Unexpanded,
4180                                                Expand,
4181                                                RetainExpansion,
4182                                                NumExpansions))
4183         return true;
4184 
4185       if (!Expand) {
4186         // The transform has determined that we should perform a simple
4187         // transformation on the pack expansion, producing another pack
4188         // expansion.
4189         TemplateArgumentLoc OutPattern;
4190         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4191         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4192           return true;
4193 
4194         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4195                                                 NumExpansions);
4196         if (Out.getArgument().isNull())
4197           return true;
4198 
4199         Outputs.addArgument(Out);
4200         continue;
4201       }
4202 
4203       // The transform has determined that we should perform an elementwise
4204       // expansion of the pattern. Do so.
4205       for (unsigned I = 0; I != *NumExpansions; ++I) {
4206         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4207 
4208         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4209           return true;
4210 
4211         if (Out.getArgument().containsUnexpandedParameterPack()) {
4212           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4213                                                   OrigNumExpansions);
4214           if (Out.getArgument().isNull())
4215             return true;
4216         }
4217 
4218         Outputs.addArgument(Out);
4219       }
4220 
4221       // If we're supposed to retain a pack expansion, do so by temporarily
4222       // forgetting the partially-substituted parameter pack.
4223       if (RetainExpansion) {
4224         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4225 
4226         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4227           return true;
4228 
4229         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4230                                                 OrigNumExpansions);
4231         if (Out.getArgument().isNull())
4232           return true;
4233 
4234         Outputs.addArgument(Out);
4235       }
4236 
4237       continue;
4238     }
4239 
4240     // The simple case:
4241     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4242       return true;
4243 
4244     Outputs.addArgument(Out);
4245   }
4246 
4247   return false;
4248 
4249 }
4250 
4251 //===----------------------------------------------------------------------===//
4252 // Type transformation
4253 //===----------------------------------------------------------------------===//
4254 
4255 template<typename Derived>
4256 QualType TreeTransform<Derived>::TransformType(QualType T) {
4257   if (getDerived().AlreadyTransformed(T))
4258     return T;
4259 
4260   // Temporary workaround.  All of these transformations should
4261   // eventually turn into transformations on TypeLocs.
4262   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4263                                                 getDerived().getBaseLocation());
4264 
4265   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4266 
4267   if (!NewDI)
4268     return QualType();
4269 
4270   return NewDI->getType();
4271 }
4272 
4273 template<typename Derived>
4274 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4275   // Refine the base location to the type's location.
4276   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4277                        getDerived().getBaseEntity());
4278   if (getDerived().AlreadyTransformed(DI->getType()))
4279     return DI;
4280 
4281   TypeLocBuilder TLB;
4282 
4283   TypeLoc TL = DI->getTypeLoc();
4284   TLB.reserve(TL.getFullDataSize());
4285 
4286   QualType Result = getDerived().TransformType(TLB, TL);
4287   if (Result.isNull())
4288     return nullptr;
4289 
4290   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4291 }
4292 
4293 template<typename Derived>
4294 QualType
4295 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4296   switch (T.getTypeLocClass()) {
4297 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4298 #define TYPELOC(CLASS, PARENT)                                                 \
4299   case TypeLoc::CLASS:                                                         \
4300     return getDerived().Transform##CLASS##Type(TLB,                            \
4301                                                T.castAs<CLASS##TypeLoc>());
4302 #include "clang/AST/TypeLocNodes.def"
4303   }
4304 
4305   llvm_unreachable("unhandled type loc!");
4306 }
4307 
4308 template<typename Derived>
4309 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4310   if (!isa<DependentNameType>(T))
4311     return TransformType(T);
4312 
4313   if (getDerived().AlreadyTransformed(T))
4314     return T;
4315   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4316                                                 getDerived().getBaseLocation());
4317   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4318   return NewDI ? NewDI->getType() : QualType();
4319 }
4320 
4321 template<typename Derived>
4322 TypeSourceInfo *
4323 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4324   if (!isa<DependentNameType>(DI->getType()))
4325     return TransformType(DI);
4326 
4327   // Refine the base location to the type's location.
4328   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4329                        getDerived().getBaseEntity());
4330   if (getDerived().AlreadyTransformed(DI->getType()))
4331     return DI;
4332 
4333   TypeLocBuilder TLB;
4334 
4335   TypeLoc TL = DI->getTypeLoc();
4336   TLB.reserve(TL.getFullDataSize());
4337 
4338   auto QTL = TL.getAs<QualifiedTypeLoc>();
4339   if (QTL)
4340     TL = QTL.getUnqualifiedLoc();
4341 
4342   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4343 
4344   QualType Result = getDerived().TransformDependentNameType(
4345       TLB, DNTL, /*DeducedTSTContext*/true);
4346   if (Result.isNull())
4347     return nullptr;
4348 
4349   if (QTL) {
4350     Result = getDerived().RebuildQualifiedType(Result, QTL);
4351     if (Result.isNull())
4352       return nullptr;
4353     TLB.TypeWasModifiedSafely(Result);
4354   }
4355 
4356   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4357 }
4358 
4359 template<typename Derived>
4360 QualType
4361 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4362                                                QualifiedTypeLoc T) {
4363   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4364   if (Result.isNull())
4365     return QualType();
4366 
4367   Result = getDerived().RebuildQualifiedType(Result, T);
4368 
4369   if (Result.isNull())
4370     return QualType();
4371 
4372   // RebuildQualifiedType might have updated the type, but not in a way
4373   // that invalidates the TypeLoc. (There's no location information for
4374   // qualifiers.)
4375   TLB.TypeWasModifiedSafely(Result);
4376 
4377   return Result;
4378 }
4379 
4380 template <typename Derived>
4381 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4382                                                       QualifiedTypeLoc TL) {
4383 
4384   SourceLocation Loc = TL.getBeginLoc();
4385   Qualifiers Quals = TL.getType().getLocalQualifiers();
4386 
4387   if (((T.getAddressSpace() != LangAS::Default &&
4388         Quals.getAddressSpace() != LangAS::Default)) &&
4389       T.getAddressSpace() != Quals.getAddressSpace()) {
4390     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4391         << TL.getType() << T;
4392     return QualType();
4393   }
4394 
4395   // C++ [dcl.fct]p7:
4396   //   [When] adding cv-qualifications on top of the function type [...] the
4397   //   cv-qualifiers are ignored.
4398   if (T->isFunctionType()) {
4399     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4400                                                      Quals.getAddressSpace());
4401     return T;
4402   }
4403 
4404   // C++ [dcl.ref]p1:
4405   //   when the cv-qualifiers are introduced through the use of a typedef-name
4406   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4407   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4408   // applied to a reference type.
4409   if (T->isReferenceType()) {
4410     // The only qualifier that applies to a reference type is restrict.
4411     if (!Quals.hasRestrict())
4412       return T;
4413     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4414   }
4415 
4416   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4417   // resulting type.
4418   if (Quals.hasObjCLifetime()) {
4419     if (!T->isObjCLifetimeType() && !T->isDependentType())
4420       Quals.removeObjCLifetime();
4421     else if (T.getObjCLifetime()) {
4422       // Objective-C ARC:
4423       //   A lifetime qualifier applied to a substituted template parameter
4424       //   overrides the lifetime qualifier from the template argument.
4425       const AutoType *AutoTy;
4426       if (const SubstTemplateTypeParmType *SubstTypeParam
4427                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4428         QualType Replacement = SubstTypeParam->getReplacementType();
4429         Qualifiers Qs = Replacement.getQualifiers();
4430         Qs.removeObjCLifetime();
4431         Replacement = SemaRef.Context.getQualifiedType(
4432             Replacement.getUnqualifiedType(), Qs);
4433         T = SemaRef.Context.getSubstTemplateTypeParmType(
4434             SubstTypeParam->getReplacedParameter(), Replacement);
4435       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4436         // 'auto' types behave the same way as template parameters.
4437         QualType Deduced = AutoTy->getDeducedType();
4438         Qualifiers Qs = Deduced.getQualifiers();
4439         Qs.removeObjCLifetime();
4440         Deduced =
4441             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4442         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4443                                         AutoTy->isDependentType());
4444       } else {
4445         // Otherwise, complain about the addition of a qualifier to an
4446         // already-qualified type.
4447         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4448         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4449         Quals.removeObjCLifetime();
4450       }
4451     }
4452   }
4453 
4454   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4455 }
4456 
4457 template<typename Derived>
4458 TypeLoc
4459 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4460                                                    QualType ObjectType,
4461                                                    NamedDecl *UnqualLookup,
4462                                                    CXXScopeSpec &SS) {
4463   if (getDerived().AlreadyTransformed(TL.getType()))
4464     return TL;
4465 
4466   TypeSourceInfo *TSI =
4467       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4468   if (TSI)
4469     return TSI->getTypeLoc();
4470   return TypeLoc();
4471 }
4472 
4473 template<typename Derived>
4474 TypeSourceInfo *
4475 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4476                                                    QualType ObjectType,
4477                                                    NamedDecl *UnqualLookup,
4478                                                    CXXScopeSpec &SS) {
4479   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4480     return TSInfo;
4481 
4482   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4483                                    UnqualLookup, SS);
4484 }
4485 
4486 template <typename Derived>
4487 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4488     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4489     CXXScopeSpec &SS) {
4490   QualType T = TL.getType();
4491   assert(!getDerived().AlreadyTransformed(T));
4492 
4493   TypeLocBuilder TLB;
4494   QualType Result;
4495 
4496   if (isa<TemplateSpecializationType>(T)) {
4497     TemplateSpecializationTypeLoc SpecTL =
4498         TL.castAs<TemplateSpecializationTypeLoc>();
4499 
4500     TemplateName Template = getDerived().TransformTemplateName(
4501         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4502         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4503     if (Template.isNull())
4504       return nullptr;
4505 
4506     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4507                                                               Template);
4508   } else if (isa<DependentTemplateSpecializationType>(T)) {
4509     DependentTemplateSpecializationTypeLoc SpecTL =
4510         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4511 
4512     TemplateName Template
4513       = getDerived().RebuildTemplateName(SS,
4514                                          SpecTL.getTemplateKeywordLoc(),
4515                                          *SpecTL.getTypePtr()->getIdentifier(),
4516                                          SpecTL.getTemplateNameLoc(),
4517                                          ObjectType, UnqualLookup,
4518                                          /*AllowInjectedClassName*/true);
4519     if (Template.isNull())
4520       return nullptr;
4521 
4522     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4523                                                                        SpecTL,
4524                                                                        Template,
4525                                                                        SS);
4526   } else {
4527     // Nothing special needs to be done for these.
4528     Result = getDerived().TransformType(TLB, TL);
4529   }
4530 
4531   if (Result.isNull())
4532     return nullptr;
4533 
4534   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4535 }
4536 
4537 template <class TyLoc> static inline
4538 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4539   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4540   NewT.setNameLoc(T.getNameLoc());
4541   return T.getType();
4542 }
4543 
4544 template<typename Derived>
4545 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4546                                                       BuiltinTypeLoc T) {
4547   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4548   NewT.setBuiltinLoc(T.getBuiltinLoc());
4549   if (T.needsExtraLocalData())
4550     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4551   return T.getType();
4552 }
4553 
4554 template<typename Derived>
4555 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4556                                                       ComplexTypeLoc T) {
4557   // FIXME: recurse?
4558   return TransformTypeSpecType(TLB, T);
4559 }
4560 
4561 template <typename Derived>
4562 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4563                                                        AdjustedTypeLoc TL) {
4564   // Adjustments applied during transformation are handled elsewhere.
4565   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4566 }
4567 
4568 template<typename Derived>
4569 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4570                                                       DecayedTypeLoc TL) {
4571   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4572   if (OriginalType.isNull())
4573     return QualType();
4574 
4575   QualType Result = TL.getType();
4576   if (getDerived().AlwaysRebuild() ||
4577       OriginalType != TL.getOriginalLoc().getType())
4578     Result = SemaRef.Context.getDecayedType(OriginalType);
4579   TLB.push<DecayedTypeLoc>(Result);
4580   // Nothing to set for DecayedTypeLoc.
4581   return Result;
4582 }
4583 
4584 template<typename Derived>
4585 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4586                                                       PointerTypeLoc TL) {
4587   QualType PointeeType
4588     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4589   if (PointeeType.isNull())
4590     return QualType();
4591 
4592   QualType Result = TL.getType();
4593   if (PointeeType->getAs<ObjCObjectType>()) {
4594     // A dependent pointer type 'T *' has is being transformed such
4595     // that an Objective-C class type is being replaced for 'T'. The
4596     // resulting pointer type is an ObjCObjectPointerType, not a
4597     // PointerType.
4598     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4599 
4600     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4601     NewT.setStarLoc(TL.getStarLoc());
4602     return Result;
4603   }
4604 
4605   if (getDerived().AlwaysRebuild() ||
4606       PointeeType != TL.getPointeeLoc().getType()) {
4607     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4608     if (Result.isNull())
4609       return QualType();
4610   }
4611 
4612   // Objective-C ARC can add lifetime qualifiers to the type that we're
4613   // pointing to.
4614   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4615 
4616   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4617   NewT.setSigilLoc(TL.getSigilLoc());
4618   return Result;
4619 }
4620 
4621 template<typename Derived>
4622 QualType
4623 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4624                                                   BlockPointerTypeLoc TL) {
4625   QualType PointeeType
4626     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4627   if (PointeeType.isNull())
4628     return QualType();
4629 
4630   QualType Result = TL.getType();
4631   if (getDerived().AlwaysRebuild() ||
4632       PointeeType != TL.getPointeeLoc().getType()) {
4633     Result = getDerived().RebuildBlockPointerType(PointeeType,
4634                                                   TL.getSigilLoc());
4635     if (Result.isNull())
4636       return QualType();
4637   }
4638 
4639   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4640   NewT.setSigilLoc(TL.getSigilLoc());
4641   return Result;
4642 }
4643 
4644 /// Transforms a reference type.  Note that somewhat paradoxically we
4645 /// don't care whether the type itself is an l-value type or an r-value
4646 /// type;  we only care if the type was *written* as an l-value type
4647 /// or an r-value type.
4648 template<typename Derived>
4649 QualType
4650 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4651                                                ReferenceTypeLoc TL) {
4652   const ReferenceType *T = TL.getTypePtr();
4653 
4654   // Note that this works with the pointee-as-written.
4655   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4656   if (PointeeType.isNull())
4657     return QualType();
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>::TransformOMPParallelMasterDirective(
8050     OMPParallelMasterDirective *D) {
8051   DeclarationNameInfo DirName;
8052   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, 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 TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8061     OMPParallelSectionsDirective *D) {
8062   DeclarationNameInfo DirName;
8063   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8064                                              nullptr, 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
8072 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8073   DeclarationNameInfo DirName;
8074   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, 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 TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8083     OMPTaskyieldDirective *D) {
8084   DeclarationNameInfo DirName;
8085   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, 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>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8095   DeclarationNameInfo DirName;
8096   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8097                                              D->getBeginLoc());
8098   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8099   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8100   return Res;
8101 }
8102 
8103 template <typename Derived>
8104 StmtResult
8105 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8106   DeclarationNameInfo DirName;
8107   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, 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 TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8116     OMPTaskgroupDirective *D) {
8117   DeclarationNameInfo DirName;
8118   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, 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>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8128   DeclarationNameInfo DirName;
8129   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, 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>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8139   DeclarationNameInfo DirName;
8140   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, 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>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8150   DeclarationNameInfo DirName;
8151   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, 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
8160 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8161   DeclarationNameInfo DirName;
8162   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, 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>::TransformOMPTargetDataDirective(
8171     OMPTargetDataDirective *D) {
8172   DeclarationNameInfo DirName;
8173   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8174                                              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>::TransformOMPTargetEnterDataDirective(
8182     OMPTargetEnterDataDirective *D) {
8183   DeclarationNameInfo DirName;
8184   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_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>::TransformOMPTargetExitDataDirective(
8193     OMPTargetExitDataDirective *D) {
8194   DeclarationNameInfo DirName;
8195   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, 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>::TransformOMPTargetParallelDirective(
8204     OMPTargetParallelDirective *D) {
8205   DeclarationNameInfo DirName;
8206   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, 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>::TransformOMPTargetParallelForDirective(
8215     OMPTargetParallelForDirective *D) {
8216   DeclarationNameInfo DirName;
8217   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, 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 TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8226     OMPTargetUpdateDirective *D) {
8227   DeclarationNameInfo DirName;
8228   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8229                                              nullptr, 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
8237 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8238   DeclarationNameInfo DirName;
8239   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8240                                              D->getBeginLoc());
8241   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8242   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8243   return Res;
8244 }
8245 
8246 template <typename Derived>
8247 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8248     OMPCancellationPointDirective *D) {
8249   DeclarationNameInfo DirName;
8250   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8251                                              nullptr, 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>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8260   DeclarationNameInfo DirName;
8261   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, 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
8270 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8271   DeclarationNameInfo DirName;
8272   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8273                                              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>::TransformOMPTaskLoopSimdDirective(
8281     OMPTaskLoopSimdDirective *D) {
8282   DeclarationNameInfo DirName;
8283   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, 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>::TransformOMPMasterTaskLoopDirective(
8292     OMPMasterTaskLoopDirective *D) {
8293   DeclarationNameInfo DirName;
8294   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, 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>::TransformOMPMasterTaskLoopSimdDirective(
8303     OMPMasterTaskLoopSimdDirective *D) {
8304   DeclarationNameInfo DirName;
8305   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8306                                              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 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8314     OMPParallelMasterTaskLoopDirective *D) {
8315   DeclarationNameInfo DirName;
8316   getDerived().getSema().StartOpenMPDSABlock(
8317       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
8318   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8319   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8320   return Res;
8321 }
8322 
8323 template <typename Derived>
8324 StmtResult
8325 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
8326     OMPParallelMasterTaskLoopSimdDirective *D) {
8327   DeclarationNameInfo DirName;
8328   getDerived().getSema().StartOpenMPDSABlock(
8329       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
8330   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8331   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8332   return Res;
8333 }
8334 
8335 template <typename Derived>
8336 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8337     OMPDistributeDirective *D) {
8338   DeclarationNameInfo DirName;
8339   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8340                                              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 TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8348     OMPDistributeParallelForDirective *D) {
8349   DeclarationNameInfo DirName;
8350   getDerived().getSema().StartOpenMPDSABlock(
8351       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8352   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8353   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8354   return Res;
8355 }
8356 
8357 template <typename Derived>
8358 StmtResult
8359 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8360     OMPDistributeParallelForSimdDirective *D) {
8361   DeclarationNameInfo DirName;
8362   getDerived().getSema().StartOpenMPDSABlock(
8363       OMPD_distribute_parallel_for_simd, DirName, 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>::TransformOMPDistributeSimdDirective(
8371     OMPDistributeSimdDirective *D) {
8372   DeclarationNameInfo DirName;
8373   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8374                                              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>::TransformOMPTargetParallelForSimdDirective(
8382     OMPTargetParallelForSimdDirective *D) {
8383   DeclarationNameInfo DirName;
8384   getDerived().getSema().StartOpenMPDSABlock(
8385       OMPD_target_parallel_for_simd, DirName, nullptr, 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>::TransformOMPTargetSimdDirective(
8393     OMPTargetSimdDirective *D) {
8394   DeclarationNameInfo DirName;
8395   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8396                                              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>::TransformOMPTeamsDistributeDirective(
8404     OMPTeamsDistributeDirective *D) {
8405   DeclarationNameInfo DirName;
8406   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8407                                              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>::TransformOMPTeamsDistributeSimdDirective(
8415     OMPTeamsDistributeSimdDirective *D) {
8416   DeclarationNameInfo DirName;
8417   getDerived().getSema().StartOpenMPDSABlock(
8418       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8419   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8420   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8421   return Res;
8422 }
8423 
8424 template <typename Derived>
8425 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8426     OMPTeamsDistributeParallelForSimdDirective *D) {
8427   DeclarationNameInfo DirName;
8428   getDerived().getSema().StartOpenMPDSABlock(
8429       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8430       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>::TransformOMPTeamsDistributeParallelForDirective(
8438     OMPTeamsDistributeParallelForDirective *D) {
8439   DeclarationNameInfo DirName;
8440   getDerived().getSema().StartOpenMPDSABlock(
8441       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8442   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8443   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8444   return Res;
8445 }
8446 
8447 template <typename Derived>
8448 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8449     OMPTargetTeamsDirective *D) {
8450   DeclarationNameInfo DirName;
8451   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8452                                              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 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8460     OMPTargetTeamsDistributeDirective *D) {
8461   DeclarationNameInfo DirName;
8462   getDerived().getSema().StartOpenMPDSABlock(
8463       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8464   auto Res = getDerived().TransformOMPExecutableDirective(D);
8465   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8466   return Res;
8467 }
8468 
8469 template <typename Derived>
8470 StmtResult
8471 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8472     OMPTargetTeamsDistributeParallelForDirective *D) {
8473   DeclarationNameInfo DirName;
8474   getDerived().getSema().StartOpenMPDSABlock(
8475       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8476       D->getBeginLoc());
8477   auto Res = getDerived().TransformOMPExecutableDirective(D);
8478   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8479   return Res;
8480 }
8481 
8482 template <typename Derived>
8483 StmtResult TreeTransform<Derived>::
8484     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8485         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8486   DeclarationNameInfo DirName;
8487   getDerived().getSema().StartOpenMPDSABlock(
8488       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8489       D->getBeginLoc());
8490   auto Res = getDerived().TransformOMPExecutableDirective(D);
8491   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8492   return Res;
8493 }
8494 
8495 template <typename Derived>
8496 StmtResult
8497 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8498     OMPTargetTeamsDistributeSimdDirective *D) {
8499   DeclarationNameInfo DirName;
8500   getDerived().getSema().StartOpenMPDSABlock(
8501       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8502   auto Res = getDerived().TransformOMPExecutableDirective(D);
8503   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8504   return Res;
8505 }
8506 
8507 
8508 //===----------------------------------------------------------------------===//
8509 // OpenMP clause transformation
8510 //===----------------------------------------------------------------------===//
8511 template <typename Derived>
8512 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8513   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8514   if (Cond.isInvalid())
8515     return nullptr;
8516   return getDerived().RebuildOMPIfClause(
8517       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8518       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8519 }
8520 
8521 template <typename Derived>
8522 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8523   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8524   if (Cond.isInvalid())
8525     return nullptr;
8526   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8527                                             C->getLParenLoc(), C->getEndLoc());
8528 }
8529 
8530 template <typename Derived>
8531 OMPClause *
8532 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8533   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8534   if (NumThreads.isInvalid())
8535     return nullptr;
8536   return getDerived().RebuildOMPNumThreadsClause(
8537       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8538 }
8539 
8540 template <typename Derived>
8541 OMPClause *
8542 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8543   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8544   if (E.isInvalid())
8545     return nullptr;
8546   return getDerived().RebuildOMPSafelenClause(
8547       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8548 }
8549 
8550 template <typename Derived>
8551 OMPClause *
8552 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8553   ExprResult E = getDerived().TransformExpr(C->getAllocator());
8554   if (E.isInvalid())
8555     return nullptr;
8556   return getDerived().RebuildOMPAllocatorClause(
8557       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8558 }
8559 
8560 template <typename Derived>
8561 OMPClause *
8562 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8563   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8564   if (E.isInvalid())
8565     return nullptr;
8566   return getDerived().RebuildOMPSimdlenClause(
8567       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8568 }
8569 
8570 template <typename Derived>
8571 OMPClause *
8572 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8573   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8574   if (E.isInvalid())
8575     return nullptr;
8576   return getDerived().RebuildOMPCollapseClause(
8577       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8578 }
8579 
8580 template <typename Derived>
8581 OMPClause *
8582 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8583   return getDerived().RebuildOMPDefaultClause(
8584       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8585       C->getLParenLoc(), C->getEndLoc());
8586 }
8587 
8588 template <typename Derived>
8589 OMPClause *
8590 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8591   return getDerived().RebuildOMPProcBindClause(
8592       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8593       C->getLParenLoc(), C->getEndLoc());
8594 }
8595 
8596 template <typename Derived>
8597 OMPClause *
8598 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8599   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8600   if (E.isInvalid())
8601     return nullptr;
8602   return getDerived().RebuildOMPScheduleClause(
8603       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8604       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8605       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8606       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8607 }
8608 
8609 template <typename Derived>
8610 OMPClause *
8611 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8612   ExprResult E;
8613   if (auto *Num = C->getNumForLoops()) {
8614     E = getDerived().TransformExpr(Num);
8615     if (E.isInvalid())
8616       return nullptr;
8617   }
8618   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8619                                               C->getLParenLoc(), E.get());
8620 }
8621 
8622 template <typename Derived>
8623 OMPClause *
8624 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8625   // No need to rebuild this clause, no template-dependent parameters.
8626   return C;
8627 }
8628 
8629 template <typename Derived>
8630 OMPClause *
8631 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8632   // No need to rebuild this clause, no template-dependent parameters.
8633   return C;
8634 }
8635 
8636 template <typename Derived>
8637 OMPClause *
8638 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8639   // No need to rebuild this clause, no template-dependent parameters.
8640   return C;
8641 }
8642 
8643 template <typename Derived>
8644 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8645   // No need to rebuild this clause, no template-dependent parameters.
8646   return C;
8647 }
8648 
8649 template <typename Derived>
8650 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8651   // No need to rebuild this clause, no template-dependent parameters.
8652   return C;
8653 }
8654 
8655 template <typename Derived>
8656 OMPClause *
8657 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8658   // No need to rebuild this clause, no template-dependent parameters.
8659   return C;
8660 }
8661 
8662 template <typename Derived>
8663 OMPClause *
8664 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8665   // No need to rebuild this clause, no template-dependent parameters.
8666   return C;
8667 }
8668 
8669 template <typename Derived>
8670 OMPClause *
8671 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8672   // No need to rebuild this clause, no template-dependent parameters.
8673   return C;
8674 }
8675 
8676 template <typename Derived>
8677 OMPClause *
8678 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8679   // No need to rebuild this clause, no template-dependent parameters.
8680   return C;
8681 }
8682 
8683 template <typename Derived>
8684 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8685   // No need to rebuild this clause, no template-dependent parameters.
8686   return C;
8687 }
8688 
8689 template <typename Derived>
8690 OMPClause *
8691 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8692   // No need to rebuild this clause, no template-dependent parameters.
8693   return C;
8694 }
8695 
8696 template <typename Derived>
8697 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8698     OMPUnifiedAddressClause *C) {
8699   llvm_unreachable("unified_address clause cannot appear in dependent context");
8700 }
8701 
8702 template <typename Derived>
8703 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8704     OMPUnifiedSharedMemoryClause *C) {
8705   llvm_unreachable(
8706       "unified_shared_memory clause cannot appear in dependent context");
8707 }
8708 
8709 template <typename Derived>
8710 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8711     OMPReverseOffloadClause *C) {
8712   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8713 }
8714 
8715 template <typename Derived>
8716 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8717     OMPDynamicAllocatorsClause *C) {
8718   llvm_unreachable(
8719       "dynamic_allocators clause cannot appear in dependent context");
8720 }
8721 
8722 template <typename Derived>
8723 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8724     OMPAtomicDefaultMemOrderClause *C) {
8725   llvm_unreachable(
8726       "atomic_default_mem_order clause cannot appear in dependent context");
8727 }
8728 
8729 template <typename Derived>
8730 OMPClause *
8731 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8732   llvm::SmallVector<Expr *, 16> Vars;
8733   Vars.reserve(C->varlist_size());
8734   for (auto *VE : C->varlists()) {
8735     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8736     if (EVar.isInvalid())
8737       return nullptr;
8738     Vars.push_back(EVar.get());
8739   }
8740   return getDerived().RebuildOMPPrivateClause(
8741       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8742 }
8743 
8744 template <typename Derived>
8745 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8746     OMPFirstprivateClause *C) {
8747   llvm::SmallVector<Expr *, 16> Vars;
8748   Vars.reserve(C->varlist_size());
8749   for (auto *VE : C->varlists()) {
8750     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8751     if (EVar.isInvalid())
8752       return nullptr;
8753     Vars.push_back(EVar.get());
8754   }
8755   return getDerived().RebuildOMPFirstprivateClause(
8756       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8757 }
8758 
8759 template <typename Derived>
8760 OMPClause *
8761 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8762   llvm::SmallVector<Expr *, 16> Vars;
8763   Vars.reserve(C->varlist_size());
8764   for (auto *VE : C->varlists()) {
8765     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8766     if (EVar.isInvalid())
8767       return nullptr;
8768     Vars.push_back(EVar.get());
8769   }
8770   return getDerived().RebuildOMPLastprivateClause(
8771       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8772 }
8773 
8774 template <typename Derived>
8775 OMPClause *
8776 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8777   llvm::SmallVector<Expr *, 16> Vars;
8778   Vars.reserve(C->varlist_size());
8779   for (auto *VE : C->varlists()) {
8780     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8781     if (EVar.isInvalid())
8782       return nullptr;
8783     Vars.push_back(EVar.get());
8784   }
8785   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8786                                              C->getLParenLoc(), C->getEndLoc());
8787 }
8788 
8789 template <typename Derived>
8790 OMPClause *
8791 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8792   llvm::SmallVector<Expr *, 16> Vars;
8793   Vars.reserve(C->varlist_size());
8794   for (auto *VE : C->varlists()) {
8795     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8796     if (EVar.isInvalid())
8797       return nullptr;
8798     Vars.push_back(EVar.get());
8799   }
8800   CXXScopeSpec ReductionIdScopeSpec;
8801   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8802 
8803   DeclarationNameInfo NameInfo = C->getNameInfo();
8804   if (NameInfo.getName()) {
8805     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8806     if (!NameInfo.getName())
8807       return nullptr;
8808   }
8809   // Build a list of all UDR decls with the same names ranged by the Scopes.
8810   // The Scope boundary is a duplication of the previous decl.
8811   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8812   for (auto *E : C->reduction_ops()) {
8813     // Transform all the decls.
8814     if (E) {
8815       auto *ULE = cast<UnresolvedLookupExpr>(E);
8816       UnresolvedSet<8> Decls;
8817       for (auto *D : ULE->decls()) {
8818         NamedDecl *InstD =
8819             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8820         Decls.addDecl(InstD, InstD->getAccess());
8821       }
8822       UnresolvedReductions.push_back(
8823        UnresolvedLookupExpr::Create(
8824           SemaRef.Context, /*NamingClass=*/nullptr,
8825           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8826           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8827           Decls.begin(), Decls.end()));
8828     } else
8829       UnresolvedReductions.push_back(nullptr);
8830   }
8831   return getDerived().RebuildOMPReductionClause(
8832       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8833       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8834 }
8835 
8836 template <typename Derived>
8837 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8838     OMPTaskReductionClause *C) {
8839   llvm::SmallVector<Expr *, 16> Vars;
8840   Vars.reserve(C->varlist_size());
8841   for (auto *VE : C->varlists()) {
8842     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8843     if (EVar.isInvalid())
8844       return nullptr;
8845     Vars.push_back(EVar.get());
8846   }
8847   CXXScopeSpec ReductionIdScopeSpec;
8848   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8849 
8850   DeclarationNameInfo NameInfo = C->getNameInfo();
8851   if (NameInfo.getName()) {
8852     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8853     if (!NameInfo.getName())
8854       return nullptr;
8855   }
8856   // Build a list of all UDR decls with the same names ranged by the Scopes.
8857   // The Scope boundary is a duplication of the previous decl.
8858   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8859   for (auto *E : C->reduction_ops()) {
8860     // Transform all the decls.
8861     if (E) {
8862       auto *ULE = cast<UnresolvedLookupExpr>(E);
8863       UnresolvedSet<8> Decls;
8864       for (auto *D : ULE->decls()) {
8865         NamedDecl *InstD =
8866             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8867         Decls.addDecl(InstD, InstD->getAccess());
8868       }
8869       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8870           SemaRef.Context, /*NamingClass=*/nullptr,
8871           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8872           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8873     } else
8874       UnresolvedReductions.push_back(nullptr);
8875   }
8876   return getDerived().RebuildOMPTaskReductionClause(
8877       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8878       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8879 }
8880 
8881 template <typename Derived>
8882 OMPClause *
8883 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8884   llvm::SmallVector<Expr *, 16> Vars;
8885   Vars.reserve(C->varlist_size());
8886   for (auto *VE : C->varlists()) {
8887     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8888     if (EVar.isInvalid())
8889       return nullptr;
8890     Vars.push_back(EVar.get());
8891   }
8892   CXXScopeSpec ReductionIdScopeSpec;
8893   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8894 
8895   DeclarationNameInfo NameInfo = C->getNameInfo();
8896   if (NameInfo.getName()) {
8897     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8898     if (!NameInfo.getName())
8899       return nullptr;
8900   }
8901   // Build a list of all UDR decls with the same names ranged by the Scopes.
8902   // The Scope boundary is a duplication of the previous decl.
8903   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8904   for (auto *E : C->reduction_ops()) {
8905     // Transform all the decls.
8906     if (E) {
8907       auto *ULE = cast<UnresolvedLookupExpr>(E);
8908       UnresolvedSet<8> Decls;
8909       for (auto *D : ULE->decls()) {
8910         NamedDecl *InstD =
8911             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8912         Decls.addDecl(InstD, InstD->getAccess());
8913       }
8914       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8915           SemaRef.Context, /*NamingClass=*/nullptr,
8916           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8917           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8918     } else
8919       UnresolvedReductions.push_back(nullptr);
8920   }
8921   return getDerived().RebuildOMPInReductionClause(
8922       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8923       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8924 }
8925 
8926 template <typename Derived>
8927 OMPClause *
8928 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8929   llvm::SmallVector<Expr *, 16> Vars;
8930   Vars.reserve(C->varlist_size());
8931   for (auto *VE : C->varlists()) {
8932     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8933     if (EVar.isInvalid())
8934       return nullptr;
8935     Vars.push_back(EVar.get());
8936   }
8937   ExprResult Step = getDerived().TransformExpr(C->getStep());
8938   if (Step.isInvalid())
8939     return nullptr;
8940   return getDerived().RebuildOMPLinearClause(
8941       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8942       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8943 }
8944 
8945 template <typename Derived>
8946 OMPClause *
8947 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8948   llvm::SmallVector<Expr *, 16> Vars;
8949   Vars.reserve(C->varlist_size());
8950   for (auto *VE : C->varlists()) {
8951     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8952     if (EVar.isInvalid())
8953       return nullptr;
8954     Vars.push_back(EVar.get());
8955   }
8956   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8957   if (Alignment.isInvalid())
8958     return nullptr;
8959   return getDerived().RebuildOMPAlignedClause(
8960       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8961       C->getColonLoc(), C->getEndLoc());
8962 }
8963 
8964 template <typename Derived>
8965 OMPClause *
8966 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8967   llvm::SmallVector<Expr *, 16> Vars;
8968   Vars.reserve(C->varlist_size());
8969   for (auto *VE : C->varlists()) {
8970     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8971     if (EVar.isInvalid())
8972       return nullptr;
8973     Vars.push_back(EVar.get());
8974   }
8975   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8976                                              C->getLParenLoc(), C->getEndLoc());
8977 }
8978 
8979 template <typename Derived>
8980 OMPClause *
8981 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8982   llvm::SmallVector<Expr *, 16> Vars;
8983   Vars.reserve(C->varlist_size());
8984   for (auto *VE : C->varlists()) {
8985     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8986     if (EVar.isInvalid())
8987       return nullptr;
8988     Vars.push_back(EVar.get());
8989   }
8990   return getDerived().RebuildOMPCopyprivateClause(
8991       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8992 }
8993 
8994 template <typename Derived>
8995 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8996   llvm::SmallVector<Expr *, 16> Vars;
8997   Vars.reserve(C->varlist_size());
8998   for (auto *VE : C->varlists()) {
8999     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9000     if (EVar.isInvalid())
9001       return nullptr;
9002     Vars.push_back(EVar.get());
9003   }
9004   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9005                                             C->getLParenLoc(), C->getEndLoc());
9006 }
9007 
9008 template <typename Derived>
9009 OMPClause *
9010 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9011   llvm::SmallVector<Expr *, 16> Vars;
9012   Vars.reserve(C->varlist_size());
9013   for (auto *VE : C->varlists()) {
9014     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9015     if (EVar.isInvalid())
9016       return nullptr;
9017     Vars.push_back(EVar.get());
9018   }
9019   return getDerived().RebuildOMPDependClause(
9020       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
9021       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9022 }
9023 
9024 template <typename Derived>
9025 OMPClause *
9026 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9027   ExprResult E = getDerived().TransformExpr(C->getDevice());
9028   if (E.isInvalid())
9029     return nullptr;
9030   return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
9031                                              C->getLParenLoc(), C->getEndLoc());
9032 }
9033 
9034 template <typename Derived, class T>
9035 bool transformOMPMappableExprListClause(
9036     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9037     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9038     DeclarationNameInfo &MapperIdInfo,
9039     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9040   // Transform expressions in the list.
9041   Vars.reserve(C->varlist_size());
9042   for (auto *VE : C->varlists()) {
9043     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9044     if (EVar.isInvalid())
9045       return true;
9046     Vars.push_back(EVar.get());
9047   }
9048   // Transform mapper scope specifier and identifier.
9049   NestedNameSpecifierLoc QualifierLoc;
9050   if (C->getMapperQualifierLoc()) {
9051     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9052         C->getMapperQualifierLoc());
9053     if (!QualifierLoc)
9054       return true;
9055   }
9056   MapperIdScopeSpec.Adopt(QualifierLoc);
9057   MapperIdInfo = C->getMapperIdInfo();
9058   if (MapperIdInfo.getName()) {
9059     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9060     if (!MapperIdInfo.getName())
9061       return true;
9062   }
9063   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9064   // the previous user-defined mapper lookup in dependent environment.
9065   for (auto *E : C->mapperlists()) {
9066     // Transform all the decls.
9067     if (E) {
9068       auto *ULE = cast<UnresolvedLookupExpr>(E);
9069       UnresolvedSet<8> Decls;
9070       for (auto *D : ULE->decls()) {
9071         NamedDecl *InstD =
9072             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9073         Decls.addDecl(InstD, InstD->getAccess());
9074       }
9075       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9076           TT.getSema().Context, /*NamingClass=*/nullptr,
9077           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9078           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9079           Decls.end()));
9080     } else {
9081       UnresolvedMappers.push_back(nullptr);
9082     }
9083   }
9084   return false;
9085 }
9086 
9087 template <typename Derived>
9088 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9089   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9090   llvm::SmallVector<Expr *, 16> Vars;
9091   CXXScopeSpec MapperIdScopeSpec;
9092   DeclarationNameInfo MapperIdInfo;
9093   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9094   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9095           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9096     return nullptr;
9097   return getDerived().RebuildOMPMapClause(
9098       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9099       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9100       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9101 }
9102 
9103 template <typename Derived>
9104 OMPClause *
9105 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9106   Expr *Allocator = C->getAllocator();
9107   if (Allocator) {
9108     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9109     if (AllocatorRes.isInvalid())
9110       return nullptr;
9111     Allocator = AllocatorRes.get();
9112   }
9113   llvm::SmallVector<Expr *, 16> Vars;
9114   Vars.reserve(C->varlist_size());
9115   for (auto *VE : C->varlists()) {
9116     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9117     if (EVar.isInvalid())
9118       return nullptr;
9119     Vars.push_back(EVar.get());
9120   }
9121   return getDerived().RebuildOMPAllocateClause(
9122       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9123       C->getEndLoc());
9124 }
9125 
9126 template <typename Derived>
9127 OMPClause *
9128 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9129   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9130   if (E.isInvalid())
9131     return nullptr;
9132   return getDerived().RebuildOMPNumTeamsClause(
9133       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9134 }
9135 
9136 template <typename Derived>
9137 OMPClause *
9138 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9139   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9140   if (E.isInvalid())
9141     return nullptr;
9142   return getDerived().RebuildOMPThreadLimitClause(
9143       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9144 }
9145 
9146 template <typename Derived>
9147 OMPClause *
9148 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9149   ExprResult E = getDerived().TransformExpr(C->getPriority());
9150   if (E.isInvalid())
9151     return nullptr;
9152   return getDerived().RebuildOMPPriorityClause(
9153       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9154 }
9155 
9156 template <typename Derived>
9157 OMPClause *
9158 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9159   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9160   if (E.isInvalid())
9161     return nullptr;
9162   return getDerived().RebuildOMPGrainsizeClause(
9163       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9164 }
9165 
9166 template <typename Derived>
9167 OMPClause *
9168 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9169   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9170   if (E.isInvalid())
9171     return nullptr;
9172   return getDerived().RebuildOMPNumTasksClause(
9173       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9174 }
9175 
9176 template <typename Derived>
9177 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9178   ExprResult E = getDerived().TransformExpr(C->getHint());
9179   if (E.isInvalid())
9180     return nullptr;
9181   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9182                                            C->getLParenLoc(), C->getEndLoc());
9183 }
9184 
9185 template <typename Derived>
9186 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9187     OMPDistScheduleClause *C) {
9188   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9189   if (E.isInvalid())
9190     return nullptr;
9191   return getDerived().RebuildOMPDistScheduleClause(
9192       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9193       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9194 }
9195 
9196 template <typename Derived>
9197 OMPClause *
9198 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9199   // Rebuild Defaultmap Clause since we need to invoke the checking of
9200   // defaultmap(none:variable-category) after template initialization.
9201   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
9202                                                  C->getDefaultmapKind(),
9203                                                  C->getBeginLoc(),
9204                                                  C->getLParenLoc(),
9205                                                  C->getDefaultmapModifierLoc(),
9206                                                  C->getDefaultmapKindLoc(),
9207                                                  C->getEndLoc());
9208 }
9209 
9210 template <typename Derived>
9211 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9212   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9213   llvm::SmallVector<Expr *, 16> Vars;
9214   CXXScopeSpec MapperIdScopeSpec;
9215   DeclarationNameInfo MapperIdInfo;
9216   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9217   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9218           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9219     return nullptr;
9220   return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9221                                          Locs, UnresolvedMappers);
9222 }
9223 
9224 template <typename Derived>
9225 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9226   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9227   llvm::SmallVector<Expr *, 16> Vars;
9228   CXXScopeSpec MapperIdScopeSpec;
9229   DeclarationNameInfo MapperIdInfo;
9230   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9231   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9232           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9233     return nullptr;
9234   return getDerived().RebuildOMPFromClause(
9235       Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9236 }
9237 
9238 template <typename Derived>
9239 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9240     OMPUseDevicePtrClause *C) {
9241   llvm::SmallVector<Expr *, 16> Vars;
9242   Vars.reserve(C->varlist_size());
9243   for (auto *VE : C->varlists()) {
9244     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9245     if (EVar.isInvalid())
9246       return nullptr;
9247     Vars.push_back(EVar.get());
9248   }
9249   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9250   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9251 }
9252 
9253 template <typename Derived>
9254 OMPClause *
9255 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9256   llvm::SmallVector<Expr *, 16> Vars;
9257   Vars.reserve(C->varlist_size());
9258   for (auto *VE : C->varlists()) {
9259     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9260     if (EVar.isInvalid())
9261       return nullptr;
9262     Vars.push_back(EVar.get());
9263   }
9264   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9265   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9266 }
9267 
9268 //===----------------------------------------------------------------------===//
9269 // Expression transformation
9270 //===----------------------------------------------------------------------===//
9271 template<typename Derived>
9272 ExprResult
9273 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9274   return TransformExpr(E->getSubExpr());
9275 }
9276 
9277 template<typename Derived>
9278 ExprResult
9279 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9280   if (!E->isTypeDependent())
9281     return E;
9282 
9283   return getDerived().RebuildPredefinedExpr(E->getLocation(),
9284                                             E->getIdentKind());
9285 }
9286 
9287 template<typename Derived>
9288 ExprResult
9289 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9290   NestedNameSpecifierLoc QualifierLoc;
9291   if (E->getQualifierLoc()) {
9292     QualifierLoc
9293       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9294     if (!QualifierLoc)
9295       return ExprError();
9296   }
9297 
9298   ValueDecl *ND
9299     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9300                                                          E->getDecl()));
9301   if (!ND)
9302     return ExprError();
9303 
9304   NamedDecl *Found = ND;
9305   if (E->getFoundDecl() != E->getDecl()) {
9306     Found = cast_or_null<NamedDecl>(
9307         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9308     if (!Found)
9309       return ExprError();
9310   }
9311 
9312   DeclarationNameInfo NameInfo = E->getNameInfo();
9313   if (NameInfo.getName()) {
9314     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9315     if (!NameInfo.getName())
9316       return ExprError();
9317   }
9318 
9319   if (!getDerived().AlwaysRebuild() &&
9320       QualifierLoc == E->getQualifierLoc() &&
9321       ND == E->getDecl() &&
9322       Found == E->getFoundDecl() &&
9323       NameInfo.getName() == E->getDecl()->getDeclName() &&
9324       !E->hasExplicitTemplateArgs()) {
9325 
9326     // Mark it referenced in the new context regardless.
9327     // FIXME: this is a bit instantiation-specific.
9328     SemaRef.MarkDeclRefReferenced(E);
9329 
9330     return E;
9331   }
9332 
9333   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9334   if (E->hasExplicitTemplateArgs()) {
9335     TemplateArgs = &TransArgs;
9336     TransArgs.setLAngleLoc(E->getLAngleLoc());
9337     TransArgs.setRAngleLoc(E->getRAngleLoc());
9338     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9339                                                 E->getNumTemplateArgs(),
9340                                                 TransArgs))
9341       return ExprError();
9342   }
9343 
9344   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9345                                          Found, TemplateArgs);
9346 }
9347 
9348 template<typename Derived>
9349 ExprResult
9350 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9351   return E;
9352 }
9353 
9354 template <typename Derived>
9355 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9356     FixedPointLiteral *E) {
9357   return E;
9358 }
9359 
9360 template<typename Derived>
9361 ExprResult
9362 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9363   return E;
9364 }
9365 
9366 template<typename Derived>
9367 ExprResult
9368 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9369   return E;
9370 }
9371 
9372 template<typename Derived>
9373 ExprResult
9374 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9375   return E;
9376 }
9377 
9378 template<typename Derived>
9379 ExprResult
9380 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9381   return E;
9382 }
9383 
9384 template<typename Derived>
9385 ExprResult
9386 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9387   if (FunctionDecl *FD = E->getDirectCallee())
9388     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9389   return SemaRef.MaybeBindToTemporary(E);
9390 }
9391 
9392 template<typename Derived>
9393 ExprResult
9394 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9395   ExprResult ControllingExpr =
9396     getDerived().TransformExpr(E->getControllingExpr());
9397   if (ControllingExpr.isInvalid())
9398     return ExprError();
9399 
9400   SmallVector<Expr *, 4> AssocExprs;
9401   SmallVector<TypeSourceInfo *, 4> AssocTypes;
9402   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
9403     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9404     if (TSI) {
9405       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9406       if (!AssocType)
9407         return ExprError();
9408       AssocTypes.push_back(AssocType);
9409     } else {
9410       AssocTypes.push_back(nullptr);
9411     }
9412 
9413     ExprResult AssocExpr =
9414         getDerived().TransformExpr(Assoc.getAssociationExpr());
9415     if (AssocExpr.isInvalid())
9416       return ExprError();
9417     AssocExprs.push_back(AssocExpr.get());
9418   }
9419 
9420   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9421                                                   E->getDefaultLoc(),
9422                                                   E->getRParenLoc(),
9423                                                   ControllingExpr.get(),
9424                                                   AssocTypes,
9425                                                   AssocExprs);
9426 }
9427 
9428 template<typename Derived>
9429 ExprResult
9430 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9431   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9432   if (SubExpr.isInvalid())
9433     return ExprError();
9434 
9435   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9436     return E;
9437 
9438   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9439                                        E->getRParen());
9440 }
9441 
9442 /// The operand of a unary address-of operator has special rules: it's
9443 /// allowed to refer to a non-static member of a class even if there's no 'this'
9444 /// object available.
9445 template<typename Derived>
9446 ExprResult
9447 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9448   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9449     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9450   else
9451     return getDerived().TransformExpr(E);
9452 }
9453 
9454 template<typename Derived>
9455 ExprResult
9456 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9457   ExprResult SubExpr;
9458   if (E->getOpcode() == UO_AddrOf)
9459     SubExpr = TransformAddressOfOperand(E->getSubExpr());
9460   else
9461     SubExpr = TransformExpr(E->getSubExpr());
9462   if (SubExpr.isInvalid())
9463     return ExprError();
9464 
9465   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9466     return E;
9467 
9468   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9469                                            E->getOpcode(),
9470                                            SubExpr.get());
9471 }
9472 
9473 template<typename Derived>
9474 ExprResult
9475 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9476   // Transform the type.
9477   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9478   if (!Type)
9479     return ExprError();
9480 
9481   // Transform all of the components into components similar to what the
9482   // parser uses.
9483   // FIXME: It would be slightly more efficient in the non-dependent case to
9484   // just map FieldDecls, rather than requiring the rebuilder to look for
9485   // the fields again. However, __builtin_offsetof is rare enough in
9486   // template code that we don't care.
9487   bool ExprChanged = false;
9488   typedef Sema::OffsetOfComponent Component;
9489   SmallVector<Component, 4> Components;
9490   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9491     const OffsetOfNode &ON = E->getComponent(I);
9492     Component Comp;
9493     Comp.isBrackets = true;
9494     Comp.LocStart = ON.getSourceRange().getBegin();
9495     Comp.LocEnd = ON.getSourceRange().getEnd();
9496     switch (ON.getKind()) {
9497     case OffsetOfNode::Array: {
9498       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9499       ExprResult Index = getDerived().TransformExpr(FromIndex);
9500       if (Index.isInvalid())
9501         return ExprError();
9502 
9503       ExprChanged = ExprChanged || Index.get() != FromIndex;
9504       Comp.isBrackets = true;
9505       Comp.U.E = Index.get();
9506       break;
9507     }
9508 
9509     case OffsetOfNode::Field:
9510     case OffsetOfNode::Identifier:
9511       Comp.isBrackets = false;
9512       Comp.U.IdentInfo = ON.getFieldName();
9513       if (!Comp.U.IdentInfo)
9514         continue;
9515 
9516       break;
9517 
9518     case OffsetOfNode::Base:
9519       // Will be recomputed during the rebuild.
9520       continue;
9521     }
9522 
9523     Components.push_back(Comp);
9524   }
9525 
9526   // If nothing changed, retain the existing expression.
9527   if (!getDerived().AlwaysRebuild() &&
9528       Type == E->getTypeSourceInfo() &&
9529       !ExprChanged)
9530     return E;
9531 
9532   // Build a new offsetof expression.
9533   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9534                                           Components, E->getRParenLoc());
9535 }
9536 
9537 template<typename Derived>
9538 ExprResult
9539 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9540   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9541          "opaque value expression requires transformation");
9542   return E;
9543 }
9544 
9545 template<typename Derived>
9546 ExprResult
9547 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9548   return E;
9549 }
9550 
9551 template<typename Derived>
9552 ExprResult
9553 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9554   // Rebuild the syntactic form.  The original syntactic form has
9555   // opaque-value expressions in it, so strip those away and rebuild
9556   // the result.  This is a really awful way of doing this, but the
9557   // better solution (rebuilding the semantic expressions and
9558   // rebinding OVEs as necessary) doesn't work; we'd need
9559   // TreeTransform to not strip away implicit conversions.
9560   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9561   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9562   if (result.isInvalid()) return ExprError();
9563 
9564   // If that gives us a pseudo-object result back, the pseudo-object
9565   // expression must have been an lvalue-to-rvalue conversion which we
9566   // should reapply.
9567   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9568     result = SemaRef.checkPseudoObjectRValue(result.get());
9569 
9570   return result;
9571 }
9572 
9573 template<typename Derived>
9574 ExprResult
9575 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9576                                                 UnaryExprOrTypeTraitExpr *E) {
9577   if (E->isArgumentType()) {
9578     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9579 
9580     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9581     if (!NewT)
9582       return ExprError();
9583 
9584     if (!getDerived().AlwaysRebuild() && OldT == NewT)
9585       return E;
9586 
9587     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9588                                                     E->getKind(),
9589                                                     E->getSourceRange());
9590   }
9591 
9592   // C++0x [expr.sizeof]p1:
9593   //   The operand is either an expression, which is an unevaluated operand
9594   //   [...]
9595   EnterExpressionEvaluationContext Unevaluated(
9596       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9597       Sema::ReuseLambdaContextDecl);
9598 
9599   // Try to recover if we have something like sizeof(T::X) where X is a type.
9600   // Notably, there must be *exactly* one set of parens if X is a type.
9601   TypeSourceInfo *RecoveryTSI = nullptr;
9602   ExprResult SubExpr;
9603   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9604   if (auto *DRE =
9605           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9606     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9607         PE, DRE, false, &RecoveryTSI);
9608   else
9609     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9610 
9611   if (RecoveryTSI) {
9612     return getDerived().RebuildUnaryExprOrTypeTrait(
9613         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9614   } else if (SubExpr.isInvalid())
9615     return ExprError();
9616 
9617   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9618     return E;
9619 
9620   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9621                                                   E->getOperatorLoc(),
9622                                                   E->getKind(),
9623                                                   E->getSourceRange());
9624 }
9625 
9626 template<typename Derived>
9627 ExprResult
9628 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9629   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9630   if (LHS.isInvalid())
9631     return ExprError();
9632 
9633   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9634   if (RHS.isInvalid())
9635     return ExprError();
9636 
9637 
9638   if (!getDerived().AlwaysRebuild() &&
9639       LHS.get() == E->getLHS() &&
9640       RHS.get() == E->getRHS())
9641     return E;
9642 
9643   return getDerived().RebuildArraySubscriptExpr(
9644       LHS.get(),
9645       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9646 }
9647 
9648 template <typename Derived>
9649 ExprResult
9650 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9651   ExprResult Base = getDerived().TransformExpr(E->getBase());
9652   if (Base.isInvalid())
9653     return ExprError();
9654 
9655   ExprResult LowerBound;
9656   if (E->getLowerBound()) {
9657     LowerBound = getDerived().TransformExpr(E->getLowerBound());
9658     if (LowerBound.isInvalid())
9659       return ExprError();
9660   }
9661 
9662   ExprResult Length;
9663   if (E->getLength()) {
9664     Length = getDerived().TransformExpr(E->getLength());
9665     if (Length.isInvalid())
9666       return ExprError();
9667   }
9668 
9669   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9670       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9671     return E;
9672 
9673   return getDerived().RebuildOMPArraySectionExpr(
9674       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9675       Length.get(), E->getRBracketLoc());
9676 }
9677 
9678 template<typename Derived>
9679 ExprResult
9680 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9681   // Transform the callee.
9682   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9683   if (Callee.isInvalid())
9684     return ExprError();
9685 
9686   // Transform arguments.
9687   bool ArgChanged = false;
9688   SmallVector<Expr*, 8> Args;
9689   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9690                                   &ArgChanged))
9691     return ExprError();
9692 
9693   if (!getDerived().AlwaysRebuild() &&
9694       Callee.get() == E->getCallee() &&
9695       !ArgChanged)
9696     return SemaRef.MaybeBindToTemporary(E);
9697 
9698   // FIXME: Wrong source location information for the '('.
9699   SourceLocation FakeLParenLoc
9700     = ((Expr *)Callee.get())->getSourceRange().getBegin();
9701   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9702                                       Args,
9703                                       E->getRParenLoc());
9704 }
9705 
9706 template<typename Derived>
9707 ExprResult
9708 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9709   ExprResult Base = getDerived().TransformExpr(E->getBase());
9710   if (Base.isInvalid())
9711     return ExprError();
9712 
9713   NestedNameSpecifierLoc QualifierLoc;
9714   if (E->hasQualifier()) {
9715     QualifierLoc
9716       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9717 
9718     if (!QualifierLoc)
9719       return ExprError();
9720   }
9721   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9722 
9723   ValueDecl *Member
9724     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9725                                                          E->getMemberDecl()));
9726   if (!Member)
9727     return ExprError();
9728 
9729   NamedDecl *FoundDecl = E->getFoundDecl();
9730   if (FoundDecl == E->getMemberDecl()) {
9731     FoundDecl = Member;
9732   } else {
9733     FoundDecl = cast_or_null<NamedDecl>(
9734                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9735     if (!FoundDecl)
9736       return ExprError();
9737   }
9738 
9739   if (!getDerived().AlwaysRebuild() &&
9740       Base.get() == E->getBase() &&
9741       QualifierLoc == E->getQualifierLoc() &&
9742       Member == E->getMemberDecl() &&
9743       FoundDecl == E->getFoundDecl() &&
9744       !E->hasExplicitTemplateArgs()) {
9745 
9746     // Mark it referenced in the new context regardless.
9747     // FIXME: this is a bit instantiation-specific.
9748     SemaRef.MarkMemberReferenced(E);
9749 
9750     return E;
9751   }
9752 
9753   TemplateArgumentListInfo TransArgs;
9754   if (E->hasExplicitTemplateArgs()) {
9755     TransArgs.setLAngleLoc(E->getLAngleLoc());
9756     TransArgs.setRAngleLoc(E->getRAngleLoc());
9757     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9758                                                 E->getNumTemplateArgs(),
9759                                                 TransArgs))
9760       return ExprError();
9761   }
9762 
9763   // FIXME: Bogus source location for the operator
9764   SourceLocation FakeOperatorLoc =
9765       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9766 
9767   // FIXME: to do this check properly, we will need to preserve the
9768   // first-qualifier-in-scope here, just in case we had a dependent
9769   // base (and therefore couldn't do the check) and a
9770   // nested-name-qualifier (and therefore could do the lookup).
9771   NamedDecl *FirstQualifierInScope = nullptr;
9772   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9773   if (MemberNameInfo.getName()) {
9774     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9775     if (!MemberNameInfo.getName())
9776       return ExprError();
9777   }
9778 
9779   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9780                                         E->isArrow(),
9781                                         QualifierLoc,
9782                                         TemplateKWLoc,
9783                                         MemberNameInfo,
9784                                         Member,
9785                                         FoundDecl,
9786                                         (E->hasExplicitTemplateArgs()
9787                                            ? &TransArgs : nullptr),
9788                                         FirstQualifierInScope);
9789 }
9790 
9791 template<typename Derived>
9792 ExprResult
9793 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9794   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9795   if (LHS.isInvalid())
9796     return ExprError();
9797 
9798   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9799   if (RHS.isInvalid())
9800     return ExprError();
9801 
9802   if (!getDerived().AlwaysRebuild() &&
9803       LHS.get() == E->getLHS() &&
9804       RHS.get() == E->getRHS())
9805     return E;
9806 
9807   Sema::FPContractStateRAII FPContractState(getSema());
9808   getSema().FPFeatures = E->getFPFeatures();
9809 
9810   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9811                                             LHS.get(), RHS.get());
9812 }
9813 
9814 template <typename Derived>
9815 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
9816     CXXRewrittenBinaryOperator *E) {
9817   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
9818 
9819   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
9820   if (LHS.isInvalid())
9821     return ExprError();
9822 
9823   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
9824   if (RHS.isInvalid())
9825     return ExprError();
9826 
9827   if (!getDerived().AlwaysRebuild() &&
9828       LHS.get() == Decomp.LHS &&
9829       RHS.get() == Decomp.RHS)
9830     return E;
9831 
9832   // Extract the already-resolved callee declarations so that we can restrict
9833   // ourselves to using them as the unqualified lookup results when rebuilding.
9834   UnresolvedSet<2> UnqualLookups;
9835   Expr *PossibleBinOps[] = {E->getSemanticForm(),
9836                             const_cast<Expr *>(Decomp.InnerBinOp)};
9837   for (Expr *PossibleBinOp : PossibleBinOps) {
9838     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
9839     if (!Op)
9840       continue;
9841     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
9842     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
9843       continue;
9844 
9845     // Transform the callee in case we built a call to a local extern
9846     // declaration.
9847     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
9848         E->getOperatorLoc(), Callee->getFoundDecl()));
9849     if (!Found)
9850       return ExprError();
9851     UnqualLookups.addDecl(Found);
9852   }
9853 
9854   return getDerived().RebuildCXXRewrittenBinaryOperator(
9855       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
9856 }
9857 
9858 template<typename Derived>
9859 ExprResult
9860 TreeTransform<Derived>::TransformCompoundAssignOperator(
9861                                                       CompoundAssignOperator *E) {
9862   return getDerived().TransformBinaryOperator(E);
9863 }
9864 
9865 template<typename Derived>
9866 ExprResult TreeTransform<Derived>::
9867 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9868   // Just rebuild the common and RHS expressions and see whether we
9869   // get any changes.
9870 
9871   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9872   if (commonExpr.isInvalid())
9873     return ExprError();
9874 
9875   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9876   if (rhs.isInvalid())
9877     return ExprError();
9878 
9879   if (!getDerived().AlwaysRebuild() &&
9880       commonExpr.get() == e->getCommon() &&
9881       rhs.get() == e->getFalseExpr())
9882     return e;
9883 
9884   return getDerived().RebuildConditionalOperator(commonExpr.get(),
9885                                                  e->getQuestionLoc(),
9886                                                  nullptr,
9887                                                  e->getColonLoc(),
9888                                                  rhs.get());
9889 }
9890 
9891 template<typename Derived>
9892 ExprResult
9893 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9894   ExprResult Cond = getDerived().TransformExpr(E->getCond());
9895   if (Cond.isInvalid())
9896     return ExprError();
9897 
9898   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9899   if (LHS.isInvalid())
9900     return ExprError();
9901 
9902   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9903   if (RHS.isInvalid())
9904     return ExprError();
9905 
9906   if (!getDerived().AlwaysRebuild() &&
9907       Cond.get() == E->getCond() &&
9908       LHS.get() == E->getLHS() &&
9909       RHS.get() == E->getRHS())
9910     return E;
9911 
9912   return getDerived().RebuildConditionalOperator(Cond.get(),
9913                                                  E->getQuestionLoc(),
9914                                                  LHS.get(),
9915                                                  E->getColonLoc(),
9916                                                  RHS.get());
9917 }
9918 
9919 template<typename Derived>
9920 ExprResult
9921 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9922   // Implicit casts are eliminated during transformation, since they
9923   // will be recomputed by semantic analysis after transformation.
9924   return getDerived().TransformExpr(E->getSubExprAsWritten());
9925 }
9926 
9927 template<typename Derived>
9928 ExprResult
9929 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9930   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9931   if (!Type)
9932     return ExprError();
9933 
9934   ExprResult SubExpr
9935     = getDerived().TransformExpr(E->getSubExprAsWritten());
9936   if (SubExpr.isInvalid())
9937     return ExprError();
9938 
9939   if (!getDerived().AlwaysRebuild() &&
9940       Type == E->getTypeInfoAsWritten() &&
9941       SubExpr.get() == E->getSubExpr())
9942     return E;
9943 
9944   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9945                                             Type,
9946                                             E->getRParenLoc(),
9947                                             SubExpr.get());
9948 }
9949 
9950 template<typename Derived>
9951 ExprResult
9952 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9953   TypeSourceInfo *OldT = E->getTypeSourceInfo();
9954   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9955   if (!NewT)
9956     return ExprError();
9957 
9958   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9959   if (Init.isInvalid())
9960     return ExprError();
9961 
9962   if (!getDerived().AlwaysRebuild() &&
9963       OldT == NewT &&
9964       Init.get() == E->getInitializer())
9965     return SemaRef.MaybeBindToTemporary(E);
9966 
9967   // Note: the expression type doesn't necessarily match the
9968   // type-as-written, but that's okay, because it should always be
9969   // derivable from the initializer.
9970 
9971   return getDerived().RebuildCompoundLiteralExpr(
9972       E->getLParenLoc(), NewT,
9973       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
9974 }
9975 
9976 template<typename Derived>
9977 ExprResult
9978 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9979   ExprResult Base = getDerived().TransformExpr(E->getBase());
9980   if (Base.isInvalid())
9981     return ExprError();
9982 
9983   if (!getDerived().AlwaysRebuild() &&
9984       Base.get() == E->getBase())
9985     return E;
9986 
9987   // FIXME: Bad source location
9988   SourceLocation FakeOperatorLoc =
9989       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
9990   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9991                                                   E->getAccessorLoc(),
9992                                                   E->getAccessor());
9993 }
9994 
9995 template<typename Derived>
9996 ExprResult
9997 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9998   if (InitListExpr *Syntactic = E->getSyntacticForm())
9999     E = Syntactic;
10000 
10001   bool InitChanged = false;
10002 
10003   EnterExpressionEvaluationContext Context(
10004       getSema(), EnterExpressionEvaluationContext::InitList);
10005 
10006   SmallVector<Expr*, 4> Inits;
10007   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
10008                                   Inits, &InitChanged))
10009     return ExprError();
10010 
10011   if (!getDerived().AlwaysRebuild() && !InitChanged) {
10012     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
10013     // in some cases. We can't reuse it in general, because the syntactic and
10014     // semantic forms are linked, and we can't know that semantic form will
10015     // match even if the syntactic form does.
10016   }
10017 
10018   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
10019                                       E->getRBraceLoc());
10020 }
10021 
10022 template<typename Derived>
10023 ExprResult
10024 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
10025   Designation Desig;
10026 
10027   // transform the initializer value
10028   ExprResult Init = getDerived().TransformExpr(E->getInit());
10029   if (Init.isInvalid())
10030     return ExprError();
10031 
10032   // transform the designators.
10033   SmallVector<Expr*, 4> ArrayExprs;
10034   bool ExprChanged = false;
10035   for (const DesignatedInitExpr::Designator &D : E->designators()) {
10036     if (D.isFieldDesignator()) {
10037       Desig.AddDesignator(Designator::getField(D.getFieldName(),
10038                                                D.getDotLoc(),
10039                                                D.getFieldLoc()));
10040       if (D.getField()) {
10041         FieldDecl *Field = cast_or_null<FieldDecl>(
10042             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
10043         if (Field != D.getField())
10044           // Rebuild the expression when the transformed FieldDecl is
10045           // different to the already assigned FieldDecl.
10046           ExprChanged = true;
10047       } else {
10048         // Ensure that the designator expression is rebuilt when there isn't
10049         // a resolved FieldDecl in the designator as we don't want to assign
10050         // a FieldDecl to a pattern designator that will be instantiated again.
10051         ExprChanged = true;
10052       }
10053       continue;
10054     }
10055 
10056     if (D.isArrayDesignator()) {
10057       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
10058       if (Index.isInvalid())
10059         return ExprError();
10060 
10061       Desig.AddDesignator(
10062           Designator::getArray(Index.get(), D.getLBracketLoc()));
10063 
10064       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
10065       ArrayExprs.push_back(Index.get());
10066       continue;
10067     }
10068 
10069     assert(D.isArrayRangeDesignator() && "New kind of designator?");
10070     ExprResult Start
10071       = getDerived().TransformExpr(E->getArrayRangeStart(D));
10072     if (Start.isInvalid())
10073       return ExprError();
10074 
10075     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
10076     if (End.isInvalid())
10077       return ExprError();
10078 
10079     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
10080                                                   End.get(),
10081                                                   D.getLBracketLoc(),
10082                                                   D.getEllipsisLoc()));
10083 
10084     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
10085                   End.get() != E->getArrayRangeEnd(D);
10086 
10087     ArrayExprs.push_back(Start.get());
10088     ArrayExprs.push_back(End.get());
10089   }
10090 
10091   if (!getDerived().AlwaysRebuild() &&
10092       Init.get() == E->getInit() &&
10093       !ExprChanged)
10094     return E;
10095 
10096   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
10097                                                 E->getEqualOrColonLoc(),
10098                                                 E->usesGNUSyntax(), Init.get());
10099 }
10100 
10101 // Seems that if TransformInitListExpr() only works on the syntactic form of an
10102 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
10103 template<typename Derived>
10104 ExprResult
10105 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
10106     DesignatedInitUpdateExpr *E) {
10107   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
10108                    "initializer");
10109   return ExprError();
10110 }
10111 
10112 template<typename Derived>
10113 ExprResult
10114 TreeTransform<Derived>::TransformNoInitExpr(
10115     NoInitExpr *E) {
10116   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
10117   return ExprError();
10118 }
10119 
10120 template<typename Derived>
10121 ExprResult
10122 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
10123   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
10124   return ExprError();
10125 }
10126 
10127 template<typename Derived>
10128 ExprResult
10129 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
10130   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
10131   return ExprError();
10132 }
10133 
10134 template<typename Derived>
10135 ExprResult
10136 TreeTransform<Derived>::TransformImplicitValueInitExpr(
10137                                                      ImplicitValueInitExpr *E) {
10138   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
10139 
10140   // FIXME: Will we ever have proper type location here? Will we actually
10141   // need to transform the type?
10142   QualType T = getDerived().TransformType(E->getType());
10143   if (T.isNull())
10144     return ExprError();
10145 
10146   if (!getDerived().AlwaysRebuild() &&
10147       T == E->getType())
10148     return E;
10149 
10150   return getDerived().RebuildImplicitValueInitExpr(T);
10151 }
10152 
10153 template<typename Derived>
10154 ExprResult
10155 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10156   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10157   if (!TInfo)
10158     return ExprError();
10159 
10160   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10161   if (SubExpr.isInvalid())
10162     return ExprError();
10163 
10164   if (!getDerived().AlwaysRebuild() &&
10165       TInfo == E->getWrittenTypeInfo() &&
10166       SubExpr.get() == E->getSubExpr())
10167     return E;
10168 
10169   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10170                                        TInfo, E->getRParenLoc());
10171 }
10172 
10173 template<typename Derived>
10174 ExprResult
10175 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10176   bool ArgumentChanged = false;
10177   SmallVector<Expr*, 4> Inits;
10178   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10179                      &ArgumentChanged))
10180     return ExprError();
10181 
10182   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10183                                            Inits,
10184                                            E->getRParenLoc());
10185 }
10186 
10187 /// Transform an address-of-label expression.
10188 ///
10189 /// By default, the transformation of an address-of-label expression always
10190 /// rebuilds the expression, so that the label identifier can be resolved to
10191 /// the corresponding label statement by semantic analysis.
10192 template<typename Derived>
10193 ExprResult
10194 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10195   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10196                                         E->getLabel());
10197   if (!LD)
10198     return ExprError();
10199 
10200   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10201                                            cast<LabelDecl>(LD));
10202 }
10203 
10204 template<typename Derived>
10205 ExprResult
10206 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10207   SemaRef.ActOnStartStmtExpr();
10208   StmtResult SubStmt
10209     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10210   if (SubStmt.isInvalid()) {
10211     SemaRef.ActOnStmtExprError();
10212     return ExprError();
10213   }
10214 
10215   if (!getDerived().AlwaysRebuild() &&
10216       SubStmt.get() == E->getSubStmt()) {
10217     // Calling this an 'error' is unintuitive, but it does the right thing.
10218     SemaRef.ActOnStmtExprError();
10219     return SemaRef.MaybeBindToTemporary(E);
10220   }
10221 
10222   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
10223                                       SubStmt.get(),
10224                                       E->getRParenLoc());
10225 }
10226 
10227 template<typename Derived>
10228 ExprResult
10229 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10230   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10231   if (Cond.isInvalid())
10232     return ExprError();
10233 
10234   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10235   if (LHS.isInvalid())
10236     return ExprError();
10237 
10238   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10239   if (RHS.isInvalid())
10240     return ExprError();
10241 
10242   if (!getDerived().AlwaysRebuild() &&
10243       Cond.get() == E->getCond() &&
10244       LHS.get() == E->getLHS() &&
10245       RHS.get() == E->getRHS())
10246     return E;
10247 
10248   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10249                                         Cond.get(), LHS.get(), RHS.get(),
10250                                         E->getRParenLoc());
10251 }
10252 
10253 template<typename Derived>
10254 ExprResult
10255 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10256   return E;
10257 }
10258 
10259 template<typename Derived>
10260 ExprResult
10261 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10262   switch (E->getOperator()) {
10263   case OO_New:
10264   case OO_Delete:
10265   case OO_Array_New:
10266   case OO_Array_Delete:
10267     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
10268 
10269   case OO_Call: {
10270     // This is a call to an object's operator().
10271     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
10272 
10273     // Transform the object itself.
10274     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10275     if (Object.isInvalid())
10276       return ExprError();
10277 
10278     // FIXME: Poor location information
10279     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10280         static_cast<Expr *>(Object.get())->getEndLoc());
10281 
10282     // Transform the call arguments.
10283     SmallVector<Expr*, 8> Args;
10284     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10285                                     Args))
10286       return ExprError();
10287 
10288     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10289                                         E->getEndLoc());
10290   }
10291 
10292 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10293   case OO_##Name:
10294 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10295 #include "clang/Basic/OperatorKinds.def"
10296   case OO_Subscript:
10297     // Handled below.
10298     break;
10299 
10300   case OO_Conditional:
10301     llvm_unreachable("conditional operator is not actually overloadable");
10302 
10303   case OO_None:
10304   case NUM_OVERLOADED_OPERATORS:
10305     llvm_unreachable("not an overloaded operator?");
10306   }
10307 
10308   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10309   if (Callee.isInvalid())
10310     return ExprError();
10311 
10312   ExprResult First;
10313   if (E->getOperator() == OO_Amp)
10314     First = getDerived().TransformAddressOfOperand(E->getArg(0));
10315   else
10316     First = getDerived().TransformExpr(E->getArg(0));
10317   if (First.isInvalid())
10318     return ExprError();
10319 
10320   ExprResult Second;
10321   if (E->getNumArgs() == 2) {
10322     Second = getDerived().TransformExpr(E->getArg(1));
10323     if (Second.isInvalid())
10324       return ExprError();
10325   }
10326 
10327   if (!getDerived().AlwaysRebuild() &&
10328       Callee.get() == E->getCallee() &&
10329       First.get() == E->getArg(0) &&
10330       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10331     return SemaRef.MaybeBindToTemporary(E);
10332 
10333   Sema::FPContractStateRAII FPContractState(getSema());
10334   getSema().FPFeatures = E->getFPFeatures();
10335 
10336   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10337                                                  E->getOperatorLoc(),
10338                                                  Callee.get(),
10339                                                  First.get(),
10340                                                  Second.get());
10341 }
10342 
10343 template<typename Derived>
10344 ExprResult
10345 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10346   return getDerived().TransformCallExpr(E);
10347 }
10348 
10349 template <typename Derived>
10350 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10351   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10352                          getSema().CurContext != E->getParentContext();
10353 
10354   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10355     return E;
10356 
10357   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10358                                            E->getEndLoc(),
10359                                            getSema().CurContext);
10360 }
10361 
10362 template<typename Derived>
10363 ExprResult
10364 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10365   // Transform the callee.
10366   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10367   if (Callee.isInvalid())
10368     return ExprError();
10369 
10370   // Transform exec config.
10371   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10372   if (EC.isInvalid())
10373     return ExprError();
10374 
10375   // Transform arguments.
10376   bool ArgChanged = false;
10377   SmallVector<Expr*, 8> Args;
10378   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10379                                   &ArgChanged))
10380     return ExprError();
10381 
10382   if (!getDerived().AlwaysRebuild() &&
10383       Callee.get() == E->getCallee() &&
10384       !ArgChanged)
10385     return SemaRef.MaybeBindToTemporary(E);
10386 
10387   // FIXME: Wrong source location information for the '('.
10388   SourceLocation FakeLParenLoc
10389     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10390   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10391                                       Args,
10392                                       E->getRParenLoc(), EC.get());
10393 }
10394 
10395 template<typename Derived>
10396 ExprResult
10397 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10398   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10399   if (!Type)
10400     return ExprError();
10401 
10402   ExprResult SubExpr
10403     = getDerived().TransformExpr(E->getSubExprAsWritten());
10404   if (SubExpr.isInvalid())
10405     return ExprError();
10406 
10407   if (!getDerived().AlwaysRebuild() &&
10408       Type == E->getTypeInfoAsWritten() &&
10409       SubExpr.get() == E->getSubExpr())
10410     return E;
10411   return getDerived().RebuildCXXNamedCastExpr(
10412       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10413       Type, E->getAngleBrackets().getEnd(),
10414       // FIXME. this should be '(' location
10415       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10416 }
10417 
10418 template<typename Derived>
10419 ExprResult
10420 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10421   TypeSourceInfo *TSI =
10422       getDerived().TransformType(BCE->getTypeInfoAsWritten());
10423   if (!TSI)
10424     return ExprError();
10425 
10426   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10427   if (Sub.isInvalid())
10428     return ExprError();
10429 
10430   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10431                                                 Sub.get(), BCE->getEndLoc());
10432 }
10433 
10434 template<typename Derived>
10435 ExprResult
10436 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10437   return getDerived().TransformCXXNamedCastExpr(E);
10438 }
10439 
10440 template<typename Derived>
10441 ExprResult
10442 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10443   return getDerived().TransformCXXNamedCastExpr(E);
10444 }
10445 
10446 template<typename Derived>
10447 ExprResult
10448 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10449                                                       CXXReinterpretCastExpr *E) {
10450   return getDerived().TransformCXXNamedCastExpr(E);
10451 }
10452 
10453 template<typename Derived>
10454 ExprResult
10455 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10456   return getDerived().TransformCXXNamedCastExpr(E);
10457 }
10458 
10459 template<typename Derived>
10460 ExprResult
10461 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10462                                                      CXXFunctionalCastExpr *E) {
10463   TypeSourceInfo *Type =
10464       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10465   if (!Type)
10466     return ExprError();
10467 
10468   ExprResult SubExpr
10469     = getDerived().TransformExpr(E->getSubExprAsWritten());
10470   if (SubExpr.isInvalid())
10471     return ExprError();
10472 
10473   if (!getDerived().AlwaysRebuild() &&
10474       Type == E->getTypeInfoAsWritten() &&
10475       SubExpr.get() == E->getSubExpr())
10476     return E;
10477 
10478   return getDerived().RebuildCXXFunctionalCastExpr(Type,
10479                                                    E->getLParenLoc(),
10480                                                    SubExpr.get(),
10481                                                    E->getRParenLoc(),
10482                                                    E->isListInitialization());
10483 }
10484 
10485 template<typename Derived>
10486 ExprResult
10487 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10488   if (E->isTypeOperand()) {
10489     TypeSourceInfo *TInfo
10490       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10491     if (!TInfo)
10492       return ExprError();
10493 
10494     if (!getDerived().AlwaysRebuild() &&
10495         TInfo == E->getTypeOperandSourceInfo())
10496       return E;
10497 
10498     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10499                                              TInfo, E->getEndLoc());
10500   }
10501 
10502   // We don't know whether the subexpression is potentially evaluated until
10503   // after we perform semantic analysis.  We speculatively assume it is
10504   // unevaluated; it will get fixed later if the subexpression is in fact
10505   // potentially evaluated.
10506   EnterExpressionEvaluationContext Unevaluated(
10507       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10508       Sema::ReuseLambdaContextDecl);
10509 
10510   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10511   if (SubExpr.isInvalid())
10512     return ExprError();
10513 
10514   if (!getDerived().AlwaysRebuild() &&
10515       SubExpr.get() == E->getExprOperand())
10516     return E;
10517 
10518   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10519                                            SubExpr.get(), E->getEndLoc());
10520 }
10521 
10522 template<typename Derived>
10523 ExprResult
10524 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10525   if (E->isTypeOperand()) {
10526     TypeSourceInfo *TInfo
10527       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10528     if (!TInfo)
10529       return ExprError();
10530 
10531     if (!getDerived().AlwaysRebuild() &&
10532         TInfo == E->getTypeOperandSourceInfo())
10533       return E;
10534 
10535     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10536                                              TInfo, E->getEndLoc());
10537   }
10538 
10539   EnterExpressionEvaluationContext Unevaluated(
10540       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10541 
10542   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10543   if (SubExpr.isInvalid())
10544     return ExprError();
10545 
10546   if (!getDerived().AlwaysRebuild() &&
10547       SubExpr.get() == E->getExprOperand())
10548     return E;
10549 
10550   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10551                                            SubExpr.get(), E->getEndLoc());
10552 }
10553 
10554 template<typename Derived>
10555 ExprResult
10556 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10557   return E;
10558 }
10559 
10560 template<typename Derived>
10561 ExprResult
10562 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10563                                                      CXXNullPtrLiteralExpr *E) {
10564   return E;
10565 }
10566 
10567 template<typename Derived>
10568 ExprResult
10569 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10570   QualType T = getSema().getCurrentThisType();
10571 
10572   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10573     // Mark it referenced in the new context regardless.
10574     // FIXME: this is a bit instantiation-specific.
10575     getSema().MarkThisReferenced(E);
10576     return E;
10577   }
10578 
10579   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10580 }
10581 
10582 template<typename Derived>
10583 ExprResult
10584 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10585   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10586   if (SubExpr.isInvalid())
10587     return ExprError();
10588 
10589   if (!getDerived().AlwaysRebuild() &&
10590       SubExpr.get() == E->getSubExpr())
10591     return E;
10592 
10593   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10594                                           E->isThrownVariableInScope());
10595 }
10596 
10597 template<typename Derived>
10598 ExprResult
10599 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10600   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10601       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10602   if (!Param)
10603     return ExprError();
10604 
10605   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10606       E->getUsedContext() == SemaRef.CurContext)
10607     return E;
10608 
10609   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10610 }
10611 
10612 template<typename Derived>
10613 ExprResult
10614 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10615   FieldDecl *Field = cast_or_null<FieldDecl>(
10616       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10617   if (!Field)
10618     return ExprError();
10619 
10620   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10621       E->getUsedContext() == SemaRef.CurContext)
10622     return E;
10623 
10624   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10625 }
10626 
10627 template<typename Derived>
10628 ExprResult
10629 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10630                                                     CXXScalarValueInitExpr *E) {
10631   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10632   if (!T)
10633     return ExprError();
10634 
10635   if (!getDerived().AlwaysRebuild() &&
10636       T == E->getTypeSourceInfo())
10637     return E;
10638 
10639   return getDerived().RebuildCXXScalarValueInitExpr(T,
10640                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
10641                                                     E->getRParenLoc());
10642 }
10643 
10644 template<typename Derived>
10645 ExprResult
10646 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10647   // Transform the type that we're allocating
10648   TypeSourceInfo *AllocTypeInfo =
10649       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10650   if (!AllocTypeInfo)
10651     return ExprError();
10652 
10653   // Transform the size of the array we're allocating (if any).
10654   Optional<Expr *> ArraySize;
10655   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10656     ExprResult NewArraySize;
10657     if (*OldArraySize) {
10658       NewArraySize = getDerived().TransformExpr(*OldArraySize);
10659       if (NewArraySize.isInvalid())
10660         return ExprError();
10661     }
10662     ArraySize = NewArraySize.get();
10663   }
10664 
10665   // Transform the placement arguments (if any).
10666   bool ArgumentChanged = false;
10667   SmallVector<Expr*, 8> PlacementArgs;
10668   if (getDerived().TransformExprs(E->getPlacementArgs(),
10669                                   E->getNumPlacementArgs(), true,
10670                                   PlacementArgs, &ArgumentChanged))
10671     return ExprError();
10672 
10673   // Transform the initializer (if any).
10674   Expr *OldInit = E->getInitializer();
10675   ExprResult NewInit;
10676   if (OldInit)
10677     NewInit = getDerived().TransformInitializer(OldInit, true);
10678   if (NewInit.isInvalid())
10679     return ExprError();
10680 
10681   // Transform new operator and delete operator.
10682   FunctionDecl *OperatorNew = nullptr;
10683   if (E->getOperatorNew()) {
10684     OperatorNew = cast_or_null<FunctionDecl>(
10685         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10686     if (!OperatorNew)
10687       return ExprError();
10688   }
10689 
10690   FunctionDecl *OperatorDelete = nullptr;
10691   if (E->getOperatorDelete()) {
10692     OperatorDelete = cast_or_null<FunctionDecl>(
10693         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10694     if (!OperatorDelete)
10695       return ExprError();
10696   }
10697 
10698   if (!getDerived().AlwaysRebuild() &&
10699       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10700       ArraySize == E->getArraySize() &&
10701       NewInit.get() == OldInit &&
10702       OperatorNew == E->getOperatorNew() &&
10703       OperatorDelete == E->getOperatorDelete() &&
10704       !ArgumentChanged) {
10705     // Mark any declarations we need as referenced.
10706     // FIXME: instantiation-specific.
10707     if (OperatorNew)
10708       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10709     if (OperatorDelete)
10710       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10711 
10712     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10713       QualType ElementType
10714         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10715       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10716         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10717         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10718           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10719         }
10720       }
10721     }
10722 
10723     return E;
10724   }
10725 
10726   QualType AllocType = AllocTypeInfo->getType();
10727   if (!ArraySize) {
10728     // If no array size was specified, but the new expression was
10729     // instantiated with an array type (e.g., "new T" where T is
10730     // instantiated with "int[4]"), extract the outer bound from the
10731     // array type as our array size. We do this with constant and
10732     // dependently-sized array types.
10733     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10734     if (!ArrayT) {
10735       // Do nothing
10736     } else if (const ConstantArrayType *ConsArrayT
10737                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
10738       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10739                                          SemaRef.Context.getSizeType(),
10740                                          /*FIXME:*/ E->getBeginLoc());
10741       AllocType = ConsArrayT->getElementType();
10742     } else if (const DependentSizedArrayType *DepArrayT
10743                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10744       if (DepArrayT->getSizeExpr()) {
10745         ArraySize = DepArrayT->getSizeExpr();
10746         AllocType = DepArrayT->getElementType();
10747       }
10748     }
10749   }
10750 
10751   return getDerived().RebuildCXXNewExpr(
10752       E->getBeginLoc(), E->isGlobalNew(),
10753       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10754       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10755       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10756 }
10757 
10758 template<typename Derived>
10759 ExprResult
10760 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10761   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10762   if (Operand.isInvalid())
10763     return ExprError();
10764 
10765   // Transform the delete operator, if known.
10766   FunctionDecl *OperatorDelete = nullptr;
10767   if (E->getOperatorDelete()) {
10768     OperatorDelete = cast_or_null<FunctionDecl>(
10769         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10770     if (!OperatorDelete)
10771       return ExprError();
10772   }
10773 
10774   if (!getDerived().AlwaysRebuild() &&
10775       Operand.get() == E->getArgument() &&
10776       OperatorDelete == E->getOperatorDelete()) {
10777     // Mark any declarations we need as referenced.
10778     // FIXME: instantiation-specific.
10779     if (OperatorDelete)
10780       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10781 
10782     if (!E->getArgument()->isTypeDependent()) {
10783       QualType Destroyed = SemaRef.Context.getBaseElementType(
10784                                                          E->getDestroyedType());
10785       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10786         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10787         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10788                                        SemaRef.LookupDestructor(Record));
10789       }
10790     }
10791 
10792     return E;
10793   }
10794 
10795   return getDerived().RebuildCXXDeleteExpr(
10796       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10797 }
10798 
10799 template<typename Derived>
10800 ExprResult
10801 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10802                                                      CXXPseudoDestructorExpr *E) {
10803   ExprResult Base = getDerived().TransformExpr(E->getBase());
10804   if (Base.isInvalid())
10805     return ExprError();
10806 
10807   ParsedType ObjectTypePtr;
10808   bool MayBePseudoDestructor = false;
10809   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10810                                               E->getOperatorLoc(),
10811                                         E->isArrow()? tok::arrow : tok::period,
10812                                               ObjectTypePtr,
10813                                               MayBePseudoDestructor);
10814   if (Base.isInvalid())
10815     return ExprError();
10816 
10817   QualType ObjectType = ObjectTypePtr.get();
10818   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10819   if (QualifierLoc) {
10820     QualifierLoc
10821       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10822     if (!QualifierLoc)
10823       return ExprError();
10824   }
10825   CXXScopeSpec SS;
10826   SS.Adopt(QualifierLoc);
10827 
10828   PseudoDestructorTypeStorage Destroyed;
10829   if (E->getDestroyedTypeInfo()) {
10830     TypeSourceInfo *DestroyedTypeInfo
10831       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10832                                                 ObjectType, nullptr, SS);
10833     if (!DestroyedTypeInfo)
10834       return ExprError();
10835     Destroyed = DestroyedTypeInfo;
10836   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10837     // We aren't likely to be able to resolve the identifier down to a type
10838     // now anyway, so just retain the identifier.
10839     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10840                                             E->getDestroyedTypeLoc());
10841   } else {
10842     // Look for a destructor known with the given name.
10843     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10844                                               *E->getDestroyedTypeIdentifier(),
10845                                                 E->getDestroyedTypeLoc(),
10846                                                 /*Scope=*/nullptr,
10847                                                 SS, ObjectTypePtr,
10848                                                 false);
10849     if (!T)
10850       return ExprError();
10851 
10852     Destroyed
10853       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10854                                                  E->getDestroyedTypeLoc());
10855   }
10856 
10857   TypeSourceInfo *ScopeTypeInfo = nullptr;
10858   if (E->getScopeTypeInfo()) {
10859     CXXScopeSpec EmptySS;
10860     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10861                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10862     if (!ScopeTypeInfo)
10863       return ExprError();
10864   }
10865 
10866   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10867                                                      E->getOperatorLoc(),
10868                                                      E->isArrow(),
10869                                                      SS,
10870                                                      ScopeTypeInfo,
10871                                                      E->getColonColonLoc(),
10872                                                      E->getTildeLoc(),
10873                                                      Destroyed);
10874 }
10875 
10876 template <typename Derived>
10877 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10878                                                         bool RequiresADL,
10879                                                         LookupResult &R) {
10880   // Transform all the decls.
10881   bool AllEmptyPacks = true;
10882   for (auto *OldD : Old->decls()) {
10883     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10884     if (!InstD) {
10885       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10886       // This can happen because of dependent hiding.
10887       if (isa<UsingShadowDecl>(OldD))
10888         continue;
10889       else {
10890         R.clear();
10891         return true;
10892       }
10893     }
10894 
10895     // Expand using pack declarations.
10896     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10897     ArrayRef<NamedDecl*> Decls = SingleDecl;
10898     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10899       Decls = UPD->expansions();
10900 
10901     // Expand using declarations.
10902     for (auto *D : Decls) {
10903       if (auto *UD = dyn_cast<UsingDecl>(D)) {
10904         for (auto *SD : UD->shadows())
10905           R.addDecl(SD);
10906       } else {
10907         R.addDecl(D);
10908       }
10909     }
10910 
10911     AllEmptyPacks &= Decls.empty();
10912   };
10913 
10914   // C++ [temp.res]/8.4.2:
10915   //   The program is ill-formed, no diagnostic required, if [...] lookup for
10916   //   a name in the template definition found a using-declaration, but the
10917   //   lookup in the corresponding scope in the instantiation odoes not find
10918   //   any declarations because the using-declaration was a pack expansion and
10919   //   the corresponding pack is empty
10920   if (AllEmptyPacks && !RequiresADL) {
10921     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10922         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10923     return true;
10924   }
10925 
10926   // Resolve a kind, but don't do any further analysis.  If it's
10927   // ambiguous, the callee needs to deal with it.
10928   R.resolveKind();
10929   return false;
10930 }
10931 
10932 template<typename Derived>
10933 ExprResult
10934 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10935                                                   UnresolvedLookupExpr *Old) {
10936   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10937                  Sema::LookupOrdinaryName);
10938 
10939   // Transform the declaration set.
10940   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10941     return ExprError();
10942 
10943   // Rebuild the nested-name qualifier, if present.
10944   CXXScopeSpec SS;
10945   if (Old->getQualifierLoc()) {
10946     NestedNameSpecifierLoc QualifierLoc
10947       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10948     if (!QualifierLoc)
10949       return ExprError();
10950 
10951     SS.Adopt(QualifierLoc);
10952   }
10953 
10954   if (Old->getNamingClass()) {
10955     CXXRecordDecl *NamingClass
10956       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10957                                                             Old->getNameLoc(),
10958                                                         Old->getNamingClass()));
10959     if (!NamingClass) {
10960       R.clear();
10961       return ExprError();
10962     }
10963 
10964     R.setNamingClass(NamingClass);
10965   }
10966 
10967   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10968 
10969   // If we have neither explicit template arguments, nor the template keyword,
10970   // it's a normal declaration name or member reference.
10971   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10972     NamedDecl *D = R.getAsSingle<NamedDecl>();
10973     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10974     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10975     // give a good diagnostic.
10976     if (D && D->isCXXInstanceMember()) {
10977       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10978                                                      /*TemplateArgs=*/nullptr,
10979                                                      /*Scope=*/nullptr);
10980     }
10981 
10982     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10983   }
10984 
10985   // If we have template arguments, rebuild them, then rebuild the
10986   // templateid expression.
10987   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10988   if (Old->hasExplicitTemplateArgs() &&
10989       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10990                                               Old->getNumTemplateArgs(),
10991                                               TransArgs)) {
10992     R.clear();
10993     return ExprError();
10994   }
10995 
10996   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10997                                             Old->requiresADL(), &TransArgs);
10998 }
10999 
11000 template<typename Derived>
11001 ExprResult
11002 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
11003   bool ArgChanged = false;
11004   SmallVector<TypeSourceInfo *, 4> Args;
11005   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
11006     TypeSourceInfo *From = E->getArg(I);
11007     TypeLoc FromTL = From->getTypeLoc();
11008     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
11009       TypeLocBuilder TLB;
11010       TLB.reserve(FromTL.getFullDataSize());
11011       QualType To = getDerived().TransformType(TLB, FromTL);
11012       if (To.isNull())
11013         return ExprError();
11014 
11015       if (To == From->getType())
11016         Args.push_back(From);
11017       else {
11018         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11019         ArgChanged = true;
11020       }
11021       continue;
11022     }
11023 
11024     ArgChanged = true;
11025 
11026     // We have a pack expansion. Instantiate it.
11027     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
11028     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
11029     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11030     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
11031 
11032     // Determine whether the set of unexpanded parameter packs can and should
11033     // be expanded.
11034     bool Expand = true;
11035     bool RetainExpansion = false;
11036     Optional<unsigned> OrigNumExpansions =
11037         ExpansionTL.getTypePtr()->getNumExpansions();
11038     Optional<unsigned> NumExpansions = OrigNumExpansions;
11039     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
11040                                              PatternTL.getSourceRange(),
11041                                              Unexpanded,
11042                                              Expand, RetainExpansion,
11043                                              NumExpansions))
11044       return ExprError();
11045 
11046     if (!Expand) {
11047       // The transform has determined that we should perform a simple
11048       // transformation on the pack expansion, producing another pack
11049       // expansion.
11050       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11051 
11052       TypeLocBuilder TLB;
11053       TLB.reserve(From->getTypeLoc().getFullDataSize());
11054 
11055       QualType To = getDerived().TransformType(TLB, PatternTL);
11056       if (To.isNull())
11057         return ExprError();
11058 
11059       To = getDerived().RebuildPackExpansionType(To,
11060                                                  PatternTL.getSourceRange(),
11061                                                  ExpansionTL.getEllipsisLoc(),
11062                                                  NumExpansions);
11063       if (To.isNull())
11064         return ExprError();
11065 
11066       PackExpansionTypeLoc ToExpansionTL
11067         = TLB.push<PackExpansionTypeLoc>(To);
11068       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11069       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11070       continue;
11071     }
11072 
11073     // Expand the pack expansion by substituting for each argument in the
11074     // pack(s).
11075     for (unsigned I = 0; I != *NumExpansions; ++I) {
11076       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
11077       TypeLocBuilder TLB;
11078       TLB.reserve(PatternTL.getFullDataSize());
11079       QualType To = getDerived().TransformType(TLB, PatternTL);
11080       if (To.isNull())
11081         return ExprError();
11082 
11083       if (To->containsUnexpandedParameterPack()) {
11084         To = getDerived().RebuildPackExpansionType(To,
11085                                                    PatternTL.getSourceRange(),
11086                                                    ExpansionTL.getEllipsisLoc(),
11087                                                    NumExpansions);
11088         if (To.isNull())
11089           return ExprError();
11090 
11091         PackExpansionTypeLoc ToExpansionTL
11092           = TLB.push<PackExpansionTypeLoc>(To);
11093         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11094       }
11095 
11096       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11097     }
11098 
11099     if (!RetainExpansion)
11100       continue;
11101 
11102     // If we're supposed to retain a pack expansion, do so by temporarily
11103     // forgetting the partially-substituted parameter pack.
11104     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11105 
11106     TypeLocBuilder TLB;
11107     TLB.reserve(From->getTypeLoc().getFullDataSize());
11108 
11109     QualType To = getDerived().TransformType(TLB, PatternTL);
11110     if (To.isNull())
11111       return ExprError();
11112 
11113     To = getDerived().RebuildPackExpansionType(To,
11114                                                PatternTL.getSourceRange(),
11115                                                ExpansionTL.getEllipsisLoc(),
11116                                                NumExpansions);
11117     if (To.isNull())
11118       return ExprError();
11119 
11120     PackExpansionTypeLoc ToExpansionTL
11121       = TLB.push<PackExpansionTypeLoc>(To);
11122     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11123     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11124   }
11125 
11126   if (!getDerived().AlwaysRebuild() && !ArgChanged)
11127     return E;
11128 
11129   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
11130                                        E->getEndLoc());
11131 }
11132 
11133 template<typename Derived>
11134 ExprResult
11135 TreeTransform<Derived>::TransformConceptSpecializationExpr(
11136                                                  ConceptSpecializationExpr *E) {
11137   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
11138   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
11139   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11140                                               Old->NumTemplateArgs, TransArgs))
11141     return ExprError();
11142 
11143   return getDerived().RebuildConceptSpecializationExpr(
11144       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
11145       E->getConceptNameLoc(), E->getFoundDecl(), E->getNamedConcept(),
11146       &TransArgs);
11147 }
11148 
11149 
11150 template<typename Derived>
11151 ExprResult
11152 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
11153   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
11154   if (!T)
11155     return ExprError();
11156 
11157   if (!getDerived().AlwaysRebuild() &&
11158       T == E->getQueriedTypeSourceInfo())
11159     return E;
11160 
11161   ExprResult SubExpr;
11162   {
11163     EnterExpressionEvaluationContext Unevaluated(
11164         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11165     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
11166     if (SubExpr.isInvalid())
11167       return ExprError();
11168 
11169     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11170       return E;
11171   }
11172 
11173   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11174                                             SubExpr.get(), E->getEndLoc());
11175 }
11176 
11177 template<typename Derived>
11178 ExprResult
11179 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11180   ExprResult SubExpr;
11181   {
11182     EnterExpressionEvaluationContext Unevaluated(
11183         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11184     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11185     if (SubExpr.isInvalid())
11186       return ExprError();
11187 
11188     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11189       return E;
11190   }
11191 
11192   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11193                                              SubExpr.get(), E->getEndLoc());
11194 }
11195 
11196 template <typename Derived>
11197 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11198     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11199     TypeSourceInfo **RecoveryTSI) {
11200   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11201       DRE, AddrTaken, RecoveryTSI);
11202 
11203   // Propagate both errors and recovered types, which return ExprEmpty.
11204   if (!NewDRE.isUsable())
11205     return NewDRE;
11206 
11207   // We got an expr, wrap it up in parens.
11208   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11209     return PE;
11210   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11211                                        PE->getRParen());
11212 }
11213 
11214 template <typename Derived>
11215 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11216     DependentScopeDeclRefExpr *E) {
11217   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11218                                             nullptr);
11219 }
11220 
11221 template<typename Derived>
11222 ExprResult
11223 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11224                                                DependentScopeDeclRefExpr *E,
11225                                                bool IsAddressOfOperand,
11226                                                TypeSourceInfo **RecoveryTSI) {
11227   assert(E->getQualifierLoc());
11228   NestedNameSpecifierLoc QualifierLoc
11229   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11230   if (!QualifierLoc)
11231     return ExprError();
11232   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11233 
11234   // TODO: If this is a conversion-function-id, verify that the
11235   // destination type name (if present) resolves the same way after
11236   // instantiation as it did in the local scope.
11237 
11238   DeclarationNameInfo NameInfo
11239     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11240   if (!NameInfo.getName())
11241     return ExprError();
11242 
11243   if (!E->hasExplicitTemplateArgs()) {
11244     if (!getDerived().AlwaysRebuild() &&
11245         QualifierLoc == E->getQualifierLoc() &&
11246         // Note: it is sufficient to compare the Name component of NameInfo:
11247         // if name has not changed, DNLoc has not changed either.
11248         NameInfo.getName() == E->getDeclName())
11249       return E;
11250 
11251     return getDerived().RebuildDependentScopeDeclRefExpr(
11252         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11253         IsAddressOfOperand, RecoveryTSI);
11254   }
11255 
11256   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11257   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11258                                               E->getNumTemplateArgs(),
11259                                               TransArgs))
11260     return ExprError();
11261 
11262   return getDerived().RebuildDependentScopeDeclRefExpr(
11263       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11264       RecoveryTSI);
11265 }
11266 
11267 template<typename Derived>
11268 ExprResult
11269 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11270   // CXXConstructExprs other than for list-initialization and
11271   // CXXTemporaryObjectExpr are always implicit, so when we have
11272   // a 1-argument construction we just transform that argument.
11273   if ((E->getNumArgs() == 1 ||
11274        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11275       (!getDerived().DropCallArgument(E->getArg(0))) &&
11276       !E->isListInitialization())
11277     return getDerived().TransformExpr(E->getArg(0));
11278 
11279   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11280 
11281   QualType T = getDerived().TransformType(E->getType());
11282   if (T.isNull())
11283     return ExprError();
11284 
11285   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11286       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11287   if (!Constructor)
11288     return ExprError();
11289 
11290   bool ArgumentChanged = false;
11291   SmallVector<Expr*, 8> Args;
11292   {
11293     EnterExpressionEvaluationContext Context(
11294         getSema(), EnterExpressionEvaluationContext::InitList,
11295         E->isListInitialization());
11296     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11297                                     &ArgumentChanged))
11298       return ExprError();
11299   }
11300 
11301   if (!getDerived().AlwaysRebuild() &&
11302       T == E->getType() &&
11303       Constructor == E->getConstructor() &&
11304       !ArgumentChanged) {
11305     // Mark the constructor as referenced.
11306     // FIXME: Instantiation-specific
11307     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11308     return E;
11309   }
11310 
11311   return getDerived().RebuildCXXConstructExpr(
11312       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11313       E->hadMultipleCandidates(), E->isListInitialization(),
11314       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11315       E->getConstructionKind(), E->getParenOrBraceRange());
11316 }
11317 
11318 template<typename Derived>
11319 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11320     CXXInheritedCtorInitExpr *E) {
11321   QualType T = getDerived().TransformType(E->getType());
11322   if (T.isNull())
11323     return ExprError();
11324 
11325   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11326       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11327   if (!Constructor)
11328     return ExprError();
11329 
11330   if (!getDerived().AlwaysRebuild() &&
11331       T == E->getType() &&
11332       Constructor == E->getConstructor()) {
11333     // Mark the constructor as referenced.
11334     // FIXME: Instantiation-specific
11335     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11336     return E;
11337   }
11338 
11339   return getDerived().RebuildCXXInheritedCtorInitExpr(
11340       T, E->getLocation(), Constructor,
11341       E->constructsVBase(), E->inheritedFromVBase());
11342 }
11343 
11344 /// Transform a C++ temporary-binding expression.
11345 ///
11346 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11347 /// transform the subexpression and return that.
11348 template<typename Derived>
11349 ExprResult
11350 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11351   return getDerived().TransformExpr(E->getSubExpr());
11352 }
11353 
11354 /// Transform a C++ expression that contains cleanups that should
11355 /// be run after the expression is evaluated.
11356 ///
11357 /// Since ExprWithCleanups nodes are implicitly generated, we
11358 /// just transform the subexpression and return that.
11359 template<typename Derived>
11360 ExprResult
11361 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11362   return getDerived().TransformExpr(E->getSubExpr());
11363 }
11364 
11365 template<typename Derived>
11366 ExprResult
11367 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11368                                                     CXXTemporaryObjectExpr *E) {
11369   TypeSourceInfo *T =
11370       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11371   if (!T)
11372     return ExprError();
11373 
11374   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11375       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11376   if (!Constructor)
11377     return ExprError();
11378 
11379   bool ArgumentChanged = false;
11380   SmallVector<Expr*, 8> Args;
11381   Args.reserve(E->getNumArgs());
11382   {
11383     EnterExpressionEvaluationContext Context(
11384         getSema(), EnterExpressionEvaluationContext::InitList,
11385         E->isListInitialization());
11386     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11387                        &ArgumentChanged))
11388       return ExprError();
11389   }
11390 
11391   if (!getDerived().AlwaysRebuild() &&
11392       T == E->getTypeSourceInfo() &&
11393       Constructor == E->getConstructor() &&
11394       !ArgumentChanged) {
11395     // FIXME: Instantiation-specific
11396     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11397     return SemaRef.MaybeBindToTemporary(E);
11398   }
11399 
11400   // FIXME: We should just pass E->isListInitialization(), but we're not
11401   // prepared to handle list-initialization without a child InitListExpr.
11402   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11403   return getDerived().RebuildCXXTemporaryObjectExpr(
11404       T, LParenLoc, Args, E->getEndLoc(),
11405       /*ListInitialization=*/LParenLoc.isInvalid());
11406 }
11407 
11408 template<typename Derived>
11409 ExprResult
11410 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11411   // Transform any init-capture expressions before entering the scope of the
11412   // lambda body, because they are not semantically within that scope.
11413   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11414   struct TransformedInitCapture {
11415     // The location of the ... if the result is retaining a pack expansion.
11416     SourceLocation EllipsisLoc;
11417     // Zero or more expansions of the init-capture.
11418     SmallVector<InitCaptureInfoTy, 4> Expansions;
11419   };
11420   SmallVector<TransformedInitCapture, 4> InitCaptures;
11421   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11422   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11423                                     CEnd = E->capture_end();
11424        C != CEnd; ++C) {
11425     if (!E->isInitCapture(C))
11426       continue;
11427 
11428     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11429     VarDecl *OldVD = C->getCapturedVar();
11430 
11431     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11432                                 Optional<unsigned> NumExpansions) {
11433       ExprResult NewExprInitResult = getDerived().TransformInitializer(
11434           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11435 
11436       if (NewExprInitResult.isInvalid()) {
11437         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11438         return;
11439       }
11440       Expr *NewExprInit = NewExprInitResult.get();
11441 
11442       QualType NewInitCaptureType =
11443           getSema().buildLambdaInitCaptureInitialization(
11444               C->getLocation(), OldVD->getType()->isReferenceType(),
11445               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11446               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11447               NewExprInit);
11448       Result.Expansions.push_back(
11449           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11450     };
11451 
11452     // If this is an init-capture pack, consider expanding the pack now.
11453     if (OldVD->isParameterPack()) {
11454       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11455                                              ->getTypeLoc()
11456                                              .castAs<PackExpansionTypeLoc>();
11457       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11458       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11459 
11460       // Determine whether the set of unexpanded parameter packs can and should
11461       // be expanded.
11462       bool Expand = true;
11463       bool RetainExpansion = false;
11464       Optional<unsigned> OrigNumExpansions =
11465           ExpansionTL.getTypePtr()->getNumExpansions();
11466       Optional<unsigned> NumExpansions = OrigNumExpansions;
11467       if (getDerived().TryExpandParameterPacks(
11468               ExpansionTL.getEllipsisLoc(),
11469               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11470               RetainExpansion, NumExpansions))
11471         return ExprError();
11472       if (Expand) {
11473         for (unsigned I = 0; I != *NumExpansions; ++I) {
11474           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11475           SubstInitCapture(SourceLocation(), None);
11476         }
11477       }
11478       if (!Expand || RetainExpansion) {
11479         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11480         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11481         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11482       }
11483     } else {
11484       SubstInitCapture(SourceLocation(), None);
11485     }
11486   }
11487 
11488   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11489   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11490 
11491   // Transform the template parameters, and add them to the current
11492   // instantiation scope. The null case is handled correctly.
11493   auto TPL = getDerived().TransformTemplateParameterList(
11494       E->getTemplateParameterList());
11495   LSI->GLTemplateParameterList = TPL;
11496 
11497   // Transform the type of the original lambda's call operator.
11498   // The transformation MUST be done in the CurrentInstantiationScope since
11499   // it introduces a mapping of the original to the newly created
11500   // transformed parameters.
11501   TypeSourceInfo *NewCallOpTSI = nullptr;
11502   {
11503     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11504     FunctionProtoTypeLoc OldCallOpFPTL =
11505         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11506 
11507     TypeLocBuilder NewCallOpTLBuilder;
11508     SmallVector<QualType, 4> ExceptionStorage;
11509     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11510     QualType NewCallOpType = TransformFunctionProtoType(
11511         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11512         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11513           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11514                                               ExceptionStorage, Changed);
11515         });
11516     if (NewCallOpType.isNull())
11517       return ExprError();
11518     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11519                                                         NewCallOpType);
11520   }
11521 
11522   // Create the local class that will describe the lambda.
11523   CXXRecordDecl *OldClass = E->getLambdaClass();
11524   CXXRecordDecl *Class
11525     = getSema().createLambdaClosureType(E->getIntroducerRange(),
11526                                         NewCallOpTSI,
11527                                         /*KnownDependent=*/false,
11528                                         E->getCaptureDefault());
11529   getDerived().transformedLocalDecl(OldClass, {Class});
11530 
11531   Optional<std::tuple<unsigned, bool, Decl *>> Mangling;
11532   if (getDerived().ReplacingOriginal())
11533     Mangling = std::make_tuple(OldClass->getLambdaManglingNumber(),
11534                                OldClass->hasKnownLambdaInternalLinkage(),
11535                                OldClass->getLambdaContextDecl());
11536 
11537   // Build the call operator.
11538   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11539       Class, E->getIntroducerRange(), NewCallOpTSI,
11540       E->getCallOperator()->getEndLoc(),
11541       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11542       E->getCallOperator()->getConstexprKind());
11543 
11544   LSI->CallOperator = NewCallOperator;
11545 
11546   for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11547        I != NumParams; ++I) {
11548     auto *P = NewCallOperator->getParamDecl(I);
11549     if (P->hasUninstantiatedDefaultArg()) {
11550       EnterExpressionEvaluationContext Eval(
11551           getSema(),
11552           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11553       ExprResult R = getDerived().TransformExpr(
11554           E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11555       P->setDefaultArg(R.get());
11556     }
11557   }
11558 
11559   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11560   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11561 
11562   // Number the lambda for linkage purposes if necessary.
11563   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
11564 
11565   // Introduce the context of the call operator.
11566   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11567                                  /*NewThisContext*/false);
11568 
11569   // Enter the scope of the lambda.
11570   getSema().buildLambdaScope(LSI, NewCallOperator,
11571                              E->getIntroducerRange(),
11572                              E->getCaptureDefault(),
11573                              E->getCaptureDefaultLoc(),
11574                              E->hasExplicitParameters(),
11575                              E->hasExplicitResultType(),
11576                              E->isMutable());
11577 
11578   bool Invalid = false;
11579 
11580   // Transform captures.
11581   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11582                                  CEnd = E->capture_end();
11583        C != CEnd; ++C) {
11584     // When we hit the first implicit capture, tell Sema that we've finished
11585     // the list of explicit captures.
11586     if (C->isImplicit())
11587       break;
11588 
11589     // Capturing 'this' is trivial.
11590     if (C->capturesThis()) {
11591       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11592                                     /*BuildAndDiagnose*/ true, nullptr,
11593                                     C->getCaptureKind() == LCK_StarThis);
11594       continue;
11595     }
11596     // Captured expression will be recaptured during captured variables
11597     // rebuilding.
11598     if (C->capturesVLAType())
11599       continue;
11600 
11601     // Rebuild init-captures, including the implied field declaration.
11602     if (E->isInitCapture(C)) {
11603       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11604 
11605       VarDecl *OldVD = C->getCapturedVar();
11606       llvm::SmallVector<Decl*, 4> NewVDs;
11607 
11608       for (InitCaptureInfoTy &Info : NewC.Expansions) {
11609         ExprResult Init = Info.first;
11610         QualType InitQualType = Info.second;
11611         if (Init.isInvalid() || InitQualType.isNull()) {
11612           Invalid = true;
11613           break;
11614         }
11615         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11616             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11617             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11618         if (!NewVD) {
11619           Invalid = true;
11620           break;
11621         }
11622         NewVDs.push_back(NewVD);
11623         getSema().addInitCapture(LSI, NewVD);
11624       }
11625 
11626       if (Invalid)
11627         break;
11628 
11629       getDerived().transformedLocalDecl(OldVD, NewVDs);
11630       continue;
11631     }
11632 
11633     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11634 
11635     // Determine the capture kind for Sema.
11636     Sema::TryCaptureKind Kind
11637       = C->isImplicit()? Sema::TryCapture_Implicit
11638                        : C->getCaptureKind() == LCK_ByCopy
11639                            ? Sema::TryCapture_ExplicitByVal
11640                            : Sema::TryCapture_ExplicitByRef;
11641     SourceLocation EllipsisLoc;
11642     if (C->isPackExpansion()) {
11643       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11644       bool ShouldExpand = false;
11645       bool RetainExpansion = false;
11646       Optional<unsigned> NumExpansions;
11647       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11648                                                C->getLocation(),
11649                                                Unexpanded,
11650                                                ShouldExpand, RetainExpansion,
11651                                                NumExpansions)) {
11652         Invalid = true;
11653         continue;
11654       }
11655 
11656       if (ShouldExpand) {
11657         // The transform has determined that we should perform an expansion;
11658         // transform and capture each of the arguments.
11659         // expansion of the pattern. Do so.
11660         VarDecl *Pack = C->getCapturedVar();
11661         for (unsigned I = 0; I != *NumExpansions; ++I) {
11662           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11663           VarDecl *CapturedVar
11664             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11665                                                                Pack));
11666           if (!CapturedVar) {
11667             Invalid = true;
11668             continue;
11669           }
11670 
11671           // Capture the transformed variable.
11672           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11673         }
11674 
11675         // FIXME: Retain a pack expansion if RetainExpansion is true.
11676 
11677         continue;
11678       }
11679 
11680       EllipsisLoc = C->getEllipsisLoc();
11681     }
11682 
11683     // Transform the captured variable.
11684     VarDecl *CapturedVar
11685       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11686                                                          C->getCapturedVar()));
11687     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11688       Invalid = true;
11689       continue;
11690     }
11691 
11692     // Capture the transformed variable.
11693     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11694                                  EllipsisLoc);
11695   }
11696   getSema().finishLambdaExplicitCaptures(LSI);
11697 
11698   // FIXME: Sema's lambda-building mechanism expects us to push an expression
11699   // evaluation context even if we're not transforming the function body.
11700   getSema().PushExpressionEvaluationContext(
11701       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11702 
11703   // Instantiate the body of the lambda expression.
11704   StmtResult Body =
11705       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
11706 
11707   // ActOnLambda* will pop the function scope for us.
11708   FuncScopeCleanup.disable();
11709 
11710   if (Body.isInvalid()) {
11711     SavedContext.pop();
11712     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11713                                /*IsInstantiation=*/true);
11714     return ExprError();
11715   }
11716 
11717   // Copy the LSI before ActOnFinishFunctionBody removes it.
11718   // FIXME: This is dumb. Store the lambda information somewhere that outlives
11719   // the call operator.
11720   auto LSICopy = *LSI;
11721   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11722                                     /*IsInstantiation*/ true);
11723   SavedContext.pop();
11724 
11725   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11726                                    &LSICopy);
11727 }
11728 
11729 template<typename Derived>
11730 StmtResult
11731 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
11732   return TransformStmt(S);
11733 }
11734 
11735 template<typename Derived>
11736 StmtResult
11737 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
11738   // Transform captures.
11739   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11740                                  CEnd = E->capture_end();
11741        C != CEnd; ++C) {
11742     // When we hit the first implicit capture, tell Sema that we've finished
11743     // the list of explicit captures.
11744     if (!C->isImplicit())
11745       continue;
11746 
11747     // Capturing 'this' is trivial.
11748     if (C->capturesThis()) {
11749       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11750                                     /*BuildAndDiagnose*/ true, nullptr,
11751                                     C->getCaptureKind() == LCK_StarThis);
11752       continue;
11753     }
11754     // Captured expression will be recaptured during captured variables
11755     // rebuilding.
11756     if (C->capturesVLAType())
11757       continue;
11758 
11759     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11760     assert(!E->isInitCapture(C) && "implicit init-capture?");
11761 
11762     // Transform the captured variable.
11763     VarDecl *CapturedVar = cast_or_null<VarDecl>(
11764         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
11765     if (!CapturedVar || CapturedVar->isInvalidDecl())
11766       return StmtError();
11767 
11768     // Capture the transformed variable.
11769     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
11770   }
11771 
11772   return S;
11773 }
11774 
11775 template<typename Derived>
11776 ExprResult
11777 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11778                                                   CXXUnresolvedConstructExpr *E) {
11779   TypeSourceInfo *T =
11780       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11781   if (!T)
11782     return ExprError();
11783 
11784   bool ArgumentChanged = false;
11785   SmallVector<Expr*, 8> Args;
11786   Args.reserve(E->arg_size());
11787   {
11788     EnterExpressionEvaluationContext Context(
11789         getSema(), EnterExpressionEvaluationContext::InitList,
11790         E->isListInitialization());
11791     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11792                                     &ArgumentChanged))
11793       return ExprError();
11794   }
11795 
11796   if (!getDerived().AlwaysRebuild() &&
11797       T == E->getTypeSourceInfo() &&
11798       !ArgumentChanged)
11799     return E;
11800 
11801   // FIXME: we're faking the locations of the commas
11802   return getDerived().RebuildCXXUnresolvedConstructExpr(
11803       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11804 }
11805 
11806 template<typename Derived>
11807 ExprResult
11808 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11809                                              CXXDependentScopeMemberExpr *E) {
11810   // Transform the base of the expression.
11811   ExprResult Base((Expr*) nullptr);
11812   Expr *OldBase;
11813   QualType BaseType;
11814   QualType ObjectType;
11815   if (!E->isImplicitAccess()) {
11816     OldBase = E->getBase();
11817     Base = getDerived().TransformExpr(OldBase);
11818     if (Base.isInvalid())
11819       return ExprError();
11820 
11821     // Start the member reference and compute the object's type.
11822     ParsedType ObjectTy;
11823     bool MayBePseudoDestructor = false;
11824     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11825                                                 E->getOperatorLoc(),
11826                                       E->isArrow()? tok::arrow : tok::period,
11827                                                 ObjectTy,
11828                                                 MayBePseudoDestructor);
11829     if (Base.isInvalid())
11830       return ExprError();
11831 
11832     ObjectType = ObjectTy.get();
11833     BaseType = ((Expr*) Base.get())->getType();
11834   } else {
11835     OldBase = nullptr;
11836     BaseType = getDerived().TransformType(E->getBaseType());
11837     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
11838   }
11839 
11840   // Transform the first part of the nested-name-specifier that qualifies
11841   // the member name.
11842   NamedDecl *FirstQualifierInScope
11843     = getDerived().TransformFirstQualifierInScope(
11844                                             E->getFirstQualifierFoundInScope(),
11845                                             E->getQualifierLoc().getBeginLoc());
11846 
11847   NestedNameSpecifierLoc QualifierLoc;
11848   if (E->getQualifier()) {
11849     QualifierLoc
11850       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11851                                                      ObjectType,
11852                                                      FirstQualifierInScope);
11853     if (!QualifierLoc)
11854       return ExprError();
11855   }
11856 
11857   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11858 
11859   // TODO: If this is a conversion-function-id, verify that the
11860   // destination type name (if present) resolves the same way after
11861   // instantiation as it did in the local scope.
11862 
11863   DeclarationNameInfo NameInfo
11864     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11865   if (!NameInfo.getName())
11866     return ExprError();
11867 
11868   if (!E->hasExplicitTemplateArgs()) {
11869     // This is a reference to a member without an explicitly-specified
11870     // template argument list. Optimize for this common case.
11871     if (!getDerived().AlwaysRebuild() &&
11872         Base.get() == OldBase &&
11873         BaseType == E->getBaseType() &&
11874         QualifierLoc == E->getQualifierLoc() &&
11875         NameInfo.getName() == E->getMember() &&
11876         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11877       return E;
11878 
11879     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11880                                                        BaseType,
11881                                                        E->isArrow(),
11882                                                        E->getOperatorLoc(),
11883                                                        QualifierLoc,
11884                                                        TemplateKWLoc,
11885                                                        FirstQualifierInScope,
11886                                                        NameInfo,
11887                                                        /*TemplateArgs*/nullptr);
11888   }
11889 
11890   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11891   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11892                                               E->getNumTemplateArgs(),
11893                                               TransArgs))
11894     return ExprError();
11895 
11896   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11897                                                      BaseType,
11898                                                      E->isArrow(),
11899                                                      E->getOperatorLoc(),
11900                                                      QualifierLoc,
11901                                                      TemplateKWLoc,
11902                                                      FirstQualifierInScope,
11903                                                      NameInfo,
11904                                                      &TransArgs);
11905 }
11906 
11907 template<typename Derived>
11908 ExprResult
11909 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11910   // Transform the base of the expression.
11911   ExprResult Base((Expr*) nullptr);
11912   QualType BaseType;
11913   if (!Old->isImplicitAccess()) {
11914     Base = getDerived().TransformExpr(Old->getBase());
11915     if (Base.isInvalid())
11916       return ExprError();
11917     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11918                                                      Old->isArrow());
11919     if (Base.isInvalid())
11920       return ExprError();
11921     BaseType = Base.get()->getType();
11922   } else {
11923     BaseType = getDerived().TransformType(Old->getBaseType());
11924   }
11925 
11926   NestedNameSpecifierLoc QualifierLoc;
11927   if (Old->getQualifierLoc()) {
11928     QualifierLoc
11929     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11930     if (!QualifierLoc)
11931       return ExprError();
11932   }
11933 
11934   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11935 
11936   LookupResult R(SemaRef, Old->getMemberNameInfo(),
11937                  Sema::LookupOrdinaryName);
11938 
11939   // Transform the declaration set.
11940   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11941     return ExprError();
11942 
11943   // Determine the naming class.
11944   if (Old->getNamingClass()) {
11945     CXXRecordDecl *NamingClass
11946       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11947                                                           Old->getMemberLoc(),
11948                                                         Old->getNamingClass()));
11949     if (!NamingClass)
11950       return ExprError();
11951 
11952     R.setNamingClass(NamingClass);
11953   }
11954 
11955   TemplateArgumentListInfo TransArgs;
11956   if (Old->hasExplicitTemplateArgs()) {
11957     TransArgs.setLAngleLoc(Old->getLAngleLoc());
11958     TransArgs.setRAngleLoc(Old->getRAngleLoc());
11959     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11960                                                 Old->getNumTemplateArgs(),
11961                                                 TransArgs))
11962       return ExprError();
11963   }
11964 
11965   // FIXME: to do this check properly, we will need to preserve the
11966   // first-qualifier-in-scope here, just in case we had a dependent
11967   // base (and therefore couldn't do the check) and a
11968   // nested-name-qualifier (and therefore could do the lookup).
11969   NamedDecl *FirstQualifierInScope = nullptr;
11970 
11971   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11972                                                   BaseType,
11973                                                   Old->getOperatorLoc(),
11974                                                   Old->isArrow(),
11975                                                   QualifierLoc,
11976                                                   TemplateKWLoc,
11977                                                   FirstQualifierInScope,
11978                                                   R,
11979                                               (Old->hasExplicitTemplateArgs()
11980                                                   ? &TransArgs : nullptr));
11981 }
11982 
11983 template<typename Derived>
11984 ExprResult
11985 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11986   EnterExpressionEvaluationContext Unevaluated(
11987       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11988   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11989   if (SubExpr.isInvalid())
11990     return ExprError();
11991 
11992   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11993     return E;
11994 
11995   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11996 }
11997 
11998 template<typename Derived>
11999 ExprResult
12000 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
12001   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
12002   if (Pattern.isInvalid())
12003     return ExprError();
12004 
12005   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
12006     return E;
12007 
12008   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
12009                                            E->getNumExpansions());
12010 }
12011 
12012 template<typename Derived>
12013 ExprResult
12014 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
12015   // If E is not value-dependent, then nothing will change when we transform it.
12016   // Note: This is an instantiation-centric view.
12017   if (!E->isValueDependent())
12018     return E;
12019 
12020   EnterExpressionEvaluationContext Unevaluated(
12021       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
12022 
12023   ArrayRef<TemplateArgument> PackArgs;
12024   TemplateArgument ArgStorage;
12025 
12026   // Find the argument list to transform.
12027   if (E->isPartiallySubstituted()) {
12028     PackArgs = E->getPartialArguments();
12029   } else if (E->isValueDependent()) {
12030     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
12031     bool ShouldExpand = false;
12032     bool RetainExpansion = false;
12033     Optional<unsigned> NumExpansions;
12034     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
12035                                              Unexpanded,
12036                                              ShouldExpand, RetainExpansion,
12037                                              NumExpansions))
12038       return ExprError();
12039 
12040     // If we need to expand the pack, build a template argument from it and
12041     // expand that.
12042     if (ShouldExpand) {
12043       auto *Pack = E->getPack();
12044       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
12045         ArgStorage = getSema().Context.getPackExpansionType(
12046             getSema().Context.getTypeDeclType(TTPD), None);
12047       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
12048         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
12049       } else {
12050         auto *VD = cast<ValueDecl>(Pack);
12051         ExprResult DRE = getSema().BuildDeclRefExpr(
12052             VD, VD->getType().getNonLValueExprType(getSema().Context),
12053             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
12054             E->getPackLoc());
12055         if (DRE.isInvalid())
12056           return ExprError();
12057         ArgStorage = new (getSema().Context) PackExpansionExpr(
12058             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
12059       }
12060       PackArgs = ArgStorage;
12061     }
12062   }
12063 
12064   // If we're not expanding the pack, just transform the decl.
12065   if (!PackArgs.size()) {
12066     auto *Pack = cast_or_null<NamedDecl>(
12067         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
12068     if (!Pack)
12069       return ExprError();
12070     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
12071                                               E->getPackLoc(),
12072                                               E->getRParenLoc(), None, None);
12073   }
12074 
12075   // Try to compute the result without performing a partial substitution.
12076   Optional<unsigned> Result = 0;
12077   for (const TemplateArgument &Arg : PackArgs) {
12078     if (!Arg.isPackExpansion()) {
12079       Result = *Result + 1;
12080       continue;
12081     }
12082 
12083     TemplateArgumentLoc ArgLoc;
12084     InventTemplateArgumentLoc(Arg, ArgLoc);
12085 
12086     // Find the pattern of the pack expansion.
12087     SourceLocation Ellipsis;
12088     Optional<unsigned> OrigNumExpansions;
12089     TemplateArgumentLoc Pattern =
12090         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
12091                                                           OrigNumExpansions);
12092 
12093     // Substitute under the pack expansion. Do not expand the pack (yet).
12094     TemplateArgumentLoc OutPattern;
12095     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12096     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
12097                                                /*Uneval*/ true))
12098       return true;
12099 
12100     // See if we can determine the number of arguments from the result.
12101     Optional<unsigned> NumExpansions =
12102         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
12103     if (!NumExpansions) {
12104       // No: we must be in an alias template expansion, and we're going to need
12105       // to actually expand the packs.
12106       Result = None;
12107       break;
12108     }
12109 
12110     Result = *Result + *NumExpansions;
12111   }
12112 
12113   // Common case: we could determine the number of expansions without
12114   // substituting.
12115   if (Result)
12116     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12117                                               E->getPackLoc(),
12118                                               E->getRParenLoc(), *Result, None);
12119 
12120   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
12121                                                E->getPackLoc());
12122   {
12123     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
12124     typedef TemplateArgumentLocInventIterator<
12125         Derived, const TemplateArgument*> PackLocIterator;
12126     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
12127                                    PackLocIterator(*this, PackArgs.end()),
12128                                    TransformedPackArgs, /*Uneval*/true))
12129       return ExprError();
12130   }
12131 
12132   // Check whether we managed to fully-expand the pack.
12133   // FIXME: Is it possible for us to do so and not hit the early exit path?
12134   SmallVector<TemplateArgument, 8> Args;
12135   bool PartialSubstitution = false;
12136   for (auto &Loc : TransformedPackArgs.arguments()) {
12137     Args.push_back(Loc.getArgument());
12138     if (Loc.getArgument().isPackExpansion())
12139       PartialSubstitution = true;
12140   }
12141 
12142   if (PartialSubstitution)
12143     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12144                                               E->getPackLoc(),
12145                                               E->getRParenLoc(), None, Args);
12146 
12147   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12148                                             E->getPackLoc(), E->getRParenLoc(),
12149                                             Args.size(), None);
12150 }
12151 
12152 template<typename Derived>
12153 ExprResult
12154 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
12155                                           SubstNonTypeTemplateParmPackExpr *E) {
12156   // Default behavior is to do nothing with this transformation.
12157   return E;
12158 }
12159 
12160 template<typename Derived>
12161 ExprResult
12162 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
12163                                           SubstNonTypeTemplateParmExpr *E) {
12164   // Default behavior is to do nothing with this transformation.
12165   return E;
12166 }
12167 
12168 template<typename Derived>
12169 ExprResult
12170 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12171   // Default behavior is to do nothing with this transformation.
12172   return E;
12173 }
12174 
12175 template<typename Derived>
12176 ExprResult
12177 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12178                                                   MaterializeTemporaryExpr *E) {
12179   return getDerived().TransformExpr(E->getSubExpr());
12180 }
12181 
12182 template<typename Derived>
12183 ExprResult
12184 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12185   Expr *Pattern = E->getPattern();
12186 
12187   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12188   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12189   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12190 
12191   // Determine whether the set of unexpanded parameter packs can and should
12192   // be expanded.
12193   bool Expand = true;
12194   bool RetainExpansion = false;
12195   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12196                      NumExpansions = OrigNumExpansions;
12197   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12198                                            Pattern->getSourceRange(),
12199                                            Unexpanded,
12200                                            Expand, RetainExpansion,
12201                                            NumExpansions))
12202     return true;
12203 
12204   if (!Expand) {
12205     // Do not expand any packs here, just transform and rebuild a fold
12206     // expression.
12207     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12208 
12209     ExprResult LHS =
12210         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12211     if (LHS.isInvalid())
12212       return true;
12213 
12214     ExprResult RHS =
12215         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12216     if (RHS.isInvalid())
12217       return true;
12218 
12219     if (!getDerived().AlwaysRebuild() &&
12220         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12221       return E;
12222 
12223     return getDerived().RebuildCXXFoldExpr(
12224         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12225         RHS.get(), E->getEndLoc(), NumExpansions);
12226   }
12227 
12228   // The transform has determined that we should perform an elementwise
12229   // expansion of the pattern. Do so.
12230   ExprResult Result = getDerived().TransformExpr(E->getInit());
12231   if (Result.isInvalid())
12232     return true;
12233   bool LeftFold = E->isLeftFold();
12234 
12235   // If we're retaining an expansion for a right fold, it is the innermost
12236   // component and takes the init (if any).
12237   if (!LeftFold && RetainExpansion) {
12238     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12239 
12240     ExprResult Out = getDerived().TransformExpr(Pattern);
12241     if (Out.isInvalid())
12242       return true;
12243 
12244     Result = getDerived().RebuildCXXFoldExpr(
12245         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12246         Result.get(), E->getEndLoc(), OrigNumExpansions);
12247     if (Result.isInvalid())
12248       return true;
12249   }
12250 
12251   for (unsigned I = 0; I != *NumExpansions; ++I) {
12252     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12253         getSema(), LeftFold ? I : *NumExpansions - I - 1);
12254     ExprResult Out = getDerived().TransformExpr(Pattern);
12255     if (Out.isInvalid())
12256       return true;
12257 
12258     if (Out.get()->containsUnexpandedParameterPack()) {
12259       // We still have a pack; retain a pack expansion for this slice.
12260       Result = getDerived().RebuildCXXFoldExpr(
12261           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12262           E->getOperator(), E->getEllipsisLoc(),
12263           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12264           OrigNumExpansions);
12265     } else if (Result.isUsable()) {
12266       // We've got down to a single element; build a binary operator.
12267       Result = getDerived().RebuildBinaryOperator(
12268           E->getEllipsisLoc(), E->getOperator(),
12269           LeftFold ? Result.get() : Out.get(),
12270           LeftFold ? Out.get() : Result.get());
12271     } else
12272       Result = Out;
12273 
12274     if (Result.isInvalid())
12275       return true;
12276   }
12277 
12278   // If we're retaining an expansion for a left fold, it is the outermost
12279   // component and takes the complete expansion so far as its init (if any).
12280   if (LeftFold && RetainExpansion) {
12281     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12282 
12283     ExprResult Out = getDerived().TransformExpr(Pattern);
12284     if (Out.isInvalid())
12285       return true;
12286 
12287     Result = getDerived().RebuildCXXFoldExpr(
12288         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12289         Out.get(), E->getEndLoc(), OrigNumExpansions);
12290     if (Result.isInvalid())
12291       return true;
12292   }
12293 
12294   // If we had no init and an empty pack, and we're not retaining an expansion,
12295   // then produce a fallback value or error.
12296   if (Result.isUnset())
12297     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12298                                                 E->getOperator());
12299 
12300   return Result;
12301 }
12302 
12303 template<typename Derived>
12304 ExprResult
12305 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12306     CXXStdInitializerListExpr *E) {
12307   return getDerived().TransformExpr(E->getSubExpr());
12308 }
12309 
12310 template<typename Derived>
12311 ExprResult
12312 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12313   return SemaRef.MaybeBindToTemporary(E);
12314 }
12315 
12316 template<typename Derived>
12317 ExprResult
12318 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12319   return E;
12320 }
12321 
12322 template<typename Derived>
12323 ExprResult
12324 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12325   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12326   if (SubExpr.isInvalid())
12327     return ExprError();
12328 
12329   if (!getDerived().AlwaysRebuild() &&
12330       SubExpr.get() == E->getSubExpr())
12331     return E;
12332 
12333   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12334 }
12335 
12336 template<typename Derived>
12337 ExprResult
12338 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12339   // Transform each of the elements.
12340   SmallVector<Expr *, 8> Elements;
12341   bool ArgChanged = false;
12342   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12343                                   /*IsCall=*/false, Elements, &ArgChanged))
12344     return ExprError();
12345 
12346   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12347     return SemaRef.MaybeBindToTemporary(E);
12348 
12349   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12350                                               Elements.data(),
12351                                               Elements.size());
12352 }
12353 
12354 template<typename Derived>
12355 ExprResult
12356 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12357                                                     ObjCDictionaryLiteral *E) {
12358   // Transform each of the elements.
12359   SmallVector<ObjCDictionaryElement, 8> Elements;
12360   bool ArgChanged = false;
12361   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12362     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12363 
12364     if (OrigElement.isPackExpansion()) {
12365       // This key/value element is a pack expansion.
12366       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12367       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12368       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12369       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12370 
12371       // Determine whether the set of unexpanded parameter packs can
12372       // and should be expanded.
12373       bool Expand = true;
12374       bool RetainExpansion = false;
12375       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12376       Optional<unsigned> NumExpansions = OrigNumExpansions;
12377       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12378                                OrigElement.Value->getEndLoc());
12379       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12380                                                PatternRange, Unexpanded, Expand,
12381                                                RetainExpansion, NumExpansions))
12382         return ExprError();
12383 
12384       if (!Expand) {
12385         // The transform has determined that we should perform a simple
12386         // transformation on the pack expansion, producing another pack
12387         // expansion.
12388         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12389         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12390         if (Key.isInvalid())
12391           return ExprError();
12392 
12393         if (Key.get() != OrigElement.Key)
12394           ArgChanged = true;
12395 
12396         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12397         if (Value.isInvalid())
12398           return ExprError();
12399 
12400         if (Value.get() != OrigElement.Value)
12401           ArgChanged = true;
12402 
12403         ObjCDictionaryElement Expansion = {
12404           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12405         };
12406         Elements.push_back(Expansion);
12407         continue;
12408       }
12409 
12410       // Record right away that the argument was changed.  This needs
12411       // to happen even if the array expands to nothing.
12412       ArgChanged = true;
12413 
12414       // The transform has determined that we should perform an elementwise
12415       // expansion of the pattern. Do so.
12416       for (unsigned I = 0; I != *NumExpansions; ++I) {
12417         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12418         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12419         if (Key.isInvalid())
12420           return ExprError();
12421 
12422         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12423         if (Value.isInvalid())
12424           return ExprError();
12425 
12426         ObjCDictionaryElement Element = {
12427           Key.get(), Value.get(), SourceLocation(), NumExpansions
12428         };
12429 
12430         // If any unexpanded parameter packs remain, we still have a
12431         // pack expansion.
12432         // FIXME: Can this really happen?
12433         if (Key.get()->containsUnexpandedParameterPack() ||
12434             Value.get()->containsUnexpandedParameterPack())
12435           Element.EllipsisLoc = OrigElement.EllipsisLoc;
12436 
12437         Elements.push_back(Element);
12438       }
12439 
12440       // FIXME: Retain a pack expansion if RetainExpansion is true.
12441 
12442       // We've finished with this pack expansion.
12443       continue;
12444     }
12445 
12446     // Transform and check key.
12447     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12448     if (Key.isInvalid())
12449       return ExprError();
12450 
12451     if (Key.get() != OrigElement.Key)
12452       ArgChanged = true;
12453 
12454     // Transform and check value.
12455     ExprResult Value
12456       = getDerived().TransformExpr(OrigElement.Value);
12457     if (Value.isInvalid())
12458       return ExprError();
12459 
12460     if (Value.get() != OrigElement.Value)
12461       ArgChanged = true;
12462 
12463     ObjCDictionaryElement Element = {
12464       Key.get(), Value.get(), SourceLocation(), None
12465     };
12466     Elements.push_back(Element);
12467   }
12468 
12469   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12470     return SemaRef.MaybeBindToTemporary(E);
12471 
12472   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12473                                                    Elements);
12474 }
12475 
12476 template<typename Derived>
12477 ExprResult
12478 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12479   TypeSourceInfo *EncodedTypeInfo
12480     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12481   if (!EncodedTypeInfo)
12482     return ExprError();
12483 
12484   if (!getDerived().AlwaysRebuild() &&
12485       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12486     return E;
12487 
12488   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12489                                             EncodedTypeInfo,
12490                                             E->getRParenLoc());
12491 }
12492 
12493 template<typename Derived>
12494 ExprResult TreeTransform<Derived>::
12495 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12496   // This is a kind of implicit conversion, and it needs to get dropped
12497   // and recomputed for the same general reasons that ImplicitCastExprs
12498   // do, as well a more specific one: this expression is only valid when
12499   // it appears *immediately* as an argument expression.
12500   return getDerived().TransformExpr(E->getSubExpr());
12501 }
12502 
12503 template<typename Derived>
12504 ExprResult TreeTransform<Derived>::
12505 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12506   TypeSourceInfo *TSInfo
12507     = getDerived().TransformType(E->getTypeInfoAsWritten());
12508   if (!TSInfo)
12509     return ExprError();
12510 
12511   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12512   if (Result.isInvalid())
12513     return ExprError();
12514 
12515   if (!getDerived().AlwaysRebuild() &&
12516       TSInfo == E->getTypeInfoAsWritten() &&
12517       Result.get() == E->getSubExpr())
12518     return E;
12519 
12520   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12521                                       E->getBridgeKeywordLoc(), TSInfo,
12522                                       Result.get());
12523 }
12524 
12525 template <typename Derived>
12526 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12527     ObjCAvailabilityCheckExpr *E) {
12528   return E;
12529 }
12530 
12531 template<typename Derived>
12532 ExprResult
12533 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12534   // Transform arguments.
12535   bool ArgChanged = false;
12536   SmallVector<Expr*, 8> Args;
12537   Args.reserve(E->getNumArgs());
12538   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12539                                   &ArgChanged))
12540     return ExprError();
12541 
12542   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12543     // Class message: transform the receiver type.
12544     TypeSourceInfo *ReceiverTypeInfo
12545       = getDerived().TransformType(E->getClassReceiverTypeInfo());
12546     if (!ReceiverTypeInfo)
12547       return ExprError();
12548 
12549     // If nothing changed, just retain the existing message send.
12550     if (!getDerived().AlwaysRebuild() &&
12551         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12552       return SemaRef.MaybeBindToTemporary(E);
12553 
12554     // Build a new class message send.
12555     SmallVector<SourceLocation, 16> SelLocs;
12556     E->getSelectorLocs(SelLocs);
12557     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12558                                                E->getSelector(),
12559                                                SelLocs,
12560                                                E->getMethodDecl(),
12561                                                E->getLeftLoc(),
12562                                                Args,
12563                                                E->getRightLoc());
12564   }
12565   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12566            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12567     if (!E->getMethodDecl())
12568       return ExprError();
12569 
12570     // Build a new class message send to 'super'.
12571     SmallVector<SourceLocation, 16> SelLocs;
12572     E->getSelectorLocs(SelLocs);
12573     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12574                                                E->getSelector(),
12575                                                SelLocs,
12576                                                E->getReceiverType(),
12577                                                E->getMethodDecl(),
12578                                                E->getLeftLoc(),
12579                                                Args,
12580                                                E->getRightLoc());
12581   }
12582 
12583   // Instance message: transform the receiver
12584   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12585          "Only class and instance messages may be instantiated");
12586   ExprResult Receiver
12587     = getDerived().TransformExpr(E->getInstanceReceiver());
12588   if (Receiver.isInvalid())
12589     return ExprError();
12590 
12591   // If nothing changed, just retain the existing message send.
12592   if (!getDerived().AlwaysRebuild() &&
12593       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12594     return SemaRef.MaybeBindToTemporary(E);
12595 
12596   // Build a new instance message send.
12597   SmallVector<SourceLocation, 16> SelLocs;
12598   E->getSelectorLocs(SelLocs);
12599   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12600                                              E->getSelector(),
12601                                              SelLocs,
12602                                              E->getMethodDecl(),
12603                                              E->getLeftLoc(),
12604                                              Args,
12605                                              E->getRightLoc());
12606 }
12607 
12608 template<typename Derived>
12609 ExprResult
12610 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12611   return E;
12612 }
12613 
12614 template<typename Derived>
12615 ExprResult
12616 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12617   return E;
12618 }
12619 
12620 template<typename Derived>
12621 ExprResult
12622 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12623   // Transform the base expression.
12624   ExprResult Base = getDerived().TransformExpr(E->getBase());
12625   if (Base.isInvalid())
12626     return ExprError();
12627 
12628   // We don't need to transform the ivar; it will never change.
12629 
12630   // If nothing changed, just retain the existing expression.
12631   if (!getDerived().AlwaysRebuild() &&
12632       Base.get() == E->getBase())
12633     return E;
12634 
12635   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12636                                              E->getLocation(),
12637                                              E->isArrow(), E->isFreeIvar());
12638 }
12639 
12640 template<typename Derived>
12641 ExprResult
12642 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12643   // 'super' and types never change. Property never changes. Just
12644   // retain the existing expression.
12645   if (!E->isObjectReceiver())
12646     return E;
12647 
12648   // Transform the base expression.
12649   ExprResult Base = getDerived().TransformExpr(E->getBase());
12650   if (Base.isInvalid())
12651     return ExprError();
12652 
12653   // We don't need to transform the property; it will never change.
12654 
12655   // If nothing changed, just retain the existing expression.
12656   if (!getDerived().AlwaysRebuild() &&
12657       Base.get() == E->getBase())
12658     return E;
12659 
12660   if (E->isExplicitProperty())
12661     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12662                                                    E->getExplicitProperty(),
12663                                                    E->getLocation());
12664 
12665   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12666                                                  SemaRef.Context.PseudoObjectTy,
12667                                                  E->getImplicitPropertyGetter(),
12668                                                  E->getImplicitPropertySetter(),
12669                                                  E->getLocation());
12670 }
12671 
12672 template<typename Derived>
12673 ExprResult
12674 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12675   // Transform the base expression.
12676   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12677   if (Base.isInvalid())
12678     return ExprError();
12679 
12680   // Transform the key expression.
12681   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12682   if (Key.isInvalid())
12683     return ExprError();
12684 
12685   // If nothing changed, just retain the existing expression.
12686   if (!getDerived().AlwaysRebuild() &&
12687       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12688     return E;
12689 
12690   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12691                                                   Base.get(), Key.get(),
12692                                                   E->getAtIndexMethodDecl(),
12693                                                   E->setAtIndexMethodDecl());
12694 }
12695 
12696 template<typename Derived>
12697 ExprResult
12698 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12699   // Transform the base expression.
12700   ExprResult Base = getDerived().TransformExpr(E->getBase());
12701   if (Base.isInvalid())
12702     return ExprError();
12703 
12704   // If nothing changed, just retain the existing expression.
12705   if (!getDerived().AlwaysRebuild() &&
12706       Base.get() == E->getBase())
12707     return E;
12708 
12709   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12710                                          E->getOpLoc(),
12711                                          E->isArrow());
12712 }
12713 
12714 template<typename Derived>
12715 ExprResult
12716 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12717   bool ArgumentChanged = false;
12718   SmallVector<Expr*, 8> SubExprs;
12719   SubExprs.reserve(E->getNumSubExprs());
12720   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12721                                   SubExprs, &ArgumentChanged))
12722     return ExprError();
12723 
12724   if (!getDerived().AlwaysRebuild() &&
12725       !ArgumentChanged)
12726     return E;
12727 
12728   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12729                                                SubExprs,
12730                                                E->getRParenLoc());
12731 }
12732 
12733 template<typename Derived>
12734 ExprResult
12735 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12736   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12737   if (SrcExpr.isInvalid())
12738     return ExprError();
12739 
12740   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12741   if (!Type)
12742     return ExprError();
12743 
12744   if (!getDerived().AlwaysRebuild() &&
12745       Type == E->getTypeSourceInfo() &&
12746       SrcExpr.get() == E->getSrcExpr())
12747     return E;
12748 
12749   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12750                                                SrcExpr.get(), Type,
12751                                                E->getRParenLoc());
12752 }
12753 
12754 template<typename Derived>
12755 ExprResult
12756 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12757   BlockDecl *oldBlock = E->getBlockDecl();
12758 
12759   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12760   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12761 
12762   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12763   blockScope->TheDecl->setBlockMissingReturnType(
12764                          oldBlock->blockMissingReturnType());
12765 
12766   SmallVector<ParmVarDecl*, 4> params;
12767   SmallVector<QualType, 4> paramTypes;
12768 
12769   const FunctionProtoType *exprFunctionType = E->getFunctionType();
12770 
12771   // Parameter substitution.
12772   Sema::ExtParameterInfoBuilder extParamInfos;
12773   if (getDerived().TransformFunctionTypeParams(
12774           E->getCaretLocation(), oldBlock->parameters(), nullptr,
12775           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
12776           extParamInfos)) {
12777     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12778     return ExprError();
12779   }
12780 
12781   QualType exprResultType =
12782       getDerived().TransformType(exprFunctionType->getReturnType());
12783 
12784   auto epi = exprFunctionType->getExtProtoInfo();
12785   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12786 
12787   QualType functionType =
12788     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12789   blockScope->FunctionType = functionType;
12790 
12791   // Set the parameters on the block decl.
12792   if (!params.empty())
12793     blockScope->TheDecl->setParams(params);
12794 
12795   if (!oldBlock->blockMissingReturnType()) {
12796     blockScope->HasImplicitReturnType = false;
12797     blockScope->ReturnType = exprResultType;
12798   }
12799 
12800   // Transform the body
12801   StmtResult body = getDerived().TransformStmt(E->getBody());
12802   if (body.isInvalid()) {
12803     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12804     return ExprError();
12805   }
12806 
12807 #ifndef NDEBUG
12808   // In builds with assertions, make sure that we captured everything we
12809   // captured before.
12810   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12811     for (const auto &I : oldBlock->captures()) {
12812       VarDecl *oldCapture = I.getVariable();
12813 
12814       // Ignore parameter packs.
12815       if (oldCapture->isParameterPack())
12816         continue;
12817 
12818       VarDecl *newCapture =
12819         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12820                                                  oldCapture));
12821       assert(blockScope->CaptureMap.count(newCapture));
12822     }
12823     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12824   }
12825 #endif
12826 
12827   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12828                                     /*Scope=*/nullptr);
12829 }
12830 
12831 template<typename Derived>
12832 ExprResult
12833 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12834   llvm_unreachable("Cannot transform asType expressions yet");
12835 }
12836 
12837 template<typename Derived>
12838 ExprResult
12839 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12840   bool ArgumentChanged = false;
12841   SmallVector<Expr*, 8> SubExprs;
12842   SubExprs.reserve(E->getNumSubExprs());
12843   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12844                                   SubExprs, &ArgumentChanged))
12845     return ExprError();
12846 
12847   if (!getDerived().AlwaysRebuild() &&
12848       !ArgumentChanged)
12849     return E;
12850 
12851   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12852                                         E->getOp(), E->getRParenLoc());
12853 }
12854 
12855 //===----------------------------------------------------------------------===//
12856 // Type reconstruction
12857 //===----------------------------------------------------------------------===//
12858 
12859 template<typename Derived>
12860 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12861                                                     SourceLocation Star) {
12862   return SemaRef.BuildPointerType(PointeeType, Star,
12863                                   getDerived().getBaseEntity());
12864 }
12865 
12866 template<typename Derived>
12867 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12868                                                          SourceLocation Star) {
12869   return SemaRef.BuildBlockPointerType(PointeeType, Star,
12870                                        getDerived().getBaseEntity());
12871 }
12872 
12873 template<typename Derived>
12874 QualType
12875 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12876                                              bool WrittenAsLValue,
12877                                              SourceLocation Sigil) {
12878   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12879                                     Sigil, getDerived().getBaseEntity());
12880 }
12881 
12882 template<typename Derived>
12883 QualType
12884 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12885                                                  QualType ClassType,
12886                                                  SourceLocation Sigil) {
12887   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12888                                         getDerived().getBaseEntity());
12889 }
12890 
12891 template<typename Derived>
12892 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12893            const ObjCTypeParamDecl *Decl,
12894            SourceLocation ProtocolLAngleLoc,
12895            ArrayRef<ObjCProtocolDecl *> Protocols,
12896            ArrayRef<SourceLocation> ProtocolLocs,
12897            SourceLocation ProtocolRAngleLoc) {
12898   return SemaRef.BuildObjCTypeParamType(Decl,
12899                                         ProtocolLAngleLoc, Protocols,
12900                                         ProtocolLocs, ProtocolRAngleLoc,
12901                                         /*FailOnError=*/true);
12902 }
12903 
12904 template<typename Derived>
12905 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12906            QualType BaseType,
12907            SourceLocation Loc,
12908            SourceLocation TypeArgsLAngleLoc,
12909            ArrayRef<TypeSourceInfo *> TypeArgs,
12910            SourceLocation TypeArgsRAngleLoc,
12911            SourceLocation ProtocolLAngleLoc,
12912            ArrayRef<ObjCProtocolDecl *> Protocols,
12913            ArrayRef<SourceLocation> ProtocolLocs,
12914            SourceLocation ProtocolRAngleLoc) {
12915   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12916                                      TypeArgs, TypeArgsRAngleLoc,
12917                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
12918                                      ProtocolRAngleLoc,
12919                                      /*FailOnError=*/true);
12920 }
12921 
12922 template<typename Derived>
12923 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12924            QualType PointeeType,
12925            SourceLocation Star) {
12926   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12927 }
12928 
12929 template<typename Derived>
12930 QualType
12931 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12932                                          ArrayType::ArraySizeModifier SizeMod,
12933                                          const llvm::APInt *Size,
12934                                          Expr *SizeExpr,
12935                                          unsigned IndexTypeQuals,
12936                                          SourceRange BracketsRange) {
12937   if (SizeExpr || !Size)
12938     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12939                                   IndexTypeQuals, BracketsRange,
12940                                   getDerived().getBaseEntity());
12941 
12942   QualType Types[] = {
12943     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12944     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12945     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12946   };
12947   const unsigned NumTypes = llvm::array_lengthof(Types);
12948   QualType SizeType;
12949   for (unsigned I = 0; I != NumTypes; ++I)
12950     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12951       SizeType = Types[I];
12952       break;
12953     }
12954 
12955   // Note that we can return a VariableArrayType here in the case where
12956   // the element type was a dependent VariableArrayType.
12957   IntegerLiteral *ArraySize
12958       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12959                                /*FIXME*/BracketsRange.getBegin());
12960   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12961                                 IndexTypeQuals, BracketsRange,
12962                                 getDerived().getBaseEntity());
12963 }
12964 
12965 template<typename Derived>
12966 QualType
12967 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12968                                                  ArrayType::ArraySizeModifier SizeMod,
12969                                                  const llvm::APInt &Size,
12970                                                  Expr *SizeExpr,
12971                                                  unsigned IndexTypeQuals,
12972                                                  SourceRange BracketsRange) {
12973   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
12974                                         IndexTypeQuals, BracketsRange);
12975 }
12976 
12977 template<typename Derived>
12978 QualType
12979 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12980                                           ArrayType::ArraySizeModifier SizeMod,
12981                                                  unsigned IndexTypeQuals,
12982                                                    SourceRange BracketsRange) {
12983   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12984                                        IndexTypeQuals, BracketsRange);
12985 }
12986 
12987 template<typename Derived>
12988 QualType
12989 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12990                                           ArrayType::ArraySizeModifier SizeMod,
12991                                                  Expr *SizeExpr,
12992                                                  unsigned IndexTypeQuals,
12993                                                  SourceRange BracketsRange) {
12994   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12995                                        SizeExpr,
12996                                        IndexTypeQuals, BracketsRange);
12997 }
12998 
12999 template<typename Derived>
13000 QualType
13001 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
13002                                           ArrayType::ArraySizeModifier SizeMod,
13003                                                        Expr *SizeExpr,
13004                                                        unsigned IndexTypeQuals,
13005                                                    SourceRange BracketsRange) {
13006   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
13007                                        SizeExpr,
13008                                        IndexTypeQuals, BracketsRange);
13009 }
13010 
13011 template <typename Derived>
13012 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
13013     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
13014   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
13015                                           AttributeLoc);
13016 }
13017 
13018 template <typename Derived>
13019 QualType
13020 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
13021                                           unsigned NumElements,
13022                                           VectorType::VectorKind VecKind) {
13023   // FIXME: semantic checking!
13024   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
13025 }
13026 
13027 template <typename Derived>
13028 QualType TreeTransform<Derived>::RebuildDependentVectorType(
13029     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
13030     VectorType::VectorKind VecKind) {
13031   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
13032 }
13033 
13034 template<typename Derived>
13035 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
13036                                                       unsigned NumElements,
13037                                                  SourceLocation AttributeLoc) {
13038   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
13039                           NumElements, true);
13040   IntegerLiteral *VectorSize
13041     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
13042                              AttributeLoc);
13043   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
13044 }
13045 
13046 template<typename Derived>
13047 QualType
13048 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
13049                                                            Expr *SizeExpr,
13050                                                   SourceLocation AttributeLoc) {
13051   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
13052 }
13053 
13054 template<typename Derived>
13055 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
13056     QualType T,
13057     MutableArrayRef<QualType> ParamTypes,
13058     const FunctionProtoType::ExtProtoInfo &EPI) {
13059   return SemaRef.BuildFunctionType(T, ParamTypes,
13060                                    getDerived().getBaseLocation(),
13061                                    getDerived().getBaseEntity(),
13062                                    EPI);
13063 }
13064 
13065 template<typename Derived>
13066 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
13067   return SemaRef.Context.getFunctionNoProtoType(T);
13068 }
13069 
13070 template<typename Derived>
13071 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
13072                                                             Decl *D) {
13073   assert(D && "no decl found");
13074   if (D->isInvalidDecl()) return QualType();
13075 
13076   // FIXME: Doesn't account for ObjCInterfaceDecl!
13077   TypeDecl *Ty;
13078   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
13079     // A valid resolved using typename pack expansion decl can have multiple
13080     // UsingDecls, but they must each have exactly one type, and it must be
13081     // the same type in every case. But we must have at least one expansion!
13082     if (UPD->expansions().empty()) {
13083       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
13084           << UPD->isCXXClassMember() << UPD;
13085       return QualType();
13086     }
13087 
13088     // We might still have some unresolved types. Try to pick a resolved type
13089     // if we can. The final instantiation will check that the remaining
13090     // unresolved types instantiate to the type we pick.
13091     QualType FallbackT;
13092     QualType T;
13093     for (auto *E : UPD->expansions()) {
13094       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
13095       if (ThisT.isNull())
13096         continue;
13097       else if (ThisT->getAs<UnresolvedUsingType>())
13098         FallbackT = ThisT;
13099       else if (T.isNull())
13100         T = ThisT;
13101       else
13102         assert(getSema().Context.hasSameType(ThisT, T) &&
13103                "mismatched resolved types in using pack expansion");
13104     }
13105     return T.isNull() ? FallbackT : T;
13106   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
13107     assert(Using->hasTypename() &&
13108            "UnresolvedUsingTypenameDecl transformed to non-typename using");
13109 
13110     // A valid resolved using typename decl points to exactly one type decl.
13111     assert(++Using->shadow_begin() == Using->shadow_end());
13112     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
13113   } else {
13114     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
13115            "UnresolvedUsingTypenameDecl transformed to non-using decl");
13116     Ty = cast<UnresolvedUsingTypenameDecl>(D);
13117   }
13118 
13119   return SemaRef.Context.getTypeDeclType(Ty);
13120 }
13121 
13122 template<typename Derived>
13123 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
13124                                                        SourceLocation Loc) {
13125   return SemaRef.BuildTypeofExprType(E, Loc);
13126 }
13127 
13128 template<typename Derived>
13129 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
13130   return SemaRef.Context.getTypeOfType(Underlying);
13131 }
13132 
13133 template<typename Derived>
13134 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
13135                                                      SourceLocation Loc) {
13136   return SemaRef.BuildDecltypeType(E, Loc);
13137 }
13138 
13139 template<typename Derived>
13140 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
13141                                             UnaryTransformType::UTTKind UKind,
13142                                             SourceLocation Loc) {
13143   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
13144 }
13145 
13146 template<typename Derived>
13147 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
13148                                                       TemplateName Template,
13149                                              SourceLocation TemplateNameLoc,
13150                                      TemplateArgumentListInfo &TemplateArgs) {
13151   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
13152 }
13153 
13154 template<typename Derived>
13155 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
13156                                                    SourceLocation KWLoc) {
13157   return SemaRef.BuildAtomicType(ValueType, KWLoc);
13158 }
13159 
13160 template<typename Derived>
13161 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
13162                                                  SourceLocation KWLoc,
13163                                                  bool isReadPipe) {
13164   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
13165                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
13166 }
13167 
13168 template<typename Derived>
13169 TemplateName
13170 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13171                                             bool TemplateKW,
13172                                             TemplateDecl *Template) {
13173   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13174                                                   Template);
13175 }
13176 
13177 template<typename Derived>
13178 TemplateName
13179 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13180                                             SourceLocation TemplateKWLoc,
13181                                             const IdentifierInfo &Name,
13182                                             SourceLocation NameLoc,
13183                                             QualType ObjectType,
13184                                             NamedDecl *FirstQualifierInScope,
13185                                             bool AllowInjectedClassName) {
13186   UnqualifiedId TemplateName;
13187   TemplateName.setIdentifier(&Name, NameLoc);
13188   Sema::TemplateTy Template;
13189   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13190                                        SS, TemplateKWLoc, TemplateName,
13191                                        ParsedType::make(ObjectType),
13192                                        /*EnteringContext=*/false,
13193                                        Template, AllowInjectedClassName);
13194   return Template.get();
13195 }
13196 
13197 template<typename Derived>
13198 TemplateName
13199 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13200                                             SourceLocation TemplateKWLoc,
13201                                             OverloadedOperatorKind Operator,
13202                                             SourceLocation NameLoc,
13203                                             QualType ObjectType,
13204                                             bool AllowInjectedClassName) {
13205   UnqualifiedId Name;
13206   // FIXME: Bogus location information.
13207   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13208   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13209   Sema::TemplateTy Template;
13210   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13211                                        SS, TemplateKWLoc, Name,
13212                                        ParsedType::make(ObjectType),
13213                                        /*EnteringContext=*/false,
13214                                        Template, AllowInjectedClassName);
13215   return Template.get();
13216 }
13217 
13218 template<typename Derived>
13219 ExprResult
13220 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13221                                                    SourceLocation OpLoc,
13222                                                    Expr *OrigCallee,
13223                                                    Expr *First,
13224                                                    Expr *Second) {
13225   Expr *Callee = OrigCallee->IgnoreParenCasts();
13226   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13227 
13228   if (First->getObjectKind() == OK_ObjCProperty) {
13229     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13230     if (BinaryOperator::isAssignmentOp(Opc))
13231       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13232                                                  First, Second);
13233     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13234     if (Result.isInvalid())
13235       return ExprError();
13236     First = Result.get();
13237   }
13238 
13239   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13240     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13241     if (Result.isInvalid())
13242       return ExprError();
13243     Second = Result.get();
13244   }
13245 
13246   // Determine whether this should be a builtin operation.
13247   if (Op == OO_Subscript) {
13248     if (!First->getType()->isOverloadableType() &&
13249         !Second->getType()->isOverloadableType())
13250       return getSema().CreateBuiltinArraySubscriptExpr(
13251           First, Callee->getBeginLoc(), Second, OpLoc);
13252   } else if (Op == OO_Arrow) {
13253     // -> is never a builtin operation.
13254     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13255   } else if (Second == nullptr || isPostIncDec) {
13256     if (!First->getType()->isOverloadableType() ||
13257         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13258       // The argument is not of overloadable type, or this is an expression
13259       // of the form &Class::member, so try to create a built-in unary
13260       // operation.
13261       UnaryOperatorKind Opc
13262         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13263 
13264       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13265     }
13266   } else {
13267     if (!First->getType()->isOverloadableType() &&
13268         !Second->getType()->isOverloadableType()) {
13269       // Neither of the arguments is an overloadable type, so try to
13270       // create a built-in binary operation.
13271       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13272       ExprResult Result
13273         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13274       if (Result.isInvalid())
13275         return ExprError();
13276 
13277       return Result;
13278     }
13279   }
13280 
13281   // Compute the transformed set of functions (and function templates) to be
13282   // used during overload resolution.
13283   UnresolvedSet<16> Functions;
13284   bool RequiresADL;
13285 
13286   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13287     Functions.append(ULE->decls_begin(), ULE->decls_end());
13288     // If the overload could not be resolved in the template definition
13289     // (because we had a dependent argument), ADL is performed as part of
13290     // template instantiation.
13291     RequiresADL = ULE->requiresADL();
13292   } else {
13293     // If we've resolved this to a particular non-member function, just call
13294     // that function. If we resolved it to a member function,
13295     // CreateOverloaded* will find that function for us.
13296     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13297     if (!isa<CXXMethodDecl>(ND))
13298       Functions.addDecl(ND);
13299     RequiresADL = false;
13300   }
13301 
13302   // Add any functions found via argument-dependent lookup.
13303   Expr *Args[2] = { First, Second };
13304   unsigned NumArgs = 1 + (Second != nullptr);
13305 
13306   // Create the overloaded operator invocation for unary operators.
13307   if (NumArgs == 1 || isPostIncDec) {
13308     UnaryOperatorKind Opc
13309       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13310     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13311                                            RequiresADL);
13312   }
13313 
13314   if (Op == OO_Subscript) {
13315     SourceLocation LBrace;
13316     SourceLocation RBrace;
13317 
13318     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13319         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13320         LBrace = SourceLocation::getFromRawEncoding(
13321                     NameLoc.CXXOperatorName.BeginOpNameLoc);
13322         RBrace = SourceLocation::getFromRawEncoding(
13323                     NameLoc.CXXOperatorName.EndOpNameLoc);
13324     } else {
13325       LBrace = Callee->getBeginLoc();
13326       RBrace = OpLoc;
13327     }
13328 
13329     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13330                                                       First, Second);
13331   }
13332 
13333   // Create the overloaded operator invocation for binary operators.
13334   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13335   ExprResult Result = SemaRef.CreateOverloadedBinOp(
13336       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13337   if (Result.isInvalid())
13338     return ExprError();
13339 
13340   return Result;
13341 }
13342 
13343 template<typename Derived>
13344 ExprResult
13345 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13346                                                      SourceLocation OperatorLoc,
13347                                                        bool isArrow,
13348                                                        CXXScopeSpec &SS,
13349                                                      TypeSourceInfo *ScopeType,
13350                                                        SourceLocation CCLoc,
13351                                                        SourceLocation TildeLoc,
13352                                         PseudoDestructorTypeStorage Destroyed) {
13353   QualType BaseType = Base->getType();
13354   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13355       (!isArrow && !BaseType->getAs<RecordType>()) ||
13356       (isArrow && BaseType->getAs<PointerType>() &&
13357        !BaseType->castAs<PointerType>()->getPointeeType()
13358                                               ->template getAs<RecordType>())){
13359     // This pseudo-destructor expression is still a pseudo-destructor.
13360     return SemaRef.BuildPseudoDestructorExpr(
13361         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13362         CCLoc, TildeLoc, Destroyed);
13363   }
13364 
13365   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13366   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13367                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13368   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13369   NameInfo.setNamedTypeInfo(DestroyedType);
13370 
13371   // The scope type is now known to be a valid nested name specifier
13372   // component. Tack it on to the end of the nested name specifier.
13373   if (ScopeType) {
13374     if (!ScopeType->getType()->getAs<TagType>()) {
13375       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13376                      diag::err_expected_class_or_namespace)
13377           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13378       return ExprError();
13379     }
13380     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13381               CCLoc);
13382   }
13383 
13384   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13385   return getSema().BuildMemberReferenceExpr(Base, BaseType,
13386                                             OperatorLoc, isArrow,
13387                                             SS, TemplateKWLoc,
13388                                             /*FIXME: FirstQualifier*/ nullptr,
13389                                             NameInfo,
13390                                             /*TemplateArgs*/ nullptr,
13391                                             /*S*/nullptr);
13392 }
13393 
13394 template<typename Derived>
13395 StmtResult
13396 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13397   SourceLocation Loc = S->getBeginLoc();
13398   CapturedDecl *CD = S->getCapturedDecl();
13399   unsigned NumParams = CD->getNumParams();
13400   unsigned ContextParamPos = CD->getContextParamPosition();
13401   SmallVector<Sema::CapturedParamNameType, 4> Params;
13402   for (unsigned I = 0; I < NumParams; ++I) {
13403     if (I != ContextParamPos) {
13404       Params.push_back(
13405              std::make_pair(
13406                   CD->getParam(I)->getName(),
13407                   getDerived().TransformType(CD->getParam(I)->getType())));
13408     } else {
13409       Params.push_back(std::make_pair(StringRef(), QualType()));
13410     }
13411   }
13412   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13413                                      S->getCapturedRegionKind(), Params);
13414   StmtResult Body;
13415   {
13416     Sema::CompoundScopeRAII CompoundScope(getSema());
13417     Body = getDerived().TransformStmt(S->getCapturedStmt());
13418   }
13419 
13420   if (Body.isInvalid()) {
13421     getSema().ActOnCapturedRegionError();
13422     return StmtError();
13423   }
13424 
13425   return getSema().ActOnCapturedRegionEnd(Body.get());
13426 }
13427 
13428 } // end namespace clang
13429 
13430 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
13431