xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 05ab65497e06edd12683163480841aa9630b9d4c)
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/ExprConcepts.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/OpenMPClause.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/StmtOpenMP.h"
31 #include "clang/Sema/Designator.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Ownership.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaDiagnostic.h"
37 #include "clang/Sema/SemaInternal.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include <algorithm>
41 
42 using namespace llvm::omp;
43 
44 namespace clang {
45 using namespace sema;
46 
47 /// A semantic tree transformation that allows one to transform one
48 /// abstract syntax tree into another.
49 ///
50 /// A new tree transformation is defined by creating a new subclass \c X of
51 /// \c TreeTransform<X> and then overriding certain operations to provide
52 /// behavior specific to that transformation. For example, template
53 /// instantiation is implemented as a tree transformation where the
54 /// transformation of TemplateTypeParmType nodes involves substituting the
55 /// template arguments for their corresponding template parameters; a similar
56 /// transformation is performed for non-type template parameters and
57 /// template template parameters.
58 ///
59 /// This tree-transformation template uses static polymorphism to allow
60 /// subclasses to customize any of its operations. Thus, a subclass can
61 /// override any of the transformation or rebuild operators by providing an
62 /// operation with the same signature as the default implementation. The
63 /// overriding function should not be virtual.
64 ///
65 /// Semantic tree transformations are split into two stages, either of which
66 /// can be replaced by a subclass. The "transform" step transforms an AST node
67 /// or the parts of an AST node using the various transformation functions,
68 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
69 /// node of the appropriate kind from the pieces. The default transformation
70 /// routines recursively transform the operands to composite AST nodes (e.g.,
71 /// the pointee type of a PointerType node) and, if any of those operand nodes
72 /// were changed by the transformation, invokes the rebuild operation to create
73 /// a new AST node.
74 ///
75 /// Subclasses can customize the transformation at various levels. The
76 /// most coarse-grained transformations involve replacing TransformType(),
77 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
78 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
79 /// new implementations.
80 ///
81 /// For more fine-grained transformations, subclasses can replace any of the
82 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
83 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
84 /// replacing TransformTemplateTypeParmType() allows template instantiation
85 /// to substitute template arguments for their corresponding template
86 /// parameters. Additionally, subclasses can override the \c RebuildXXX
87 /// functions to control how AST nodes are rebuilt when their operands change.
88 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
89 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
90 /// be able to use more efficient rebuild steps.
91 ///
92 /// There are a handful of other functions that can be overridden, allowing one
93 /// to avoid traversing nodes that don't need any transformation
94 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
95 /// operands have not changed (\c AlwaysRebuild()), and customize the
96 /// default locations and entity names used for type-checking
97 /// (\c getBaseLocation(), \c getBaseEntity()).
98 template<typename Derived>
99 class TreeTransform {
100   /// Private RAII object that helps us forget and then re-remember
101   /// the template argument corresponding to a partially-substituted parameter
102   /// pack.
103   class ForgetPartiallySubstitutedPackRAII {
104     Derived &Self;
105     TemplateArgument Old;
106 
107   public:
108     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
109       Old = Self.ForgetPartiallySubstitutedPack();
110     }
111 
112     ~ForgetPartiallySubstitutedPackRAII() {
113       Self.RememberPartiallySubstitutedPack(Old);
114     }
115   };
116 
117 protected:
118   Sema &SemaRef;
119 
120   /// The set of local declarations that have been transformed, for
121   /// cases where we are forced to build new declarations within the transformer
122   /// rather than in the subclass (e.g., lambda closure types).
123   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
124 
125 public:
126   /// Initializes a new tree transformer.
127   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
128 
129   /// Retrieves a reference to the derived class.
130   Derived &getDerived() { return static_cast<Derived&>(*this); }
131 
132   /// Retrieves a reference to the derived class.
133   const Derived &getDerived() const {
134     return static_cast<const Derived&>(*this);
135   }
136 
137   static inline ExprResult Owned(Expr *E) { return E; }
138   static inline StmtResult Owned(Stmt *S) { return S; }
139 
140   /// Retrieves a reference to the semantic analysis object used for
141   /// this tree transform.
142   Sema &getSema() const { return SemaRef; }
143 
144   /// Whether the transformation should always rebuild AST nodes, even
145   /// if none of the children have changed.
146   ///
147   /// Subclasses may override this function to specify when the transformation
148   /// should rebuild all AST nodes.
149   ///
150   /// We must always rebuild all AST nodes when performing variadic template
151   /// pack expansion, in order to avoid violating the AST invariant that each
152   /// statement node appears at most once in its containing declaration.
153   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
154 
155   /// Whether the transformation is forming an expression or statement that
156   /// replaces the original. In this case, we'll reuse mangling numbers from
157   /// existing lambdas.
158   bool ReplacingOriginal() { return false; }
159 
160   /// Returns the location of the entity being transformed, if that
161   /// information was not available elsewhere in the AST.
162   ///
163   /// By default, returns no source-location information. Subclasses can
164   /// provide an alternative implementation that provides better location
165   /// information.
166   SourceLocation getBaseLocation() { return SourceLocation(); }
167 
168   /// Returns the name of the entity being transformed, if that
169   /// information was not available elsewhere in the AST.
170   ///
171   /// By default, returns an empty name. Subclasses can provide an alternative
172   /// implementation with a more precise name.
173   DeclarationName getBaseEntity() { return DeclarationName(); }
174 
175   /// Sets the "base" location and entity when that
176   /// information is known based on another transformation.
177   ///
178   /// By default, the source location and entity are ignored. Subclasses can
179   /// override this function to provide a customized implementation.
180   void setBase(SourceLocation Loc, DeclarationName Entity) { }
181 
182   /// RAII object that temporarily sets the base location and entity
183   /// used for reporting diagnostics in types.
184   class TemporaryBase {
185     TreeTransform &Self;
186     SourceLocation OldLocation;
187     DeclarationName OldEntity;
188 
189   public:
190     TemporaryBase(TreeTransform &Self, SourceLocation Location,
191                   DeclarationName Entity) : Self(Self) {
192       OldLocation = Self.getDerived().getBaseLocation();
193       OldEntity = Self.getDerived().getBaseEntity();
194 
195       if (Location.isValid())
196         Self.getDerived().setBase(Location, Entity);
197     }
198 
199     ~TemporaryBase() {
200       Self.getDerived().setBase(OldLocation, OldEntity);
201     }
202   };
203 
204   /// Determine whether the given type \p T has already been
205   /// transformed.
206   ///
207   /// Subclasses can provide an alternative implementation of this routine
208   /// to short-circuit evaluation when it is known that a given type will
209   /// not change. For example, template instantiation need not traverse
210   /// non-dependent types.
211   bool AlreadyTransformed(QualType T) {
212     return T.isNull();
213   }
214 
215   /// Transform a template parameter depth level.
216   ///
217   /// During a transformation that transforms template parameters, this maps
218   /// an old template parameter depth to a new depth.
219   unsigned TransformTemplateDepth(unsigned Depth) {
220     return Depth;
221   }
222 
223   /// Determine whether the given call argument should be dropped, e.g.,
224   /// because it is a default argument.
225   ///
226   /// Subclasses can provide an alternative implementation of this routine to
227   /// determine which kinds of call arguments get dropped. By default,
228   /// CXXDefaultArgument nodes are dropped (prior to transformation).
229   bool DropCallArgument(Expr *E) {
230     return E->isDefaultArgument();
231   }
232 
233   /// Determine whether we should expand a pack expansion with the
234   /// given set of parameter packs into separate arguments by repeatedly
235   /// transforming the pattern.
236   ///
237   /// By default, the transformer never tries to expand pack expansions.
238   /// Subclasses can override this routine to provide different behavior.
239   ///
240   /// \param EllipsisLoc The location of the ellipsis that identifies the
241   /// pack expansion.
242   ///
243   /// \param PatternRange The source range that covers the entire pattern of
244   /// the pack expansion.
245   ///
246   /// \param Unexpanded The set of unexpanded parameter packs within the
247   /// pattern.
248   ///
249   /// \param ShouldExpand Will be set to \c true if the transformer should
250   /// expand the corresponding pack expansions into separate arguments. When
251   /// set, \c NumExpansions must also be set.
252   ///
253   /// \param RetainExpansion Whether the caller should add an unexpanded
254   /// pack expansion after all of the expanded arguments. This is used
255   /// when extending explicitly-specified template argument packs per
256   /// C++0x [temp.arg.explicit]p9.
257   ///
258   /// \param NumExpansions The number of separate arguments that will be in
259   /// the expanded form of the corresponding pack expansion. This is both an
260   /// input and an output parameter, which can be set by the caller if the
261   /// number of expansions is known a priori (e.g., due to a prior substitution)
262   /// and will be set by the callee when the number of expansions is known.
263   /// The callee must set this value when \c ShouldExpand is \c true; it may
264   /// set this value in other cases.
265   ///
266   /// \returns true if an error occurred (e.g., because the parameter packs
267   /// are to be instantiated with arguments of different lengths), false
268   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
269   /// must be set.
270   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
271                                SourceRange PatternRange,
272                                ArrayRef<UnexpandedParameterPack> Unexpanded,
273                                bool &ShouldExpand,
274                                bool &RetainExpansion,
275                                Optional<unsigned> &NumExpansions) {
276     ShouldExpand = false;
277     return false;
278   }
279 
280   /// "Forget" about the partially-substituted pack template argument,
281   /// when performing an instantiation that must preserve the parameter pack
282   /// use.
283   ///
284   /// This routine is meant to be overridden by the template instantiator.
285   TemplateArgument ForgetPartiallySubstitutedPack() {
286     return TemplateArgument();
287   }
288 
289   /// "Remember" the partially-substituted pack template argument
290   /// after performing an instantiation that must preserve the parameter pack
291   /// use.
292   ///
293   /// This routine is meant to be overridden by the template instantiator.
294   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
295 
296   /// Note to the derived class when a function parameter pack is
297   /// being expanded.
298   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
299 
300   /// Transforms the given type into another type.
301   ///
302   /// By default, this routine transforms a type by creating a
303   /// TypeSourceInfo for it and delegating to the appropriate
304   /// function.  This is expensive, but we don't mind, because
305   /// this method is deprecated anyway;  all users should be
306   /// switched to storing TypeSourceInfos.
307   ///
308   /// \returns the transformed type.
309   QualType TransformType(QualType T);
310 
311   /// Transforms the given type-with-location into a new
312   /// type-with-location.
313   ///
314   /// By default, this routine transforms a type by delegating to the
315   /// appropriate TransformXXXType to build a new type.  Subclasses
316   /// may override this function (to take over all type
317   /// transformations) or some set of the TransformXXXType functions
318   /// to alter the transformation.
319   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
320 
321   /// Transform the given type-with-location into a new
322   /// type, collecting location information in the given builder
323   /// as necessary.
324   ///
325   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
326 
327   /// Transform a type that is permitted to produce a
328   /// DeducedTemplateSpecializationType.
329   ///
330   /// This is used in the (relatively rare) contexts where it is acceptable
331   /// for transformation to produce a class template type with deduced
332   /// template arguments.
333   /// @{
334   QualType TransformTypeWithDeducedTST(QualType T);
335   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
336   /// @}
337 
338   /// The reason why the value of a statement is not discarded, if any.
339   enum StmtDiscardKind {
340     SDK_Discarded,
341     SDK_NotDiscarded,
342     SDK_StmtExprResult,
343   };
344 
345   /// Transform the given statement.
346   ///
347   /// By default, this routine transforms a statement by delegating to the
348   /// appropriate TransformXXXStmt function to transform a specific kind of
349   /// statement or the TransformExpr() function to transform an expression.
350   /// Subclasses may override this function to transform statements using some
351   /// other mechanism.
352   ///
353   /// \returns the transformed statement.
354   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
355 
356   /// Transform the given statement.
357   ///
358   /// By default, this routine transforms a statement by delegating to the
359   /// appropriate TransformOMPXXXClause function to transform a specific kind
360   /// of clause. Subclasses may override this function to transform statements
361   /// using some other mechanism.
362   ///
363   /// \returns the transformed OpenMP clause.
364   OMPClause *TransformOMPClause(OMPClause *S);
365 
366   /// Transform the given attribute.
367   ///
368   /// By default, this routine transforms a statement by delegating to the
369   /// appropriate TransformXXXAttr function to transform a specific kind
370   /// of attribute. Subclasses may override this function to transform
371   /// attributed statements using some other mechanism.
372   ///
373   /// \returns the transformed attribute
374   const Attr *TransformAttr(const Attr *S);
375 
376 /// Transform the specified attribute.
377 ///
378 /// Subclasses should override the transformation of attributes with a pragma
379 /// spelling to transform expressions stored within the attribute.
380 ///
381 /// \returns the transformed attribute.
382 #define ATTR(X)
383 #define PRAGMA_SPELLING_ATTR(X)                                                \
384   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
385 #include "clang/Basic/AttrList.inc"
386 
387   /// Transform the given expression.
388   ///
389   /// By default, this routine transforms an expression by delegating to the
390   /// appropriate TransformXXXExpr function to build a new expression.
391   /// Subclasses may override this function to transform expressions using some
392   /// other mechanism.
393   ///
394   /// \returns the transformed expression.
395   ExprResult TransformExpr(Expr *E);
396 
397   /// Transform the given initializer.
398   ///
399   /// By default, this routine transforms an initializer by stripping off the
400   /// semantic nodes added by initialization, then passing the result to
401   /// TransformExpr or TransformExprs.
402   ///
403   /// \returns the transformed initializer.
404   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
405 
406   /// Transform the given list of expressions.
407   ///
408   /// This routine transforms a list of expressions by invoking
409   /// \c TransformExpr() for each subexpression. However, it also provides
410   /// support for variadic templates by expanding any pack expansions (if the
411   /// derived class permits such expansion) along the way. When pack expansions
412   /// are present, the number of outputs may not equal the number of inputs.
413   ///
414   /// \param Inputs The set of expressions to be transformed.
415   ///
416   /// \param NumInputs The number of expressions in \c Inputs.
417   ///
418   /// \param IsCall If \c true, then this transform is being performed on
419   /// function-call arguments, and any arguments that should be dropped, will
420   /// be.
421   ///
422   /// \param Outputs The transformed input expressions will be added to this
423   /// vector.
424   ///
425   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
426   /// due to transformation.
427   ///
428   /// \returns true if an error occurred, false otherwise.
429   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
430                       SmallVectorImpl<Expr *> &Outputs,
431                       bool *ArgChanged = nullptr);
432 
433   /// Transform the given declaration, which is referenced from a type
434   /// or expression.
435   ///
436   /// By default, acts as the identity function on declarations, unless the
437   /// transformer has had to transform the declaration itself. Subclasses
438   /// may override this function to provide alternate behavior.
439   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
440     llvm::DenseMap<Decl *, Decl *>::iterator Known
441       = TransformedLocalDecls.find(D);
442     if (Known != TransformedLocalDecls.end())
443       return Known->second;
444 
445     return D;
446   }
447 
448   /// Transform the specified condition.
449   ///
450   /// By default, this transforms the variable and expression and rebuilds
451   /// the condition.
452   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
453                                            Expr *Expr,
454                                            Sema::ConditionKind Kind);
455 
456   /// Transform the attributes associated with the given declaration and
457   /// place them on the new declaration.
458   ///
459   /// By default, this operation does nothing. Subclasses may override this
460   /// behavior to transform attributes.
461   void transformAttrs(Decl *Old, Decl *New) { }
462 
463   /// Note that a local declaration has been transformed by this
464   /// transformer.
465   ///
466   /// Local declarations are typically transformed via a call to
467   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
468   /// the transformer itself has to transform the declarations. This routine
469   /// can be overridden by a subclass that keeps track of such mappings.
470   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
471     assert(New.size() == 1 &&
472            "must override transformedLocalDecl if performing pack expansion");
473     TransformedLocalDecls[Old] = New.front();
474   }
475 
476   /// Transform the definition of the given declaration.
477   ///
478   /// By default, invokes TransformDecl() to transform the declaration.
479   /// Subclasses may override this function to provide alternate behavior.
480   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
481     return getDerived().TransformDecl(Loc, D);
482   }
483 
484   /// Transform the given declaration, which was the first part of a
485   /// nested-name-specifier in a member access expression.
486   ///
487   /// This specific declaration transformation only applies to the first
488   /// identifier in a nested-name-specifier of a member access expression, e.g.,
489   /// the \c T in \c x->T::member
490   ///
491   /// By default, invokes TransformDecl() to transform the declaration.
492   /// Subclasses may override this function to provide alternate behavior.
493   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
494     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
495   }
496 
497   /// Transform the set of declarations in an OverloadExpr.
498   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
499                                   LookupResult &R);
500 
501   /// Transform the given nested-name-specifier with source-location
502   /// information.
503   ///
504   /// By default, transforms all of the types and declarations within the
505   /// nested-name-specifier. Subclasses may override this function to provide
506   /// alternate behavior.
507   NestedNameSpecifierLoc
508   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
509                                   QualType ObjectType = QualType(),
510                                   NamedDecl *FirstQualifierInScope = nullptr);
511 
512   /// Transform the given declaration name.
513   ///
514   /// By default, transforms the types of conversion function, constructor,
515   /// and destructor names and then (if needed) rebuilds the declaration name.
516   /// Identifiers and selectors are returned unmodified. Sublcasses may
517   /// override this function to provide alternate behavior.
518   DeclarationNameInfo
519   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
520 
521   bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
522       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
523   concepts::TypeRequirement *
524   TransformTypeRequirement(concepts::TypeRequirement *Req);
525   concepts::ExprRequirement *
526   TransformExprRequirement(concepts::ExprRequirement *Req);
527   concepts::NestedRequirement *
528   TransformNestedRequirement(concepts::NestedRequirement *Req);
529 
530   /// Transform the given template name.
531   ///
532   /// \param SS The nested-name-specifier that qualifies the template
533   /// name. This nested-name-specifier must already have been transformed.
534   ///
535   /// \param Name The template name to transform.
536   ///
537   /// \param NameLoc The source location of the template name.
538   ///
539   /// \param ObjectType If we're translating a template name within a member
540   /// access expression, this is the type of the object whose member template
541   /// is being referenced.
542   ///
543   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
544   /// also refers to a name within the current (lexical) scope, this is the
545   /// declaration it refers to.
546   ///
547   /// By default, transforms the template name by transforming the declarations
548   /// and nested-name-specifiers that occur within the template name.
549   /// Subclasses may override this function to provide alternate behavior.
550   TemplateName
551   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
552                         SourceLocation NameLoc,
553                         QualType ObjectType = QualType(),
554                         NamedDecl *FirstQualifierInScope = nullptr,
555                         bool AllowInjectedClassName = false);
556 
557   /// Transform the given template argument.
558   ///
559   /// By default, this operation transforms the type, expression, or
560   /// declaration stored within the template argument and constructs a
561   /// new template argument from the transformed result. Subclasses may
562   /// override this function to provide alternate behavior.
563   ///
564   /// Returns true if there was an error.
565   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
566                                  TemplateArgumentLoc &Output,
567                                  bool Uneval = false);
568 
569   /// Transform the given set of template arguments.
570   ///
571   /// By default, this operation transforms all of the template arguments
572   /// in the input set using \c TransformTemplateArgument(), and appends
573   /// the transformed arguments to the output list.
574   ///
575   /// Note that this overload of \c TransformTemplateArguments() is merely
576   /// a convenience function. Subclasses that wish to override this behavior
577   /// should override the iterator-based member template version.
578   ///
579   /// \param Inputs The set of template arguments to be transformed.
580   ///
581   /// \param NumInputs The number of template arguments in \p Inputs.
582   ///
583   /// \param Outputs The set of transformed template arguments output by this
584   /// routine.
585   ///
586   /// Returns true if an error occurred.
587   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
588                                   unsigned NumInputs,
589                                   TemplateArgumentListInfo &Outputs,
590                                   bool Uneval = false) {
591     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
592                                       Uneval);
593   }
594 
595   /// Transform the given set of template arguments.
596   ///
597   /// By default, this operation transforms all of the template arguments
598   /// in the input set using \c TransformTemplateArgument(), and appends
599   /// the transformed arguments to the output list.
600   ///
601   /// \param First An iterator to the first template argument.
602   ///
603   /// \param Last An iterator one step past the last template argument.
604   ///
605   /// \param Outputs The set of transformed template arguments output by this
606   /// routine.
607   ///
608   /// Returns true if an error occurred.
609   template<typename InputIterator>
610   bool TransformTemplateArguments(InputIterator First,
611                                   InputIterator Last,
612                                   TemplateArgumentListInfo &Outputs,
613                                   bool Uneval = false);
614 
615   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
616   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
617                                  TemplateArgumentLoc &ArgLoc);
618 
619   /// Fakes up a TypeSourceInfo for a type.
620   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
621     return SemaRef.Context.getTrivialTypeSourceInfo(T,
622                        getDerived().getBaseLocation());
623   }
624 
625 #define ABSTRACT_TYPELOC(CLASS, PARENT)
626 #define TYPELOC(CLASS, PARENT)                                   \
627   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
628 #include "clang/AST/TypeLocNodes.def"
629 
630   template<typename Fn>
631   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
632                                       FunctionProtoTypeLoc TL,
633                                       CXXRecordDecl *ThisContext,
634                                       Qualifiers ThisTypeQuals,
635                                       Fn TransformExceptionSpec);
636 
637   bool TransformExceptionSpec(SourceLocation Loc,
638                               FunctionProtoType::ExceptionSpecInfo &ESI,
639                               SmallVectorImpl<QualType> &Exceptions,
640                               bool &Changed);
641 
642   StmtResult TransformSEHHandler(Stmt *Handler);
643 
644   QualType
645   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
646                                       TemplateSpecializationTypeLoc TL,
647                                       TemplateName Template);
648 
649   QualType
650   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
651                                       DependentTemplateSpecializationTypeLoc TL,
652                                                TemplateName Template,
653                                                CXXScopeSpec &SS);
654 
655   QualType TransformDependentTemplateSpecializationType(
656       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
657       NestedNameSpecifierLoc QualifierLoc);
658 
659   /// Transforms the parameters of a function type into the
660   /// given vectors.
661   ///
662   /// The result vectors should be kept in sync; null entries in the
663   /// variables vector are acceptable.
664   ///
665   /// Return true on error.
666   bool TransformFunctionTypeParams(
667       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
668       const QualType *ParamTypes,
669       const FunctionProtoType::ExtParameterInfo *ParamInfos,
670       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
671       Sema::ExtParameterInfoBuilder &PInfos);
672 
673   /// Transforms a single function-type parameter.  Return null
674   /// on error.
675   ///
676   /// \param indexAdjustment - A number to add to the parameter's
677   ///   scope index;  can be negative
678   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
679                                           int indexAdjustment,
680                                           Optional<unsigned> NumExpansions,
681                                           bool ExpectParameterPack);
682 
683   /// Transform the body of a lambda-expression.
684   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
685   /// Alternative implementation of TransformLambdaBody that skips transforming
686   /// the body.
687   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
688 
689   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
690 
691   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
692   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
693 
694   TemplateParameterList *TransformTemplateParameterList(
695         TemplateParameterList *TPL) {
696     return TPL;
697   }
698 
699   ExprResult TransformAddressOfOperand(Expr *E);
700 
701   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
702                                                 bool IsAddressOfOperand,
703                                                 TypeSourceInfo **RecoveryTSI);
704 
705   ExprResult TransformParenDependentScopeDeclRefExpr(
706       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
707       TypeSourceInfo **RecoveryTSI);
708 
709   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
710 
711 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
712 // amount of stack usage with clang.
713 #define STMT(Node, Parent)                        \
714   LLVM_ATTRIBUTE_NOINLINE \
715   StmtResult Transform##Node(Node *S);
716 #define VALUESTMT(Node, Parent)                   \
717   LLVM_ATTRIBUTE_NOINLINE \
718   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
719 #define EXPR(Node, Parent)                        \
720   LLVM_ATTRIBUTE_NOINLINE \
721   ExprResult Transform##Node(Node *E);
722 #define ABSTRACT_STMT(Stmt)
723 #include "clang/AST/StmtNodes.inc"
724 
725 #define OPENMP_CLAUSE(Name, Class)                        \
726   LLVM_ATTRIBUTE_NOINLINE \
727   OMPClause *Transform ## Class(Class *S);
728 #include "clang/Basic/OpenMPKinds.def"
729 
730   /// Build a new qualified type given its unqualified type and type location.
731   ///
732   /// By default, this routine adds type qualifiers only to types that can
733   /// have qualifiers, and silently suppresses those qualifiers that are not
734   /// permitted. Subclasses may override this routine to provide different
735   /// behavior.
736   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
737 
738   /// Build a new pointer type given its pointee type.
739   ///
740   /// By default, performs semantic analysis when building the pointer type.
741   /// Subclasses may override this routine to provide different behavior.
742   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
743 
744   /// Build a new block pointer type given its pointee type.
745   ///
746   /// By default, performs semantic analysis when building the block pointer
747   /// type. Subclasses may override this routine to provide different behavior.
748   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
749 
750   /// Build a new reference type given the type it references.
751   ///
752   /// By default, performs semantic analysis when building the
753   /// reference type. Subclasses may override this routine to provide
754   /// different behavior.
755   ///
756   /// \param LValue whether the type was written with an lvalue sigil
757   /// or an rvalue sigil.
758   QualType RebuildReferenceType(QualType ReferentType,
759                                 bool LValue,
760                                 SourceLocation Sigil);
761 
762   /// Build a new member pointer type given the pointee type and the
763   /// class type it refers into.
764   ///
765   /// By default, performs semantic analysis when building the member pointer
766   /// type. Subclasses may override this routine to provide different behavior.
767   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
768                                     SourceLocation Sigil);
769 
770   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
771                                     SourceLocation ProtocolLAngleLoc,
772                                     ArrayRef<ObjCProtocolDecl *> Protocols,
773                                     ArrayRef<SourceLocation> ProtocolLocs,
774                                     SourceLocation ProtocolRAngleLoc);
775 
776   /// Build an Objective-C object type.
777   ///
778   /// By default, performs semantic analysis when building the object type.
779   /// Subclasses may override this routine to provide different behavior.
780   QualType RebuildObjCObjectType(QualType BaseType,
781                                  SourceLocation Loc,
782                                  SourceLocation TypeArgsLAngleLoc,
783                                  ArrayRef<TypeSourceInfo *> TypeArgs,
784                                  SourceLocation TypeArgsRAngleLoc,
785                                  SourceLocation ProtocolLAngleLoc,
786                                  ArrayRef<ObjCProtocolDecl *> Protocols,
787                                  ArrayRef<SourceLocation> ProtocolLocs,
788                                  SourceLocation ProtocolRAngleLoc);
789 
790   /// Build a new Objective-C object pointer type given the pointee type.
791   ///
792   /// By default, directly builds the pointer type, with no additional semantic
793   /// analysis.
794   QualType RebuildObjCObjectPointerType(QualType PointeeType,
795                                         SourceLocation Star);
796 
797   /// Build a new array type given the element type, size
798   /// modifier, size of the array (if known), size expression, and index type
799   /// qualifiers.
800   ///
801   /// By default, performs semantic analysis when building the array type.
802   /// Subclasses may override this routine to provide different behavior.
803   /// Also by default, all of the other Rebuild*Array
804   QualType RebuildArrayType(QualType ElementType,
805                             ArrayType::ArraySizeModifier SizeMod,
806                             const llvm::APInt *Size,
807                             Expr *SizeExpr,
808                             unsigned IndexTypeQuals,
809                             SourceRange BracketsRange);
810 
811   /// Build a new constant array type given the element type, size
812   /// modifier, (known) size of the array, and index type qualifiers.
813   ///
814   /// By default, performs semantic analysis when building the array type.
815   /// Subclasses may override this routine to provide different behavior.
816   QualType RebuildConstantArrayType(QualType ElementType,
817                                     ArrayType::ArraySizeModifier SizeMod,
818                                     const llvm::APInt &Size,
819                                     Expr *SizeExpr,
820                                     unsigned IndexTypeQuals,
821                                     SourceRange BracketsRange);
822 
823   /// Build a new incomplete array type given the element type, size
824   /// modifier, and index type qualifiers.
825   ///
826   /// By default, performs semantic analysis when building the array type.
827   /// Subclasses may override this routine to provide different behavior.
828   QualType RebuildIncompleteArrayType(QualType ElementType,
829                                       ArrayType::ArraySizeModifier SizeMod,
830                                       unsigned IndexTypeQuals,
831                                       SourceRange BracketsRange);
832 
833   /// Build a new variable-length array type given the element type,
834   /// size modifier, size expression, and index type qualifiers.
835   ///
836   /// By default, performs semantic analysis when building the array type.
837   /// Subclasses may override this routine to provide different behavior.
838   QualType RebuildVariableArrayType(QualType ElementType,
839                                     ArrayType::ArraySizeModifier SizeMod,
840                                     Expr *SizeExpr,
841                                     unsigned IndexTypeQuals,
842                                     SourceRange BracketsRange);
843 
844   /// Build a new dependent-sized array type given the element type,
845   /// size modifier, size expression, and index type qualifiers.
846   ///
847   /// By default, performs semantic analysis when building the array type.
848   /// Subclasses may override this routine to provide different behavior.
849   QualType RebuildDependentSizedArrayType(QualType ElementType,
850                                           ArrayType::ArraySizeModifier SizeMod,
851                                           Expr *SizeExpr,
852                                           unsigned IndexTypeQuals,
853                                           SourceRange BracketsRange);
854 
855   /// Build a new vector type given the element type and
856   /// number of elements.
857   ///
858   /// By default, performs semantic analysis when building the vector type.
859   /// Subclasses may override this routine to provide different behavior.
860   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
861                              VectorType::VectorKind VecKind);
862 
863   /// Build a new potentially dependently-sized extended vector type
864   /// given the element type and number of elements.
865   ///
866   /// By default, performs semantic analysis when building the vector type.
867   /// Subclasses may override this routine to provide different behavior.
868   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
869                                            SourceLocation AttributeLoc,
870                                            VectorType::VectorKind);
871 
872   /// Build a new extended vector type given the element type and
873   /// number of elements.
874   ///
875   /// By default, performs semantic analysis when building the vector type.
876   /// Subclasses may override this routine to provide different behavior.
877   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
878                                 SourceLocation AttributeLoc);
879 
880   /// Build a new potentially dependently-sized extended vector type
881   /// given the element type and number of elements.
882   ///
883   /// By default, performs semantic analysis when building the vector type.
884   /// Subclasses may override this routine to provide different behavior.
885   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
886                                               Expr *SizeExpr,
887                                               SourceLocation AttributeLoc);
888 
889   /// Build a new DependentAddressSpaceType or return the pointee
890   /// type variable with the correct address space (retrieved from
891   /// AddrSpaceExpr) applied to it. The former will be returned in cases
892   /// where the address space remains dependent.
893   ///
894   /// By default, performs semantic analysis when building the type with address
895   /// space applied. Subclasses may override this routine to provide different
896   /// behavior.
897   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
898                                             Expr *AddrSpaceExpr,
899                                             SourceLocation AttributeLoc);
900 
901   /// Build a new function type.
902   ///
903   /// By default, performs semantic analysis when building the function type.
904   /// Subclasses may override this routine to provide different behavior.
905   QualType RebuildFunctionProtoType(QualType T,
906                                     MutableArrayRef<QualType> ParamTypes,
907                                     const FunctionProtoType::ExtProtoInfo &EPI);
908 
909   /// Build a new unprototyped function type.
910   QualType RebuildFunctionNoProtoType(QualType ResultType);
911 
912   /// Rebuild an unresolved typename type, given the decl that
913   /// the UnresolvedUsingTypenameDecl was transformed to.
914   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
915 
916   /// Build a new typedef type.
917   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
918     return SemaRef.Context.getTypeDeclType(Typedef);
919   }
920 
921   /// Build a new MacroDefined type.
922   QualType RebuildMacroQualifiedType(QualType T,
923                                      const IdentifierInfo *MacroII) {
924     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
925   }
926 
927   /// Build a new class/struct/union type.
928   QualType RebuildRecordType(RecordDecl *Record) {
929     return SemaRef.Context.getTypeDeclType(Record);
930   }
931 
932   /// Build a new Enum type.
933   QualType RebuildEnumType(EnumDecl *Enum) {
934     return SemaRef.Context.getTypeDeclType(Enum);
935   }
936 
937   /// Build a new typeof(expr) type.
938   ///
939   /// By default, performs semantic analysis when building the typeof type.
940   /// Subclasses may override this routine to provide different behavior.
941   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
942 
943   /// Build a new typeof(type) type.
944   ///
945   /// By default, builds a new TypeOfType with the given underlying type.
946   QualType RebuildTypeOfType(QualType Underlying);
947 
948   /// Build a new unary transform type.
949   QualType RebuildUnaryTransformType(QualType BaseType,
950                                      UnaryTransformType::UTTKind UKind,
951                                      SourceLocation Loc);
952 
953   /// Build a new C++11 decltype type.
954   ///
955   /// By default, performs semantic analysis when building the decltype type.
956   /// Subclasses may override this routine to provide different behavior.
957   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
958 
959   /// Build a new C++11 auto type.
960   ///
961   /// By default, builds a new AutoType with the given deduced type.
962   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
963                            ConceptDecl *TypeConstraintConcept,
964                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
965     // Note, IsDependent is always false here: we implicitly convert an 'auto'
966     // which has been deduced to a dependent type into an undeduced 'auto', so
967     // that we'll retry deduction after the transformation.
968     return SemaRef.Context.getAutoType(Deduced, Keyword,
969                                        /*IsDependent*/ false, /*IsPack=*/false,
970                                        TypeConstraintConcept,
971                                        TypeConstraintArgs);
972   }
973 
974   /// By default, builds a new DeducedTemplateSpecializationType with the given
975   /// deduced type.
976   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
977       QualType Deduced) {
978     return SemaRef.Context.getDeducedTemplateSpecializationType(
979         Template, Deduced, /*IsDependent*/ false);
980   }
981 
982   /// Build a new template specialization type.
983   ///
984   /// By default, performs semantic analysis when building the template
985   /// specialization type. Subclasses may override this routine to provide
986   /// different behavior.
987   QualType RebuildTemplateSpecializationType(TemplateName Template,
988                                              SourceLocation TemplateLoc,
989                                              TemplateArgumentListInfo &Args);
990 
991   /// Build a new parenthesized type.
992   ///
993   /// By default, builds a new ParenType type from the inner type.
994   /// Subclasses may override this routine to provide different behavior.
995   QualType RebuildParenType(QualType InnerType) {
996     return SemaRef.BuildParenType(InnerType);
997   }
998 
999   /// Build a new qualified name type.
1000   ///
1001   /// By default, builds a new ElaboratedType type from the keyword,
1002   /// the nested-name-specifier and the named type.
1003   /// Subclasses may override this routine to provide different behavior.
1004   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1005                                  ElaboratedTypeKeyword Keyword,
1006                                  NestedNameSpecifierLoc QualifierLoc,
1007                                  QualType Named) {
1008     return SemaRef.Context.getElaboratedType(Keyword,
1009                                          QualifierLoc.getNestedNameSpecifier(),
1010                                              Named);
1011   }
1012 
1013   /// Build a new typename type that refers to a template-id.
1014   ///
1015   /// By default, builds a new DependentNameType type from the
1016   /// nested-name-specifier and the given type. Subclasses may override
1017   /// this routine to provide different behavior.
1018   QualType RebuildDependentTemplateSpecializationType(
1019                                           ElaboratedTypeKeyword Keyword,
1020                                           NestedNameSpecifierLoc QualifierLoc,
1021                                           SourceLocation TemplateKWLoc,
1022                                           const IdentifierInfo *Name,
1023                                           SourceLocation NameLoc,
1024                                           TemplateArgumentListInfo &Args,
1025                                           bool AllowInjectedClassName) {
1026     // Rebuild the template name.
1027     // TODO: avoid TemplateName abstraction
1028     CXXScopeSpec SS;
1029     SS.Adopt(QualifierLoc);
1030     TemplateName InstName = getDerived().RebuildTemplateName(
1031         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1032         AllowInjectedClassName);
1033 
1034     if (InstName.isNull())
1035       return QualType();
1036 
1037     // If it's still dependent, make a dependent specialization.
1038     if (InstName.getAsDependentTemplateName())
1039       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1040                                           QualifierLoc.getNestedNameSpecifier(),
1041                                                                     Name,
1042                                                                     Args);
1043 
1044     // Otherwise, make an elaborated type wrapping a non-dependent
1045     // specialization.
1046     QualType T =
1047     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1048     if (T.isNull()) return QualType();
1049 
1050     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1051       return T;
1052 
1053     return SemaRef.Context.getElaboratedType(Keyword,
1054                                        QualifierLoc.getNestedNameSpecifier(),
1055                                              T);
1056   }
1057 
1058   /// Build a new typename type that refers to an identifier.
1059   ///
1060   /// By default, performs semantic analysis when building the typename type
1061   /// (or elaborated type). Subclasses may override this routine to provide
1062   /// different behavior.
1063   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1064                                     SourceLocation KeywordLoc,
1065                                     NestedNameSpecifierLoc QualifierLoc,
1066                                     const IdentifierInfo *Id,
1067                                     SourceLocation IdLoc,
1068                                     bool DeducedTSTContext) {
1069     CXXScopeSpec SS;
1070     SS.Adopt(QualifierLoc);
1071 
1072     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1073       // If the name is still dependent, just build a new dependent name type.
1074       if (!SemaRef.computeDeclContext(SS))
1075         return SemaRef.Context.getDependentNameType(Keyword,
1076                                           QualifierLoc.getNestedNameSpecifier(),
1077                                                     Id);
1078     }
1079 
1080     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1081       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1082                                        *Id, IdLoc, DeducedTSTContext);
1083     }
1084 
1085     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1086 
1087     // We had a dependent elaborated-type-specifier that has been transformed
1088     // into a non-dependent elaborated-type-specifier. Find the tag we're
1089     // referring to.
1090     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1091     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1092     if (!DC)
1093       return QualType();
1094 
1095     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1096       return QualType();
1097 
1098     TagDecl *Tag = nullptr;
1099     SemaRef.LookupQualifiedName(Result, DC);
1100     switch (Result.getResultKind()) {
1101       case LookupResult::NotFound:
1102       case LookupResult::NotFoundInCurrentInstantiation:
1103         break;
1104 
1105       case LookupResult::Found:
1106         Tag = Result.getAsSingle<TagDecl>();
1107         break;
1108 
1109       case LookupResult::FoundOverloaded:
1110       case LookupResult::FoundUnresolvedValue:
1111         llvm_unreachable("Tag lookup cannot find non-tags");
1112 
1113       case LookupResult::Ambiguous:
1114         // Let the LookupResult structure handle ambiguities.
1115         return QualType();
1116     }
1117 
1118     if (!Tag) {
1119       // Check where the name exists but isn't a tag type and use that to emit
1120       // better diagnostics.
1121       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1122       SemaRef.LookupQualifiedName(Result, DC);
1123       switch (Result.getResultKind()) {
1124         case LookupResult::Found:
1125         case LookupResult::FoundOverloaded:
1126         case LookupResult::FoundUnresolvedValue: {
1127           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1128           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1129           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1130                                                                << NTK << Kind;
1131           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1132           break;
1133         }
1134         default:
1135           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1136               << Kind << Id << DC << QualifierLoc.getSourceRange();
1137           break;
1138       }
1139       return QualType();
1140     }
1141 
1142     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1143                                               IdLoc, Id)) {
1144       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1145       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1146       return QualType();
1147     }
1148 
1149     // Build the elaborated-type-specifier type.
1150     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1151     return SemaRef.Context.getElaboratedType(Keyword,
1152                                          QualifierLoc.getNestedNameSpecifier(),
1153                                              T);
1154   }
1155 
1156   /// Build a new pack expansion type.
1157   ///
1158   /// By default, builds a new PackExpansionType type from the given pattern.
1159   /// Subclasses may override this routine to provide different behavior.
1160   QualType RebuildPackExpansionType(QualType Pattern,
1161                                     SourceRange PatternRange,
1162                                     SourceLocation EllipsisLoc,
1163                                     Optional<unsigned> NumExpansions) {
1164     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1165                                         NumExpansions);
1166   }
1167 
1168   /// Build a new atomic type given its value type.
1169   ///
1170   /// By default, performs semantic analysis when building the atomic type.
1171   /// Subclasses may override this routine to provide different behavior.
1172   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1173 
1174   /// Build a new pipe type given its value type.
1175   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1176                            bool isReadPipe);
1177 
1178   /// Build a new template name given a nested name specifier, a flag
1179   /// indicating whether the "template" keyword was provided, and the template
1180   /// that the template name refers to.
1181   ///
1182   /// By default, builds the new template name directly. Subclasses may override
1183   /// this routine to provide different behavior.
1184   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1185                                    bool TemplateKW,
1186                                    TemplateDecl *Template);
1187 
1188   /// Build a new template name given a nested name specifier and the
1189   /// name that is referred to as a template.
1190   ///
1191   /// By default, performs semantic analysis to determine whether the name can
1192   /// be resolved to a specific template, then builds the appropriate kind of
1193   /// template name. Subclasses may override this routine to provide different
1194   /// behavior.
1195   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1196                                    SourceLocation TemplateKWLoc,
1197                                    const IdentifierInfo &Name,
1198                                    SourceLocation NameLoc, QualType ObjectType,
1199                                    NamedDecl *FirstQualifierInScope,
1200                                    bool AllowInjectedClassName);
1201 
1202   /// Build a new template name given a nested name specifier and the
1203   /// overloaded operator name that is referred to as a template.
1204   ///
1205   /// By default, performs semantic analysis to determine whether the name can
1206   /// be resolved to a specific template, then builds the appropriate kind of
1207   /// template name. Subclasses may override this routine to provide different
1208   /// behavior.
1209   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1210                                    SourceLocation TemplateKWLoc,
1211                                    OverloadedOperatorKind Operator,
1212                                    SourceLocation NameLoc, QualType ObjectType,
1213                                    bool AllowInjectedClassName);
1214 
1215   /// Build a new template name given a template template parameter pack
1216   /// and the
1217   ///
1218   /// By default, performs semantic analysis to determine whether the name can
1219   /// be resolved to a specific template, then builds the appropriate kind of
1220   /// template name. Subclasses may override this routine to provide different
1221   /// behavior.
1222   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1223                                    const TemplateArgument &ArgPack) {
1224     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1225   }
1226 
1227   /// Build a new compound statement.
1228   ///
1229   /// By default, performs semantic analysis to build the new statement.
1230   /// Subclasses may override this routine to provide different behavior.
1231   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1232                                        MultiStmtArg Statements,
1233                                        SourceLocation RBraceLoc,
1234                                        bool IsStmtExpr) {
1235     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1236                                        IsStmtExpr);
1237   }
1238 
1239   /// Build a new case statement.
1240   ///
1241   /// By default, performs semantic analysis to build the new statement.
1242   /// Subclasses may override this routine to provide different behavior.
1243   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1244                                    Expr *LHS,
1245                                    SourceLocation EllipsisLoc,
1246                                    Expr *RHS,
1247                                    SourceLocation ColonLoc) {
1248     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1249                                    ColonLoc);
1250   }
1251 
1252   /// Attach the body to a new case statement.
1253   ///
1254   /// By default, performs semantic analysis to build the new statement.
1255   /// Subclasses may override this routine to provide different behavior.
1256   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1257     getSema().ActOnCaseStmtBody(S, Body);
1258     return S;
1259   }
1260 
1261   /// Build a new default statement.
1262   ///
1263   /// By default, performs semantic analysis to build the new statement.
1264   /// Subclasses may override this routine to provide different behavior.
1265   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1266                                       SourceLocation ColonLoc,
1267                                       Stmt *SubStmt) {
1268     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1269                                       /*CurScope=*/nullptr);
1270   }
1271 
1272   /// Build a new label statement.
1273   ///
1274   /// By default, performs semantic analysis to build the new statement.
1275   /// Subclasses may override this routine to provide different behavior.
1276   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1277                               SourceLocation ColonLoc, Stmt *SubStmt) {
1278     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1279   }
1280 
1281   /// Build a new label statement.
1282   ///
1283   /// By default, performs semantic analysis to build the new statement.
1284   /// Subclasses may override this routine to provide different behavior.
1285   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1286                                    ArrayRef<const Attr*> Attrs,
1287                                    Stmt *SubStmt) {
1288     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1289   }
1290 
1291   /// Build a new "if" statement.
1292   ///
1293   /// By default, performs semantic analysis to build the new statement.
1294   /// Subclasses may override this routine to provide different behavior.
1295   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1296                            Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1297                            SourceLocation ElseLoc, Stmt *Else) {
1298     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1299                                  ElseLoc, Else);
1300   }
1301 
1302   /// Start building a new switch statement.
1303   ///
1304   /// By default, performs semantic analysis to build the new statement.
1305   /// Subclasses may override this routine to provide different behavior.
1306   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1307                                     Sema::ConditionResult Cond) {
1308     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1309   }
1310 
1311   /// Attach the body to the switch statement.
1312   ///
1313   /// By default, performs semantic analysis to build the new statement.
1314   /// Subclasses may override this routine to provide different behavior.
1315   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1316                                    Stmt *Switch, Stmt *Body) {
1317     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1318   }
1319 
1320   /// Build a new while statement.
1321   ///
1322   /// By default, performs semantic analysis to build the new statement.
1323   /// Subclasses may override this routine to provide different behavior.
1324   StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1325                               Sema::ConditionResult Cond, Stmt *Body) {
1326     return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1327   }
1328 
1329   /// Build a new do-while statement.
1330   ///
1331   /// By default, performs semantic analysis to build the new statement.
1332   /// Subclasses may override this routine to provide different behavior.
1333   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1334                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1335                            Expr *Cond, SourceLocation RParenLoc) {
1336     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1337                                  Cond, RParenLoc);
1338   }
1339 
1340   /// Build a new for statement.
1341   ///
1342   /// By default, performs semantic analysis to build the new statement.
1343   /// Subclasses may override this routine to provide different behavior.
1344   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1345                             Stmt *Init, Sema::ConditionResult Cond,
1346                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1347                             Stmt *Body) {
1348     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1349                                   Inc, RParenLoc, Body);
1350   }
1351 
1352   /// Build a new goto statement.
1353   ///
1354   /// By default, performs semantic analysis to build the new statement.
1355   /// Subclasses may override this routine to provide different behavior.
1356   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1357                              LabelDecl *Label) {
1358     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1359   }
1360 
1361   /// Build a new indirect goto statement.
1362   ///
1363   /// By default, performs semantic analysis to build the new statement.
1364   /// Subclasses may override this routine to provide different behavior.
1365   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1366                                      SourceLocation StarLoc,
1367                                      Expr *Target) {
1368     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1369   }
1370 
1371   /// Build a new return 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 RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1376     return getSema().BuildReturnStmt(ReturnLoc, Result);
1377   }
1378 
1379   /// Build a new declaration statement.
1380   ///
1381   /// By default, performs semantic analysis to build the new statement.
1382   /// Subclasses may override this routine to provide different behavior.
1383   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1384                              SourceLocation StartLoc, SourceLocation EndLoc) {
1385     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1386     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1387   }
1388 
1389   /// Build a new inline asm statement.
1390   ///
1391   /// By default, performs semantic analysis to build the new statement.
1392   /// Subclasses may override this routine to provide different behavior.
1393   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1394                                bool IsVolatile, unsigned NumOutputs,
1395                                unsigned NumInputs, IdentifierInfo **Names,
1396                                MultiExprArg Constraints, MultiExprArg Exprs,
1397                                Expr *AsmString, MultiExprArg Clobbers,
1398                                unsigned NumLabels,
1399                                SourceLocation RParenLoc) {
1400     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1401                                      NumInputs, Names, Constraints, Exprs,
1402                                      AsmString, Clobbers, NumLabels, RParenLoc);
1403   }
1404 
1405   /// Build a new MS style inline asm statement.
1406   ///
1407   /// By default, performs semantic analysis to build the new statement.
1408   /// Subclasses may override this routine to provide different behavior.
1409   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1410                               ArrayRef<Token> AsmToks,
1411                               StringRef AsmString,
1412                               unsigned NumOutputs, unsigned NumInputs,
1413                               ArrayRef<StringRef> Constraints,
1414                               ArrayRef<StringRef> Clobbers,
1415                               ArrayRef<Expr*> Exprs,
1416                               SourceLocation EndLoc) {
1417     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1418                                     NumOutputs, NumInputs,
1419                                     Constraints, Clobbers, Exprs, EndLoc);
1420   }
1421 
1422   /// Build a new co_return statement.
1423   ///
1424   /// By default, performs semantic analysis to build the new statement.
1425   /// Subclasses may override this routine to provide different behavior.
1426   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1427                                  bool IsImplicit) {
1428     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1429   }
1430 
1431   /// Build a new co_await expression.
1432   ///
1433   /// By default, performs semantic analysis to build the new expression.
1434   /// Subclasses may override this routine to provide different behavior.
1435   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1436                                 bool IsImplicit) {
1437     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1438   }
1439 
1440   /// Build a new co_await expression.
1441   ///
1442   /// By default, performs semantic analysis to build the new expression.
1443   /// Subclasses may override this routine to provide different behavior.
1444   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1445                                          Expr *Result,
1446                                          UnresolvedLookupExpr *Lookup) {
1447     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1448   }
1449 
1450   /// Build a new co_yield expression.
1451   ///
1452   /// By default, performs semantic analysis to build the new expression.
1453   /// Subclasses may override this routine to provide different behavior.
1454   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1455     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1456   }
1457 
1458   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1459     return getSema().BuildCoroutineBodyStmt(Args);
1460   }
1461 
1462   /// Build a new Objective-C \@try statement.
1463   ///
1464   /// By default, performs semantic analysis to build the new statement.
1465   /// Subclasses may override this routine to provide different behavior.
1466   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1467                                         Stmt *TryBody,
1468                                         MultiStmtArg CatchStmts,
1469                                         Stmt *Finally) {
1470     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1471                                         Finally);
1472   }
1473 
1474   /// Rebuild an Objective-C exception declaration.
1475   ///
1476   /// By default, performs semantic analysis to build the new declaration.
1477   /// Subclasses may override this routine to provide different behavior.
1478   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1479                                     TypeSourceInfo *TInfo, QualType T) {
1480     return getSema().BuildObjCExceptionDecl(TInfo, T,
1481                                             ExceptionDecl->getInnerLocStart(),
1482                                             ExceptionDecl->getLocation(),
1483                                             ExceptionDecl->getIdentifier());
1484   }
1485 
1486   /// Build a new Objective-C \@catch statement.
1487   ///
1488   /// By default, performs semantic analysis to build the new statement.
1489   /// Subclasses may override this routine to provide different behavior.
1490   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1491                                           SourceLocation RParenLoc,
1492                                           VarDecl *Var,
1493                                           Stmt *Body) {
1494     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1495                                           Var, Body);
1496   }
1497 
1498   /// Build a new Objective-C \@finally statement.
1499   ///
1500   /// By default, performs semantic analysis to build the new statement.
1501   /// Subclasses may override this routine to provide different behavior.
1502   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1503                                             Stmt *Body) {
1504     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1505   }
1506 
1507   /// Build a new Objective-C \@throw statement.
1508   ///
1509   /// By default, performs semantic analysis to build the new statement.
1510   /// Subclasses may override this routine to provide different behavior.
1511   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1512                                           Expr *Operand) {
1513     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1514   }
1515 
1516   /// Build a new OpenMP executable directive.
1517   ///
1518   /// By default, performs semantic analysis to build the new statement.
1519   /// Subclasses may override this routine to provide different behavior.
1520   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1521                                            DeclarationNameInfo DirName,
1522                                            OpenMPDirectiveKind CancelRegion,
1523                                            ArrayRef<OMPClause *> Clauses,
1524                                            Stmt *AStmt, SourceLocation StartLoc,
1525                                            SourceLocation EndLoc) {
1526     return getSema().ActOnOpenMPExecutableDirective(
1527         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1528   }
1529 
1530   /// Build a new OpenMP 'if' clause.
1531   ///
1532   /// By default, performs semantic analysis to build the new OpenMP clause.
1533   /// Subclasses may override this routine to provide different behavior.
1534   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1535                                 Expr *Condition, SourceLocation StartLoc,
1536                                 SourceLocation LParenLoc,
1537                                 SourceLocation NameModifierLoc,
1538                                 SourceLocation ColonLoc,
1539                                 SourceLocation EndLoc) {
1540     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1541                                          LParenLoc, NameModifierLoc, ColonLoc,
1542                                          EndLoc);
1543   }
1544 
1545   /// Build a new OpenMP 'final' clause.
1546   ///
1547   /// By default, performs semantic analysis to build the new OpenMP clause.
1548   /// Subclasses may override this routine to provide different behavior.
1549   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1550                                    SourceLocation LParenLoc,
1551                                    SourceLocation EndLoc) {
1552     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1553                                             EndLoc);
1554   }
1555 
1556   /// Build a new OpenMP 'num_threads' clause.
1557   ///
1558   /// By default, performs semantic analysis to build the new OpenMP clause.
1559   /// Subclasses may override this routine to provide different behavior.
1560   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1561                                         SourceLocation StartLoc,
1562                                         SourceLocation LParenLoc,
1563                                         SourceLocation EndLoc) {
1564     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1565                                                  LParenLoc, EndLoc);
1566   }
1567 
1568   /// Build a new OpenMP 'safelen' clause.
1569   ///
1570   /// By default, performs semantic analysis to build the new OpenMP clause.
1571   /// Subclasses may override this routine to provide different behavior.
1572   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1573                                      SourceLocation LParenLoc,
1574                                      SourceLocation EndLoc) {
1575     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1576   }
1577 
1578   /// Build a new OpenMP 'simdlen' clause.
1579   ///
1580   /// By default, performs semantic analysis to build the new OpenMP clause.
1581   /// Subclasses may override this routine to provide different behavior.
1582   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1583                                      SourceLocation LParenLoc,
1584                                      SourceLocation EndLoc) {
1585     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1586   }
1587 
1588   /// Build a new OpenMP 'allocator' clause.
1589   ///
1590   /// By default, performs semantic analysis to build the new OpenMP clause.
1591   /// Subclasses may override this routine to provide different behavior.
1592   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1593                                        SourceLocation LParenLoc,
1594                                        SourceLocation EndLoc) {
1595     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1596   }
1597 
1598   /// Build a new OpenMP 'collapse' clause.
1599   ///
1600   /// By default, performs semantic analysis to build the new OpenMP clause.
1601   /// Subclasses may override this routine to provide different behavior.
1602   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1603                                       SourceLocation LParenLoc,
1604                                       SourceLocation EndLoc) {
1605     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1606                                                EndLoc);
1607   }
1608 
1609   /// Build a new OpenMP 'default' clause.
1610   ///
1611   /// By default, performs semantic analysis to build the new OpenMP clause.
1612   /// Subclasses may override this routine to provide different behavior.
1613   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1614                                      SourceLocation KindKwLoc,
1615                                      SourceLocation StartLoc,
1616                                      SourceLocation LParenLoc,
1617                                      SourceLocation EndLoc) {
1618     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1619                                               StartLoc, LParenLoc, EndLoc);
1620   }
1621 
1622   /// Build a new OpenMP 'proc_bind' clause.
1623   ///
1624   /// By default, performs semantic analysis to build the new OpenMP clause.
1625   /// Subclasses may override this routine to provide different behavior.
1626   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1627                                       SourceLocation KindKwLoc,
1628                                       SourceLocation StartLoc,
1629                                       SourceLocation LParenLoc,
1630                                       SourceLocation EndLoc) {
1631     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1632                                                StartLoc, LParenLoc, EndLoc);
1633   }
1634 
1635   /// Build a new OpenMP 'schedule' clause.
1636   ///
1637   /// By default, performs semantic analysis to build the new OpenMP clause.
1638   /// Subclasses may override this routine to provide different behavior.
1639   OMPClause *RebuildOMPScheduleClause(
1640       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1641       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1642       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1643       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1644     return getSema().ActOnOpenMPScheduleClause(
1645         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1646         CommaLoc, EndLoc);
1647   }
1648 
1649   /// Build a new OpenMP 'ordered' clause.
1650   ///
1651   /// By default, performs semantic analysis to build the new OpenMP clause.
1652   /// Subclasses may override this routine to provide different behavior.
1653   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1654                                      SourceLocation EndLoc,
1655                                      SourceLocation LParenLoc, Expr *Num) {
1656     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1657   }
1658 
1659   /// Build a new OpenMP 'private' clause.
1660   ///
1661   /// By default, performs semantic analysis to build the new OpenMP clause.
1662   /// Subclasses may override this routine to provide different behavior.
1663   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1664                                      SourceLocation StartLoc,
1665                                      SourceLocation LParenLoc,
1666                                      SourceLocation EndLoc) {
1667     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1668                                               EndLoc);
1669   }
1670 
1671   /// Build a new OpenMP 'firstprivate' clause.
1672   ///
1673   /// By default, performs semantic analysis to build the new OpenMP clause.
1674   /// Subclasses may override this routine to provide different behavior.
1675   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1676                                           SourceLocation StartLoc,
1677                                           SourceLocation LParenLoc,
1678                                           SourceLocation EndLoc) {
1679     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1680                                                    EndLoc);
1681   }
1682 
1683   /// Build a new OpenMP 'lastprivate' clause.
1684   ///
1685   /// By default, performs semantic analysis to build the new OpenMP clause.
1686   /// Subclasses may override this routine to provide different behavior.
1687   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1688                                          OpenMPLastprivateModifier LPKind,
1689                                          SourceLocation LPKindLoc,
1690                                          SourceLocation ColonLoc,
1691                                          SourceLocation StartLoc,
1692                                          SourceLocation LParenLoc,
1693                                          SourceLocation EndLoc) {
1694     return getSema().ActOnOpenMPLastprivateClause(
1695         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1696   }
1697 
1698   /// Build a new OpenMP 'shared' clause.
1699   ///
1700   /// By default, performs semantic analysis to build the new OpenMP clause.
1701   /// Subclasses may override this routine to provide different behavior.
1702   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1703                                     SourceLocation StartLoc,
1704                                     SourceLocation LParenLoc,
1705                                     SourceLocation EndLoc) {
1706     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1707                                              EndLoc);
1708   }
1709 
1710   /// Build a new OpenMP 'reduction' clause.
1711   ///
1712   /// By default, performs semantic analysis to build the new statement.
1713   /// Subclasses may override this routine to provide different behavior.
1714   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1715                                        SourceLocation StartLoc,
1716                                        SourceLocation LParenLoc,
1717                                        SourceLocation ColonLoc,
1718                                        SourceLocation EndLoc,
1719                                        CXXScopeSpec &ReductionIdScopeSpec,
1720                                        const DeclarationNameInfo &ReductionId,
1721                                        ArrayRef<Expr *> UnresolvedReductions) {
1722     return getSema().ActOnOpenMPReductionClause(
1723         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1724         ReductionId, UnresolvedReductions);
1725   }
1726 
1727   /// Build a new OpenMP 'task_reduction' clause.
1728   ///
1729   /// By default, performs semantic analysis to build the new statement.
1730   /// Subclasses may override this routine to provide different behavior.
1731   OMPClause *RebuildOMPTaskReductionClause(
1732       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1733       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1734       CXXScopeSpec &ReductionIdScopeSpec,
1735       const DeclarationNameInfo &ReductionId,
1736       ArrayRef<Expr *> UnresolvedReductions) {
1737     return getSema().ActOnOpenMPTaskReductionClause(
1738         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1739         ReductionId, UnresolvedReductions);
1740   }
1741 
1742   /// Build a new OpenMP 'in_reduction' clause.
1743   ///
1744   /// By default, performs semantic analysis to build the new statement.
1745   /// Subclasses may override this routine to provide different behavior.
1746   OMPClause *
1747   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1748                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1749                               SourceLocation EndLoc,
1750                               CXXScopeSpec &ReductionIdScopeSpec,
1751                               const DeclarationNameInfo &ReductionId,
1752                               ArrayRef<Expr *> UnresolvedReductions) {
1753     return getSema().ActOnOpenMPInReductionClause(
1754         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1755         ReductionId, UnresolvedReductions);
1756   }
1757 
1758   /// Build a new OpenMP 'linear' clause.
1759   ///
1760   /// By default, performs semantic analysis to build the new OpenMP clause.
1761   /// Subclasses may override this routine to provide different behavior.
1762   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1763                                     SourceLocation StartLoc,
1764                                     SourceLocation LParenLoc,
1765                                     OpenMPLinearClauseKind Modifier,
1766                                     SourceLocation ModifierLoc,
1767                                     SourceLocation ColonLoc,
1768                                     SourceLocation EndLoc) {
1769     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1770                                              Modifier, ModifierLoc, ColonLoc,
1771                                              EndLoc);
1772   }
1773 
1774   /// Build a new OpenMP 'aligned' clause.
1775   ///
1776   /// By default, performs semantic analysis to build the new OpenMP clause.
1777   /// Subclasses may override this routine to provide different behavior.
1778   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1779                                      SourceLocation StartLoc,
1780                                      SourceLocation LParenLoc,
1781                                      SourceLocation ColonLoc,
1782                                      SourceLocation EndLoc) {
1783     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1784                                               LParenLoc, ColonLoc, EndLoc);
1785   }
1786 
1787   /// Build a new OpenMP 'copyin' clause.
1788   ///
1789   /// By default, performs semantic analysis to build the new OpenMP clause.
1790   /// Subclasses may override this routine to provide different behavior.
1791   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1792                                     SourceLocation StartLoc,
1793                                     SourceLocation LParenLoc,
1794                                     SourceLocation EndLoc) {
1795     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1796                                              EndLoc);
1797   }
1798 
1799   /// Build a new OpenMP 'copyprivate' clause.
1800   ///
1801   /// By default, performs semantic analysis to build the new OpenMP clause.
1802   /// Subclasses may override this routine to provide different behavior.
1803   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1804                                          SourceLocation StartLoc,
1805                                          SourceLocation LParenLoc,
1806                                          SourceLocation EndLoc) {
1807     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1808                                                   EndLoc);
1809   }
1810 
1811   /// Build a new OpenMP 'flush' pseudo clause.
1812   ///
1813   /// By default, performs semantic analysis to build the new OpenMP clause.
1814   /// Subclasses may override this routine to provide different behavior.
1815   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1816                                    SourceLocation StartLoc,
1817                                    SourceLocation LParenLoc,
1818                                    SourceLocation EndLoc) {
1819     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1820                                             EndLoc);
1821   }
1822 
1823   /// Build a new OpenMP 'depend' pseudo clause.
1824   ///
1825   /// By default, performs semantic analysis to build the new OpenMP clause.
1826   /// Subclasses may override this routine to provide different behavior.
1827   OMPClause *
1828   RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1829                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1830                          SourceLocation StartLoc, SourceLocation LParenLoc,
1831                          SourceLocation EndLoc) {
1832     return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1833                                              StartLoc, LParenLoc, EndLoc);
1834   }
1835 
1836   /// Build a new OpenMP 'device' clause.
1837   ///
1838   /// By default, performs semantic analysis to build the new statement.
1839   /// Subclasses may override this routine to provide different behavior.
1840   OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1841                                     SourceLocation LParenLoc,
1842                                     SourceLocation EndLoc) {
1843     return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1844                                              EndLoc);
1845   }
1846 
1847   /// Build a new OpenMP 'map' clause.
1848   ///
1849   /// By default, performs semantic analysis to build the new OpenMP clause.
1850   /// Subclasses may override this routine to provide different behavior.
1851   OMPClause *RebuildOMPMapClause(
1852       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1853       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1854       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1855       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1856       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1857       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1858     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1859                                           MapperIdScopeSpec, MapperId, MapType,
1860                                           IsMapTypeImplicit, MapLoc, ColonLoc,
1861                                           VarList, Locs, UnresolvedMappers);
1862   }
1863 
1864   /// Build a new OpenMP 'allocate' clause.
1865   ///
1866   /// By default, performs semantic analysis to build the new OpenMP clause.
1867   /// Subclasses may override this routine to provide different behavior.
1868   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1869                                       SourceLocation StartLoc,
1870                                       SourceLocation LParenLoc,
1871                                       SourceLocation ColonLoc,
1872                                       SourceLocation EndLoc) {
1873     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1874                                                LParenLoc, ColonLoc, EndLoc);
1875   }
1876 
1877   /// Build a new OpenMP 'num_teams' 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 *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1882                                       SourceLocation LParenLoc,
1883                                       SourceLocation EndLoc) {
1884     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1885                                                EndLoc);
1886   }
1887 
1888   /// Build a new OpenMP 'thread_limit' clause.
1889   ///
1890   /// By default, performs semantic analysis to build the new statement.
1891   /// Subclasses may override this routine to provide different behavior.
1892   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1893                                          SourceLocation StartLoc,
1894                                          SourceLocation LParenLoc,
1895                                          SourceLocation EndLoc) {
1896     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1897                                                   LParenLoc, EndLoc);
1898   }
1899 
1900   /// Build a new OpenMP 'priority' 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 *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1905                                       SourceLocation LParenLoc,
1906                                       SourceLocation EndLoc) {
1907     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1908                                                EndLoc);
1909   }
1910 
1911   /// Build a new OpenMP 'grainsize' 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 *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1916                                        SourceLocation LParenLoc,
1917                                        SourceLocation EndLoc) {
1918     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1919                                                 EndLoc);
1920   }
1921 
1922   /// Build a new OpenMP 'num_tasks' 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 *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1927                                       SourceLocation LParenLoc,
1928                                       SourceLocation EndLoc) {
1929     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1930                                                EndLoc);
1931   }
1932 
1933   /// Build a new OpenMP 'hint' clause.
1934   ///
1935   /// By default, performs semantic analysis to build the new statement.
1936   /// Subclasses may override this routine to provide different behavior.
1937   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1938                                   SourceLocation LParenLoc,
1939                                   SourceLocation EndLoc) {
1940     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1941   }
1942 
1943   /// Build a new OpenMP 'dist_schedule' clause.
1944   ///
1945   /// By default, performs semantic analysis to build the new OpenMP clause.
1946   /// Subclasses may override this routine to provide different behavior.
1947   OMPClause *
1948   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1949                                Expr *ChunkSize, SourceLocation StartLoc,
1950                                SourceLocation LParenLoc, SourceLocation KindLoc,
1951                                SourceLocation CommaLoc, SourceLocation EndLoc) {
1952     return getSema().ActOnOpenMPDistScheduleClause(
1953         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1954   }
1955 
1956   /// Build a new OpenMP 'to' clause.
1957   ///
1958   /// By default, performs semantic analysis to build the new statement.
1959   /// Subclasses may override this routine to provide different behavior.
1960   OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1961                                 CXXScopeSpec &MapperIdScopeSpec,
1962                                 DeclarationNameInfo &MapperId,
1963                                 const OMPVarListLocTy &Locs,
1964                                 ArrayRef<Expr *> UnresolvedMappers) {
1965     return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1966                                          Locs, UnresolvedMappers);
1967   }
1968 
1969   /// Build a new OpenMP 'from' clause.
1970   ///
1971   /// By default, performs semantic analysis to build the new statement.
1972   /// Subclasses may override this routine to provide different behavior.
1973   OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1974                                   CXXScopeSpec &MapperIdScopeSpec,
1975                                   DeclarationNameInfo &MapperId,
1976                                   const OMPVarListLocTy &Locs,
1977                                   ArrayRef<Expr *> UnresolvedMappers) {
1978     return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1979                                            Locs, UnresolvedMappers);
1980   }
1981 
1982   /// Build a new OpenMP 'use_device_ptr' clause.
1983   ///
1984   /// By default, performs semantic analysis to build the new OpenMP clause.
1985   /// Subclasses may override this routine to provide different behavior.
1986   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1987                                           const OMPVarListLocTy &Locs) {
1988     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1989   }
1990 
1991   /// Build a new OpenMP 'is_device_ptr' clause.
1992   ///
1993   /// By default, performs semantic analysis to build the new OpenMP clause.
1994   /// Subclasses may override this routine to provide different behavior.
1995   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1996                                          const OMPVarListLocTy &Locs) {
1997     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1998   }
1999 
2000   /// Build a new OpenMP 'defaultmap' clause.
2001   ///
2002   /// By default, performs semantic analysis to build the new OpenMP clause.
2003   /// Subclasses may override this routine to provide different behavior.
2004   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2005                                         OpenMPDefaultmapClauseKind Kind,
2006                                         SourceLocation StartLoc,
2007                                         SourceLocation LParenLoc,
2008                                         SourceLocation MLoc,
2009                                         SourceLocation KindLoc,
2010                                         SourceLocation EndLoc) {
2011     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2012                                                  MLoc, KindLoc, EndLoc);
2013   }
2014 
2015   /// Build a new OpenMP 'nontemporal' clause.
2016   ///
2017   /// By default, performs semantic analysis to build the new OpenMP clause.
2018   /// Subclasses may override this routine to provide different behavior.
2019   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2020                                          SourceLocation StartLoc,
2021                                          SourceLocation LParenLoc,
2022                                          SourceLocation EndLoc) {
2023     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2024                                                   EndLoc);
2025   }
2026 
2027   /// Rebuild the operand to an Objective-C \@synchronized statement.
2028   ///
2029   /// By default, performs semantic analysis to build the new statement.
2030   /// Subclasses may override this routine to provide different behavior.
2031   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2032                                               Expr *object) {
2033     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2034   }
2035 
2036   /// Build a new Objective-C \@synchronized statement.
2037   ///
2038   /// By default, performs semantic analysis to build the new statement.
2039   /// Subclasses may override this routine to provide different behavior.
2040   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2041                                            Expr *Object, Stmt *Body) {
2042     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2043   }
2044 
2045   /// Build a new Objective-C \@autoreleasepool statement.
2046   ///
2047   /// By default, performs semantic analysis to build the new statement.
2048   /// Subclasses may override this routine to provide different behavior.
2049   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2050                                             Stmt *Body) {
2051     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2052   }
2053 
2054   /// Build a new Objective-C fast enumeration statement.
2055   ///
2056   /// By default, performs semantic analysis to build the new statement.
2057   /// Subclasses may override this routine to provide different behavior.
2058   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2059                                           Stmt *Element,
2060                                           Expr *Collection,
2061                                           SourceLocation RParenLoc,
2062                                           Stmt *Body) {
2063     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2064                                                 Element,
2065                                                 Collection,
2066                                                 RParenLoc);
2067     if (ForEachStmt.isInvalid())
2068       return StmtError();
2069 
2070     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2071   }
2072 
2073   /// Build a new C++ exception declaration.
2074   ///
2075   /// By default, performs semantic analysis to build the new decaration.
2076   /// Subclasses may override this routine to provide different behavior.
2077   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2078                                 TypeSourceInfo *Declarator,
2079                                 SourceLocation StartLoc,
2080                                 SourceLocation IdLoc,
2081                                 IdentifierInfo *Id) {
2082     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2083                                                        StartLoc, IdLoc, Id);
2084     if (Var)
2085       getSema().CurContext->addDecl(Var);
2086     return Var;
2087   }
2088 
2089   /// Build a new C++ catch statement.
2090   ///
2091   /// By default, performs semantic analysis to build the new statement.
2092   /// Subclasses may override this routine to provide different behavior.
2093   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2094                                  VarDecl *ExceptionDecl,
2095                                  Stmt *Handler) {
2096     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2097                                                       Handler));
2098   }
2099 
2100   /// Build a new C++ try statement.
2101   ///
2102   /// By default, performs semantic analysis to build the new statement.
2103   /// Subclasses may override this routine to provide different behavior.
2104   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2105                                ArrayRef<Stmt *> Handlers) {
2106     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2107   }
2108 
2109   /// Build a new C++0x range-based for statement.
2110   ///
2111   /// By default, performs semantic analysis to build the new statement.
2112   /// Subclasses may override this routine to provide different behavior.
2113   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2114                                     SourceLocation CoawaitLoc, Stmt *Init,
2115                                     SourceLocation ColonLoc, Stmt *Range,
2116                                     Stmt *Begin, Stmt *End, Expr *Cond,
2117                                     Expr *Inc, Stmt *LoopVar,
2118                                     SourceLocation RParenLoc) {
2119     // If we've just learned that the range is actually an Objective-C
2120     // collection, treat this as an Objective-C fast enumeration loop.
2121     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2122       if (RangeStmt->isSingleDecl()) {
2123         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2124           if (RangeVar->isInvalidDecl())
2125             return StmtError();
2126 
2127           Expr *RangeExpr = RangeVar->getInit();
2128           if (!RangeExpr->isTypeDependent() &&
2129               RangeExpr->getType()->isObjCObjectPointerType()) {
2130             // FIXME: Support init-statements in Objective-C++20 ranged for
2131             // statement.
2132             if (Init) {
2133               return SemaRef.Diag(Init->getBeginLoc(),
2134                                   diag::err_objc_for_range_init_stmt)
2135                          << Init->getSourceRange();
2136             }
2137             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2138                                                         RangeExpr, RParenLoc);
2139           }
2140         }
2141       }
2142     }
2143 
2144     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2145                                           Range, Begin, End, Cond, Inc, LoopVar,
2146                                           RParenLoc, Sema::BFRK_Rebuild);
2147   }
2148 
2149   /// Build a new C++0x range-based for statement.
2150   ///
2151   /// By default, performs semantic analysis to build the new statement.
2152   /// Subclasses may override this routine to provide different behavior.
2153   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2154                                           bool IsIfExists,
2155                                           NestedNameSpecifierLoc QualifierLoc,
2156                                           DeclarationNameInfo NameInfo,
2157                                           Stmt *Nested) {
2158     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2159                                                 QualifierLoc, NameInfo, Nested);
2160   }
2161 
2162   /// Attach body to a C++0x range-based for statement.
2163   ///
2164   /// By default, performs semantic analysis to finish the new statement.
2165   /// Subclasses may override this routine to provide different behavior.
2166   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2167     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2168   }
2169 
2170   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2171                                Stmt *TryBlock, Stmt *Handler) {
2172     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2173   }
2174 
2175   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2176                                   Stmt *Block) {
2177     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2178   }
2179 
2180   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2181     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2182   }
2183 
2184   /// Build a new predefined expression.
2185   ///
2186   /// By default, performs semantic analysis to build the new expression.
2187   /// Subclasses may override this routine to provide different behavior.
2188   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2189                                    PredefinedExpr::IdentKind IK) {
2190     return getSema().BuildPredefinedExpr(Loc, IK);
2191   }
2192 
2193   /// Build a new expression that references a declaration.
2194   ///
2195   /// By default, performs semantic analysis to build the new expression.
2196   /// Subclasses may override this routine to provide different behavior.
2197   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2198                                         LookupResult &R,
2199                                         bool RequiresADL) {
2200     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2201   }
2202 
2203 
2204   /// Build a new expression that references a declaration.
2205   ///
2206   /// By default, performs semantic analysis to build the new expression.
2207   /// Subclasses may override this routine to provide different behavior.
2208   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2209                                 ValueDecl *VD,
2210                                 const DeclarationNameInfo &NameInfo,
2211                                 NamedDecl *Found,
2212                                 TemplateArgumentListInfo *TemplateArgs) {
2213     CXXScopeSpec SS;
2214     SS.Adopt(QualifierLoc);
2215     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2216                                               TemplateArgs);
2217   }
2218 
2219   /// Build a new expression in parentheses.
2220   ///
2221   /// By default, performs semantic analysis to build the new expression.
2222   /// Subclasses may override this routine to provide different behavior.
2223   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2224                                     SourceLocation RParen) {
2225     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2226   }
2227 
2228   /// Build a new pseudo-destructor 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 RebuildCXXPseudoDestructorExpr(Expr *Base,
2233                                             SourceLocation OperatorLoc,
2234                                             bool isArrow,
2235                                             CXXScopeSpec &SS,
2236                                             TypeSourceInfo *ScopeType,
2237                                             SourceLocation CCLoc,
2238                                             SourceLocation TildeLoc,
2239                                         PseudoDestructorTypeStorage Destroyed);
2240 
2241   /// Build a new unary operator expression.
2242   ///
2243   /// By default, performs semantic analysis to build the new expression.
2244   /// Subclasses may override this routine to provide different behavior.
2245   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2246                                         UnaryOperatorKind Opc,
2247                                         Expr *SubExpr) {
2248     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2249   }
2250 
2251   /// Build a new builtin offsetof expression.
2252   ///
2253   /// By default, performs semantic analysis to build the new expression.
2254   /// Subclasses may override this routine to provide different behavior.
2255   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2256                                  TypeSourceInfo *Type,
2257                                  ArrayRef<Sema::OffsetOfComponent> Components,
2258                                  SourceLocation RParenLoc) {
2259     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2260                                           RParenLoc);
2261   }
2262 
2263   /// Build a new sizeof, alignof or vec_step expression with a
2264   /// type argument.
2265   ///
2266   /// By default, performs semantic analysis to build the new expression.
2267   /// Subclasses may override this routine to provide different behavior.
2268   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2269                                          SourceLocation OpLoc,
2270                                          UnaryExprOrTypeTrait ExprKind,
2271                                          SourceRange R) {
2272     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2273   }
2274 
2275   /// Build a new sizeof, alignof or vec step expression with an
2276   /// expression argument.
2277   ///
2278   /// By default, performs semantic analysis to build the new expression.
2279   /// Subclasses may override this routine to provide different behavior.
2280   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2281                                          UnaryExprOrTypeTrait ExprKind,
2282                                          SourceRange R) {
2283     ExprResult Result
2284       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2285     if (Result.isInvalid())
2286       return ExprError();
2287 
2288     return Result;
2289   }
2290 
2291   /// Build a new array subscript expression.
2292   ///
2293   /// By default, performs semantic analysis to build the new expression.
2294   /// Subclasses may override this routine to provide different behavior.
2295   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2296                                              SourceLocation LBracketLoc,
2297                                              Expr *RHS,
2298                                              SourceLocation RBracketLoc) {
2299     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2300                                              LBracketLoc, RHS,
2301                                              RBracketLoc);
2302   }
2303 
2304   /// Build a new array section expression.
2305   ///
2306   /// By default, performs semantic analysis to build the new expression.
2307   /// Subclasses may override this routine to provide different behavior.
2308   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2309                                         Expr *LowerBound,
2310                                         SourceLocation ColonLoc, Expr *Length,
2311                                         SourceLocation RBracketLoc) {
2312     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2313                                               ColonLoc, Length, RBracketLoc);
2314   }
2315 
2316   /// Build a new call expression.
2317   ///
2318   /// By default, performs semantic analysis to build the new expression.
2319   /// Subclasses may override this routine to provide different behavior.
2320   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2321                                    MultiExprArg Args,
2322                                    SourceLocation RParenLoc,
2323                                    Expr *ExecConfig = nullptr) {
2324     return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2325                                    RParenLoc, ExecConfig);
2326   }
2327 
2328   /// Build a new member access expression.
2329   ///
2330   /// By default, performs semantic analysis to build the new expression.
2331   /// Subclasses may override this routine to provide different behavior.
2332   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2333                                bool isArrow,
2334                                NestedNameSpecifierLoc QualifierLoc,
2335                                SourceLocation TemplateKWLoc,
2336                                const DeclarationNameInfo &MemberNameInfo,
2337                                ValueDecl *Member,
2338                                NamedDecl *FoundDecl,
2339                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2340                                NamedDecl *FirstQualifierInScope) {
2341     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2342                                                                       isArrow);
2343     if (!Member->getDeclName()) {
2344       // We have a reference to an unnamed field.  This is always the
2345       // base of an anonymous struct/union member access, i.e. the
2346       // field is always of record type.
2347       assert(Member->getType()->isRecordType() &&
2348              "unnamed member not of record type?");
2349 
2350       BaseResult =
2351         getSema().PerformObjectMemberConversion(BaseResult.get(),
2352                                                 QualifierLoc.getNestedNameSpecifier(),
2353                                                 FoundDecl, Member);
2354       if (BaseResult.isInvalid())
2355         return ExprError();
2356       Base = BaseResult.get();
2357 
2358       CXXScopeSpec EmptySS;
2359       return getSema().BuildFieldReferenceExpr(
2360           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2361           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2362     }
2363 
2364     CXXScopeSpec SS;
2365     SS.Adopt(QualifierLoc);
2366 
2367     Base = BaseResult.get();
2368     QualType BaseType = Base->getType();
2369 
2370     if (isArrow && !BaseType->isPointerType())
2371       return ExprError();
2372 
2373     // FIXME: this involves duplicating earlier analysis in a lot of
2374     // cases; we should avoid this when possible.
2375     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2376     R.addDecl(FoundDecl);
2377     R.resolveKind();
2378 
2379     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2380                                               SS, TemplateKWLoc,
2381                                               FirstQualifierInScope,
2382                                               R, ExplicitTemplateArgs,
2383                                               /*S*/nullptr);
2384   }
2385 
2386   /// Build a new binary operator expression.
2387   ///
2388   /// By default, performs semantic analysis to build the new expression.
2389   /// Subclasses may override this routine to provide different behavior.
2390   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2391                                          BinaryOperatorKind Opc,
2392                                          Expr *LHS, Expr *RHS) {
2393     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2394   }
2395 
2396   /// Build a new rewritten operator expression.
2397   ///
2398   /// By default, performs semantic analysis to build the new expression.
2399   /// Subclasses may override this routine to provide different behavior.
2400   ExprResult RebuildCXXRewrittenBinaryOperator(
2401       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2402       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2403     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2404                                            RHS, /*RequiresADL*/false);
2405   }
2406 
2407   /// Build a new conditional operator expression.
2408   ///
2409   /// By default, performs semantic analysis to build the new expression.
2410   /// Subclasses may override this routine to provide different behavior.
2411   ExprResult RebuildConditionalOperator(Expr *Cond,
2412                                         SourceLocation QuestionLoc,
2413                                         Expr *LHS,
2414                                         SourceLocation ColonLoc,
2415                                         Expr *RHS) {
2416     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2417                                         LHS, RHS);
2418   }
2419 
2420   /// Build a new C-style cast expression.
2421   ///
2422   /// By default, performs semantic analysis to build the new expression.
2423   /// Subclasses may override this routine to provide different behavior.
2424   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2425                                          TypeSourceInfo *TInfo,
2426                                          SourceLocation RParenLoc,
2427                                          Expr *SubExpr) {
2428     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2429                                          SubExpr);
2430   }
2431 
2432   /// Build a new compound literal expression.
2433   ///
2434   /// By default, performs semantic analysis to build the new expression.
2435   /// Subclasses may override this routine to provide different behavior.
2436   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2437                                               TypeSourceInfo *TInfo,
2438                                               SourceLocation RParenLoc,
2439                                               Expr *Init) {
2440     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2441                                               Init);
2442   }
2443 
2444   /// Build a new extended vector element access expression.
2445   ///
2446   /// By default, performs semantic analysis to build the new expression.
2447   /// Subclasses may override this routine to provide different behavior.
2448   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2449                                                SourceLocation OpLoc,
2450                                                SourceLocation AccessorLoc,
2451                                                IdentifierInfo &Accessor) {
2452 
2453     CXXScopeSpec SS;
2454     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2455     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2456                                               OpLoc, /*IsArrow*/ false,
2457                                               SS, SourceLocation(),
2458                                               /*FirstQualifierInScope*/ nullptr,
2459                                               NameInfo,
2460                                               /* TemplateArgs */ nullptr,
2461                                               /*S*/ nullptr);
2462   }
2463 
2464   /// Build a new initializer list expression.
2465   ///
2466   /// By default, performs semantic analysis to build the new expression.
2467   /// Subclasses may override this routine to provide different behavior.
2468   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2469                              MultiExprArg Inits,
2470                              SourceLocation RBraceLoc) {
2471     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2472   }
2473 
2474   /// Build a new designated initializer expression.
2475   ///
2476   /// By default, performs semantic analysis to build the new expression.
2477   /// Subclasses may override this routine to provide different behavior.
2478   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2479                                              MultiExprArg ArrayExprs,
2480                                              SourceLocation EqualOrColonLoc,
2481                                              bool GNUSyntax,
2482                                              Expr *Init) {
2483     ExprResult Result
2484       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2485                                            Init);
2486     if (Result.isInvalid())
2487       return ExprError();
2488 
2489     return Result;
2490   }
2491 
2492   /// Build a new value-initialized expression.
2493   ///
2494   /// By default, builds the implicit value initialization without performing
2495   /// any semantic analysis. Subclasses may override this routine to provide
2496   /// different behavior.
2497   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2498     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2499   }
2500 
2501   /// Build a new \c va_arg expression.
2502   ///
2503   /// By default, performs semantic analysis to build the new expression.
2504   /// Subclasses may override this routine to provide different behavior.
2505   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2506                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2507                                     SourceLocation RParenLoc) {
2508     return getSema().BuildVAArgExpr(BuiltinLoc,
2509                                     SubExpr, TInfo,
2510                                     RParenLoc);
2511   }
2512 
2513   /// Build a new expression list in parentheses.
2514   ///
2515   /// By default, performs semantic analysis to build the new expression.
2516   /// Subclasses may override this routine to provide different behavior.
2517   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2518                                   MultiExprArg SubExprs,
2519                                   SourceLocation RParenLoc) {
2520     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2521   }
2522 
2523   /// Build a new address-of-label expression.
2524   ///
2525   /// By default, performs semantic analysis, using the name of the label
2526   /// rather than attempting to map the label statement itself.
2527   /// Subclasses may override this routine to provide different behavior.
2528   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2529                                   SourceLocation LabelLoc, LabelDecl *Label) {
2530     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2531   }
2532 
2533   /// Build a new GNU statement expression.
2534   ///
2535   /// By default, performs semantic analysis to build the new expression.
2536   /// Subclasses may override this routine to provide different behavior.
2537   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2538                              SourceLocation RParenLoc, unsigned TemplateDepth) {
2539     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2540                                    TemplateDepth);
2541   }
2542 
2543   /// Build a new __builtin_choose_expr expression.
2544   ///
2545   /// By default, performs semantic analysis to build the new expression.
2546   /// Subclasses may override this routine to provide different behavior.
2547   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2548                                      Expr *Cond, Expr *LHS, Expr *RHS,
2549                                      SourceLocation RParenLoc) {
2550     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2551                                    Cond, LHS, RHS,
2552                                    RParenLoc);
2553   }
2554 
2555   /// Build a new generic selection expression.
2556   ///
2557   /// By default, performs semantic analysis to build the new expression.
2558   /// Subclasses may override this routine to provide different behavior.
2559   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2560                                          SourceLocation DefaultLoc,
2561                                          SourceLocation RParenLoc,
2562                                          Expr *ControllingExpr,
2563                                          ArrayRef<TypeSourceInfo *> Types,
2564                                          ArrayRef<Expr *> Exprs) {
2565     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2566                                                 ControllingExpr, Types, Exprs);
2567   }
2568 
2569   /// Build a new overloaded operator call expression.
2570   ///
2571   /// By default, performs semantic analysis to build the new expression.
2572   /// The semantic analysis provides the behavior of template instantiation,
2573   /// copying with transformations that turn what looks like an overloaded
2574   /// operator call into a use of a builtin operator, performing
2575   /// argument-dependent lookup, etc. Subclasses may override this routine to
2576   /// provide different behavior.
2577   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2578                                               SourceLocation OpLoc,
2579                                               Expr *Callee,
2580                                               Expr *First,
2581                                               Expr *Second);
2582 
2583   /// Build a new C++ "named" cast expression, such as static_cast or
2584   /// reinterpret_cast.
2585   ///
2586   /// By default, this routine dispatches to one of the more-specific routines
2587   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2588   /// Subclasses may override this routine to provide different behavior.
2589   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2590                                            Stmt::StmtClass Class,
2591                                            SourceLocation LAngleLoc,
2592                                            TypeSourceInfo *TInfo,
2593                                            SourceLocation RAngleLoc,
2594                                            SourceLocation LParenLoc,
2595                                            Expr *SubExpr,
2596                                            SourceLocation RParenLoc) {
2597     switch (Class) {
2598     case Stmt::CXXStaticCastExprClass:
2599       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2600                                                    RAngleLoc, LParenLoc,
2601                                                    SubExpr, RParenLoc);
2602 
2603     case Stmt::CXXDynamicCastExprClass:
2604       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2605                                                     RAngleLoc, LParenLoc,
2606                                                     SubExpr, RParenLoc);
2607 
2608     case Stmt::CXXReinterpretCastExprClass:
2609       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2610                                                         RAngleLoc, LParenLoc,
2611                                                         SubExpr,
2612                                                         RParenLoc);
2613 
2614     case Stmt::CXXConstCastExprClass:
2615       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2616                                                    RAngleLoc, LParenLoc,
2617                                                    SubExpr, RParenLoc);
2618 
2619     default:
2620       llvm_unreachable("Invalid C++ named cast");
2621     }
2622   }
2623 
2624   /// Build a new C++ static_cast expression.
2625   ///
2626   /// By default, performs semantic analysis to build the new expression.
2627   /// Subclasses may override this routine to provide different behavior.
2628   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2629                                             SourceLocation LAngleLoc,
2630                                             TypeSourceInfo *TInfo,
2631                                             SourceLocation RAngleLoc,
2632                                             SourceLocation LParenLoc,
2633                                             Expr *SubExpr,
2634                                             SourceLocation RParenLoc) {
2635     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2636                                        TInfo, SubExpr,
2637                                        SourceRange(LAngleLoc, RAngleLoc),
2638                                        SourceRange(LParenLoc, RParenLoc));
2639   }
2640 
2641   /// Build a new C++ dynamic_cast expression.
2642   ///
2643   /// By default, performs semantic analysis to build the new expression.
2644   /// Subclasses may override this routine to provide different behavior.
2645   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2646                                              SourceLocation LAngleLoc,
2647                                              TypeSourceInfo *TInfo,
2648                                              SourceLocation RAngleLoc,
2649                                              SourceLocation LParenLoc,
2650                                              Expr *SubExpr,
2651                                              SourceLocation RParenLoc) {
2652     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2653                                        TInfo, SubExpr,
2654                                        SourceRange(LAngleLoc, RAngleLoc),
2655                                        SourceRange(LParenLoc, RParenLoc));
2656   }
2657 
2658   /// Build a new C++ reinterpret_cast expression.
2659   ///
2660   /// By default, performs semantic analysis to build the new expression.
2661   /// Subclasses may override this routine to provide different behavior.
2662   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2663                                                  SourceLocation LAngleLoc,
2664                                                  TypeSourceInfo *TInfo,
2665                                                  SourceLocation RAngleLoc,
2666                                                  SourceLocation LParenLoc,
2667                                                  Expr *SubExpr,
2668                                                  SourceLocation RParenLoc) {
2669     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2670                                        TInfo, SubExpr,
2671                                        SourceRange(LAngleLoc, RAngleLoc),
2672                                        SourceRange(LParenLoc, RParenLoc));
2673   }
2674 
2675   /// Build a new C++ const_cast expression.
2676   ///
2677   /// By default, performs semantic analysis to build the new expression.
2678   /// Subclasses may override this routine to provide different behavior.
2679   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2680                                            SourceLocation LAngleLoc,
2681                                            TypeSourceInfo *TInfo,
2682                                            SourceLocation RAngleLoc,
2683                                            SourceLocation LParenLoc,
2684                                            Expr *SubExpr,
2685                                            SourceLocation RParenLoc) {
2686     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2687                                        TInfo, SubExpr,
2688                                        SourceRange(LAngleLoc, RAngleLoc),
2689                                        SourceRange(LParenLoc, RParenLoc));
2690   }
2691 
2692   /// Build a new C++ functional-style cast expression.
2693   ///
2694   /// By default, performs semantic analysis to build the new expression.
2695   /// Subclasses may override this routine to provide different behavior.
2696   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2697                                           SourceLocation LParenLoc,
2698                                           Expr *Sub,
2699                                           SourceLocation RParenLoc,
2700                                           bool ListInitialization) {
2701     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2702                                                MultiExprArg(&Sub, 1), RParenLoc,
2703                                                ListInitialization);
2704   }
2705 
2706   /// Build a new C++ __builtin_bit_cast 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 RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2711                                        TypeSourceInfo *TSI, Expr *Sub,
2712                                        SourceLocation RParenLoc) {
2713     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2714   }
2715 
2716   /// Build a new C++ typeid(type) expression.
2717   ///
2718   /// By default, performs semantic analysis to build the new expression.
2719   /// Subclasses may override this routine to provide different behavior.
2720   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2721                                         SourceLocation TypeidLoc,
2722                                         TypeSourceInfo *Operand,
2723                                         SourceLocation RParenLoc) {
2724     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2725                                     RParenLoc);
2726   }
2727 
2728 
2729   /// Build a new C++ typeid(expr) expression.
2730   ///
2731   /// By default, performs semantic analysis to build the new expression.
2732   /// Subclasses may override this routine to provide different behavior.
2733   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2734                                         SourceLocation TypeidLoc,
2735                                         Expr *Operand,
2736                                         SourceLocation RParenLoc) {
2737     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2738                                     RParenLoc);
2739   }
2740 
2741   /// Build a new C++ __uuidof(type) expression.
2742   ///
2743   /// By default, performs semantic analysis to build the new expression.
2744   /// Subclasses may override this routine to provide different behavior.
2745   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2746                                         SourceLocation TypeidLoc,
2747                                         TypeSourceInfo *Operand,
2748                                         SourceLocation RParenLoc) {
2749     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2750                                     RParenLoc);
2751   }
2752 
2753   /// Build a new C++ __uuidof(expr) 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 RebuildCXXUuidofExpr(QualType TypeInfoType,
2758                                         SourceLocation TypeidLoc,
2759                                         Expr *Operand,
2760                                         SourceLocation RParenLoc) {
2761     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2762                                     RParenLoc);
2763   }
2764 
2765   /// Build a new C++ "this" expression.
2766   ///
2767   /// By default, builds a new "this" expression without performing any
2768   /// semantic analysis. Subclasses may override this routine to provide
2769   /// different behavior.
2770   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2771                                 QualType ThisType,
2772                                 bool isImplicit) {
2773     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2774   }
2775 
2776   /// Build a new C++ throw expression.
2777   ///
2778   /// By default, performs semantic analysis to build the new expression.
2779   /// Subclasses may override this routine to provide different behavior.
2780   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2781                                  bool IsThrownVariableInScope) {
2782     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2783   }
2784 
2785   /// Build a new C++ default-argument expression.
2786   ///
2787   /// By default, builds a new default-argument expression, which does not
2788   /// require any semantic analysis. Subclasses may override this routine to
2789   /// provide different behavior.
2790   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2791     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2792                                      getSema().CurContext);
2793   }
2794 
2795   /// Build a new C++11 default-initialization expression.
2796   ///
2797   /// By default, builds a new default field initialization expression, which
2798   /// does not require any semantic analysis. Subclasses may override this
2799   /// routine to provide different behavior.
2800   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2801                                        FieldDecl *Field) {
2802     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2803                                       getSema().CurContext);
2804   }
2805 
2806   /// Build a new C++ zero-initialization expression.
2807   ///
2808   /// By default, performs semantic analysis to build the new expression.
2809   /// Subclasses may override this routine to provide different behavior.
2810   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2811                                            SourceLocation LParenLoc,
2812                                            SourceLocation RParenLoc) {
2813     return getSema().BuildCXXTypeConstructExpr(
2814         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2815   }
2816 
2817   /// Build a new C++ "new" expression.
2818   ///
2819   /// By default, performs semantic analysis to build the new expression.
2820   /// Subclasses may override this routine to provide different behavior.
2821   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2822                                bool UseGlobal,
2823                                SourceLocation PlacementLParen,
2824                                MultiExprArg PlacementArgs,
2825                                SourceLocation PlacementRParen,
2826                                SourceRange TypeIdParens,
2827                                QualType AllocatedType,
2828                                TypeSourceInfo *AllocatedTypeInfo,
2829                                Optional<Expr *> ArraySize,
2830                                SourceRange DirectInitRange,
2831                                Expr *Initializer) {
2832     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2833                                  PlacementLParen,
2834                                  PlacementArgs,
2835                                  PlacementRParen,
2836                                  TypeIdParens,
2837                                  AllocatedType,
2838                                  AllocatedTypeInfo,
2839                                  ArraySize,
2840                                  DirectInitRange,
2841                                  Initializer);
2842   }
2843 
2844   /// Build a new C++ "delete" 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 RebuildCXXDeleteExpr(SourceLocation StartLoc,
2849                                         bool IsGlobalDelete,
2850                                         bool IsArrayForm,
2851                                         Expr *Operand) {
2852     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2853                                     Operand);
2854   }
2855 
2856   /// Build a new type 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 RebuildTypeTrait(TypeTrait Trait,
2861                               SourceLocation StartLoc,
2862                               ArrayRef<TypeSourceInfo *> Args,
2863                               SourceLocation RParenLoc) {
2864     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2865   }
2866 
2867   /// Build a new array type trait expression.
2868   ///
2869   /// By default, performs semantic analysis to build the new expression.
2870   /// Subclasses may override this routine to provide different behavior.
2871   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2872                                    SourceLocation StartLoc,
2873                                    TypeSourceInfo *TSInfo,
2874                                    Expr *DimExpr,
2875                                    SourceLocation RParenLoc) {
2876     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2877   }
2878 
2879   /// Build a new expression trait expression.
2880   ///
2881   /// By default, performs semantic analysis to build the new expression.
2882   /// Subclasses may override this routine to provide different behavior.
2883   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2884                                    SourceLocation StartLoc,
2885                                    Expr *Queried,
2886                                    SourceLocation RParenLoc) {
2887     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2888   }
2889 
2890   /// Build a new (previously unresolved) declaration reference
2891   /// expression.
2892   ///
2893   /// By default, performs semantic analysis to build the new expression.
2894   /// Subclasses may override this routine to provide different behavior.
2895   ExprResult RebuildDependentScopeDeclRefExpr(
2896                                           NestedNameSpecifierLoc QualifierLoc,
2897                                           SourceLocation TemplateKWLoc,
2898                                        const DeclarationNameInfo &NameInfo,
2899                               const TemplateArgumentListInfo *TemplateArgs,
2900                                           bool IsAddressOfOperand,
2901                                           TypeSourceInfo **RecoveryTSI) {
2902     CXXScopeSpec SS;
2903     SS.Adopt(QualifierLoc);
2904 
2905     if (TemplateArgs || TemplateKWLoc.isValid())
2906       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2907                                                     TemplateArgs);
2908 
2909     return getSema().BuildQualifiedDeclarationNameExpr(
2910         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2911   }
2912 
2913   /// Build a new template-id expression.
2914   ///
2915   /// By default, performs semantic analysis to build the new expression.
2916   /// Subclasses may override this routine to provide different behavior.
2917   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2918                                    SourceLocation TemplateKWLoc,
2919                                    LookupResult &R,
2920                                    bool RequiresADL,
2921                               const TemplateArgumentListInfo *TemplateArgs) {
2922     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2923                                          TemplateArgs);
2924   }
2925 
2926   /// Build a new object-construction expression.
2927   ///
2928   /// By default, performs semantic analysis to build the new expression.
2929   /// Subclasses may override this routine to provide different behavior.
2930   ExprResult RebuildCXXConstructExpr(QualType T,
2931                                      SourceLocation Loc,
2932                                      CXXConstructorDecl *Constructor,
2933                                      bool IsElidable,
2934                                      MultiExprArg Args,
2935                                      bool HadMultipleCandidates,
2936                                      bool ListInitialization,
2937                                      bool StdInitListInitialization,
2938                                      bool RequiresZeroInit,
2939                              CXXConstructExpr::ConstructionKind ConstructKind,
2940                                      SourceRange ParenRange) {
2941     SmallVector<Expr*, 8> ConvertedArgs;
2942     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2943                                           ConvertedArgs))
2944       return ExprError();
2945 
2946     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2947                                            IsElidable,
2948                                            ConvertedArgs,
2949                                            HadMultipleCandidates,
2950                                            ListInitialization,
2951                                            StdInitListInitialization,
2952                                            RequiresZeroInit, ConstructKind,
2953                                            ParenRange);
2954   }
2955 
2956   /// Build a new implicit construction via inherited constructor
2957   /// expression.
2958   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2959                                              CXXConstructorDecl *Constructor,
2960                                              bool ConstructsVBase,
2961                                              bool InheritedFromVBase) {
2962     return new (getSema().Context) CXXInheritedCtorInitExpr(
2963         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2964   }
2965 
2966   /// Build a new object-construction expression.
2967   ///
2968   /// By default, performs semantic analysis to build the new expression.
2969   /// Subclasses may override this routine to provide different behavior.
2970   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2971                                            SourceLocation LParenOrBraceLoc,
2972                                            MultiExprArg Args,
2973                                            SourceLocation RParenOrBraceLoc,
2974                                            bool ListInitialization) {
2975     return getSema().BuildCXXTypeConstructExpr(
2976         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2977   }
2978 
2979   /// Build a new object-construction expression.
2980   ///
2981   /// By default, performs semantic analysis to build the new expression.
2982   /// Subclasses may override this routine to provide different behavior.
2983   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2984                                                SourceLocation LParenLoc,
2985                                                MultiExprArg Args,
2986                                                SourceLocation RParenLoc,
2987                                                bool ListInitialization) {
2988     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2989                                                RParenLoc, ListInitialization);
2990   }
2991 
2992   /// Build a new member reference expression.
2993   ///
2994   /// By default, performs semantic analysis to build the new expression.
2995   /// Subclasses may override this routine to provide different behavior.
2996   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2997                                                 QualType BaseType,
2998                                                 bool IsArrow,
2999                                                 SourceLocation OperatorLoc,
3000                                           NestedNameSpecifierLoc QualifierLoc,
3001                                                 SourceLocation TemplateKWLoc,
3002                                             NamedDecl *FirstQualifierInScope,
3003                                    const DeclarationNameInfo &MemberNameInfo,
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                                             MemberNameInfo,
3013                                             TemplateArgs, /*S*/nullptr);
3014   }
3015 
3016   /// Build a new member reference expression.
3017   ///
3018   /// By default, performs semantic analysis to build the new expression.
3019   /// Subclasses may override this routine to provide different behavior.
3020   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3021                                          SourceLocation OperatorLoc,
3022                                          bool IsArrow,
3023                                          NestedNameSpecifierLoc QualifierLoc,
3024                                          SourceLocation TemplateKWLoc,
3025                                          NamedDecl *FirstQualifierInScope,
3026                                          LookupResult &R,
3027                                 const TemplateArgumentListInfo *TemplateArgs) {
3028     CXXScopeSpec SS;
3029     SS.Adopt(QualifierLoc);
3030 
3031     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3032                                             OperatorLoc, IsArrow,
3033                                             SS, TemplateKWLoc,
3034                                             FirstQualifierInScope,
3035                                             R, TemplateArgs, /*S*/nullptr);
3036   }
3037 
3038   /// Build a new noexcept expression.
3039   ///
3040   /// By default, performs semantic analysis to build the new expression.
3041   /// Subclasses may override this routine to provide different behavior.
3042   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3043     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3044   }
3045 
3046   /// Build a new expression to compute the length of a parameter pack.
3047   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3048                                    NamedDecl *Pack,
3049                                    SourceLocation PackLoc,
3050                                    SourceLocation RParenLoc,
3051                                    Optional<unsigned> Length,
3052                                    ArrayRef<TemplateArgument> PartialArgs) {
3053     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3054                                   RParenLoc, Length, PartialArgs);
3055   }
3056 
3057   /// Build a new expression representing a call to a source location
3058   ///  builtin.
3059   ///
3060   /// By default, performs semantic analysis to build the new expression.
3061   /// Subclasses may override this routine to provide different behavior.
3062   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3063                                   SourceLocation BuiltinLoc,
3064                                   SourceLocation RPLoc,
3065                                   DeclContext *ParentContext) {
3066     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3067   }
3068 
3069   /// Build a new Objective-C boxed expression.
3070   ///
3071   /// By default, performs semantic analysis to build the new expression.
3072   /// Subclasses may override this routine to provide different behavior.
3073   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3074       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3075       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3076       TemplateArgumentListInfo *TALI) {
3077     CXXScopeSpec SS;
3078     SS.Adopt(NNS);
3079     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3080                                                          ConceptNameInfo,
3081                                                          FoundDecl,
3082                                                          NamedConcept, TALI);
3083     if (Result.isInvalid())
3084       return ExprError();
3085     return Result;
3086   }
3087 
3088   /// \brief Build a new requires expression.
3089   ///
3090   /// By default, performs semantic analysis to build the new expression.
3091   /// Subclasses may override this routine to provide different behavior.
3092   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3093                                  RequiresExprBodyDecl *Body,
3094                                  ArrayRef<ParmVarDecl *> LocalParameters,
3095                                  ArrayRef<concepts::Requirement *> Requirements,
3096                                  SourceLocation ClosingBraceLoc) {
3097     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3098                                 LocalParameters, Requirements, ClosingBraceLoc);
3099   }
3100 
3101   concepts::TypeRequirement *
3102   RebuildTypeRequirement(
3103       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3104     return SemaRef.BuildTypeRequirement(SubstDiag);
3105   }
3106 
3107   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3108     return SemaRef.BuildTypeRequirement(T);
3109   }
3110 
3111   concepts::ExprRequirement *
3112   RebuildExprRequirement(
3113       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3114       SourceLocation NoexceptLoc,
3115       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3116     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3117                                         std::move(Ret));
3118   }
3119 
3120   concepts::ExprRequirement *
3121   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3122                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3123     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3124                                         std::move(Ret));
3125   }
3126 
3127   concepts::NestedRequirement *
3128   RebuildNestedRequirement(
3129       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3130     return SemaRef.BuildNestedRequirement(SubstDiag);
3131   }
3132 
3133   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3134     return SemaRef.BuildNestedRequirement(Constraint);
3135   }
3136 
3137   /// \brief Build a new Objective-C boxed expression.
3138   ///
3139   /// By default, performs semantic analysis to build the new expression.
3140   /// Subclasses may override this routine to provide different behavior.
3141   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3142     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3143   }
3144 
3145   /// Build a new Objective-C array literal.
3146   ///
3147   /// By default, performs semantic analysis to build the new expression.
3148   /// Subclasses may override this routine to provide different behavior.
3149   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3150                                      Expr **Elements, unsigned NumElements) {
3151     return getSema().BuildObjCArrayLiteral(Range,
3152                                            MultiExprArg(Elements, NumElements));
3153   }
3154 
3155   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3156                                          Expr *Base, Expr *Key,
3157                                          ObjCMethodDecl *getterMethod,
3158                                          ObjCMethodDecl *setterMethod) {
3159     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3160                                                    getterMethod, setterMethod);
3161   }
3162 
3163   /// Build a new Objective-C dictionary literal.
3164   ///
3165   /// By default, performs semantic analysis to build the new expression.
3166   /// Subclasses may override this routine to provide different behavior.
3167   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3168                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3169     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3170   }
3171 
3172   /// Build a new Objective-C \@encode expression.
3173   ///
3174   /// By default, performs semantic analysis to build the new expression.
3175   /// Subclasses may override this routine to provide different behavior.
3176   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3177                                          TypeSourceInfo *EncodeTypeInfo,
3178                                          SourceLocation RParenLoc) {
3179     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3180   }
3181 
3182   /// Build a new Objective-C class message.
3183   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3184                                           Selector Sel,
3185                                           ArrayRef<SourceLocation> SelectorLocs,
3186                                           ObjCMethodDecl *Method,
3187                                           SourceLocation LBracLoc,
3188                                           MultiExprArg Args,
3189                                           SourceLocation RBracLoc) {
3190     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3191                                      ReceiverTypeInfo->getType(),
3192                                      /*SuperLoc=*/SourceLocation(),
3193                                      Sel, Method, LBracLoc, SelectorLocs,
3194                                      RBracLoc, Args);
3195   }
3196 
3197   /// Build a new Objective-C instance message.
3198   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3199                                           Selector Sel,
3200                                           ArrayRef<SourceLocation> SelectorLocs,
3201                                           ObjCMethodDecl *Method,
3202                                           SourceLocation LBracLoc,
3203                                           MultiExprArg Args,
3204                                           SourceLocation RBracLoc) {
3205     return SemaRef.BuildInstanceMessage(Receiver,
3206                                         Receiver->getType(),
3207                                         /*SuperLoc=*/SourceLocation(),
3208                                         Sel, Method, LBracLoc, SelectorLocs,
3209                                         RBracLoc, Args);
3210   }
3211 
3212   /// Build a new Objective-C instance/class message to 'super'.
3213   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3214                                     Selector Sel,
3215                                     ArrayRef<SourceLocation> SelectorLocs,
3216                                     QualType SuperType,
3217                                     ObjCMethodDecl *Method,
3218                                     SourceLocation LBracLoc,
3219                                     MultiExprArg Args,
3220                                     SourceLocation RBracLoc) {
3221     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3222                                           SuperType,
3223                                           SuperLoc,
3224                                           Sel, Method, LBracLoc, SelectorLocs,
3225                                           RBracLoc, Args)
3226                                       : SemaRef.BuildClassMessage(nullptr,
3227                                           SuperType,
3228                                           SuperLoc,
3229                                           Sel, Method, LBracLoc, SelectorLocs,
3230                                           RBracLoc, Args);
3231 
3232 
3233   }
3234 
3235   /// Build a new Objective-C ivar reference 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 RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3240                                           SourceLocation IvarLoc,
3241                                           bool IsArrow, bool IsFreeIvar) {
3242     CXXScopeSpec SS;
3243     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3244     ExprResult Result = getSema().BuildMemberReferenceExpr(
3245         BaseArg, BaseArg->getType(),
3246         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3247         /*FirstQualifierInScope=*/nullptr, NameInfo,
3248         /*TemplateArgs=*/nullptr,
3249         /*S=*/nullptr);
3250     if (IsFreeIvar && Result.isUsable())
3251       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3252     return Result;
3253   }
3254 
3255   /// Build a new Objective-C property reference expression.
3256   ///
3257   /// By default, performs semantic analysis to build the new expression.
3258   /// Subclasses may override this routine to provide different behavior.
3259   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3260                                         ObjCPropertyDecl *Property,
3261                                         SourceLocation PropertyLoc) {
3262     CXXScopeSpec SS;
3263     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3264     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3265                                               /*FIXME:*/PropertyLoc,
3266                                               /*IsArrow=*/false,
3267                                               SS, SourceLocation(),
3268                                               /*FirstQualifierInScope=*/nullptr,
3269                                               NameInfo,
3270                                               /*TemplateArgs=*/nullptr,
3271                                               /*S=*/nullptr);
3272   }
3273 
3274   /// Build a new Objective-C property reference expression.
3275   ///
3276   /// By default, performs semantic analysis to build the new expression.
3277   /// Subclasses may override this routine to provide different behavior.
3278   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3279                                         ObjCMethodDecl *Getter,
3280                                         ObjCMethodDecl *Setter,
3281                                         SourceLocation PropertyLoc) {
3282     // Since these expressions can only be value-dependent, we do not
3283     // need to perform semantic analysis again.
3284     return Owned(
3285       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3286                                                   VK_LValue, OK_ObjCProperty,
3287                                                   PropertyLoc, Base));
3288   }
3289 
3290   /// Build a new Objective-C "isa" expression.
3291   ///
3292   /// By default, performs semantic analysis to build the new expression.
3293   /// Subclasses may override this routine to provide different behavior.
3294   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3295                                 SourceLocation OpLoc, bool IsArrow) {
3296     CXXScopeSpec SS;
3297     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3298     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3299                                               OpLoc, IsArrow,
3300                                               SS, SourceLocation(),
3301                                               /*FirstQualifierInScope=*/nullptr,
3302                                               NameInfo,
3303                                               /*TemplateArgs=*/nullptr,
3304                                               /*S=*/nullptr);
3305   }
3306 
3307   /// Build a new shuffle vector expression.
3308   ///
3309   /// By default, performs semantic analysis to build the new expression.
3310   /// Subclasses may override this routine to provide different behavior.
3311   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3312                                       MultiExprArg SubExprs,
3313                                       SourceLocation RParenLoc) {
3314     // Find the declaration for __builtin_shufflevector
3315     const IdentifierInfo &Name
3316       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3317     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3318     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3319     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3320 
3321     // Build a reference to the __builtin_shufflevector builtin
3322     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3323     Expr *Callee = new (SemaRef.Context)
3324         DeclRefExpr(SemaRef.Context, Builtin, false,
3325                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3326     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3327     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3328                                        CK_BuiltinFnToFnPtr).get();
3329 
3330     // Build the CallExpr
3331     ExprResult TheCall = CallExpr::Create(
3332         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3333         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3334 
3335     // Type-check the __builtin_shufflevector expression.
3336     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3337   }
3338 
3339   /// Build a new convert vector expression.
3340   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3341                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3342                                       SourceLocation RParenLoc) {
3343     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3344                                          BuiltinLoc, RParenLoc);
3345   }
3346 
3347   /// Build a new template argument pack expansion.
3348   ///
3349   /// By default, performs semantic analysis to build a new pack expansion
3350   /// for a template argument. Subclasses may override this routine to provide
3351   /// different behavior.
3352   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3353                                            SourceLocation EllipsisLoc,
3354                                            Optional<unsigned> NumExpansions) {
3355     switch (Pattern.getArgument().getKind()) {
3356     case TemplateArgument::Expression: {
3357       ExprResult Result
3358         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3359                                        EllipsisLoc, NumExpansions);
3360       if (Result.isInvalid())
3361         return TemplateArgumentLoc();
3362 
3363       return TemplateArgumentLoc(Result.get(), Result.get());
3364     }
3365 
3366     case TemplateArgument::Template:
3367       return TemplateArgumentLoc(TemplateArgument(
3368                                           Pattern.getArgument().getAsTemplate(),
3369                                                   NumExpansions),
3370                                  Pattern.getTemplateQualifierLoc(),
3371                                  Pattern.getTemplateNameLoc(),
3372                                  EllipsisLoc);
3373 
3374     case TemplateArgument::Null:
3375     case TemplateArgument::Integral:
3376     case TemplateArgument::Declaration:
3377     case TemplateArgument::Pack:
3378     case TemplateArgument::TemplateExpansion:
3379     case TemplateArgument::NullPtr:
3380       llvm_unreachable("Pack expansion pattern has no parameter packs");
3381 
3382     case TemplateArgument::Type:
3383       if (TypeSourceInfo *Expansion
3384             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3385                                            EllipsisLoc,
3386                                            NumExpansions))
3387         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3388                                    Expansion);
3389       break;
3390     }
3391 
3392     return TemplateArgumentLoc();
3393   }
3394 
3395   /// Build a new expression pack expansion.
3396   ///
3397   /// By default, performs semantic analysis to build a new pack expansion
3398   /// for an expression. Subclasses may override this routine to provide
3399   /// different behavior.
3400   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3401                                   Optional<unsigned> NumExpansions) {
3402     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3403   }
3404 
3405   /// Build a new C++1z fold-expression.
3406   ///
3407   /// By default, performs semantic analysis in order to build a new fold
3408   /// expression.
3409   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3410                                 BinaryOperatorKind Operator,
3411                                 SourceLocation EllipsisLoc, Expr *RHS,
3412                                 SourceLocation RParenLoc,
3413                                 Optional<unsigned> NumExpansions) {
3414     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3415                                       RHS, RParenLoc, NumExpansions);
3416   }
3417 
3418   /// Build an empty C++1z fold-expression with the given operator.
3419   ///
3420   /// By default, produces the fallback value for the fold-expression, or
3421   /// produce an error if there is no fallback value.
3422   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3423                                      BinaryOperatorKind Operator) {
3424     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3425   }
3426 
3427   /// Build a new atomic operation expression.
3428   ///
3429   /// By default, performs semantic analysis to build the new expression.
3430   /// Subclasses may override this routine to provide different behavior.
3431   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3432                                AtomicExpr::AtomicOp Op,
3433                                SourceLocation RParenLoc) {
3434     // Use this for all of the locations, since we don't know the difference
3435     // between the call and the expr at this point.
3436     SourceRange Range{BuiltinLoc, RParenLoc};
3437     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3438                                      Sema::AtomicArgumentOrder::AST);
3439   }
3440 
3441 private:
3442   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3443                                      QualType ObjectType,
3444                                      NamedDecl *FirstQualifierInScope,
3445                                      CXXScopeSpec &SS);
3446 
3447   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3448                                              QualType ObjectType,
3449                                              NamedDecl *FirstQualifierInScope,
3450                                              CXXScopeSpec &SS);
3451 
3452   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3453                                             NamedDecl *FirstQualifierInScope,
3454                                             CXXScopeSpec &SS);
3455 
3456   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3457                                       DependentNameTypeLoc TL,
3458                                       bool DeducibleTSTContext);
3459 };
3460 
3461 template <typename Derived>
3462 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3463   if (!S)
3464     return S;
3465 
3466   switch (S->getStmtClass()) {
3467   case Stmt::NoStmtClass: break;
3468 
3469   // Transform individual statement nodes
3470   // Pass SDK into statements that can produce a value
3471 #define STMT(Node, Parent)                                              \
3472   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3473 #define VALUESTMT(Node, Parent)                                         \
3474   case Stmt::Node##Class:                                               \
3475     return getDerived().Transform##Node(cast<Node>(S), SDK);
3476 #define ABSTRACT_STMT(Node)
3477 #define EXPR(Node, Parent)
3478 #include "clang/AST/StmtNodes.inc"
3479 
3480   // Transform expressions by calling TransformExpr.
3481 #define STMT(Node, Parent)
3482 #define ABSTRACT_STMT(Stmt)
3483 #define EXPR(Node, Parent) case Stmt::Node##Class:
3484 #include "clang/AST/StmtNodes.inc"
3485     {
3486       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3487 
3488       if (SDK == SDK_StmtExprResult)
3489         E = getSema().ActOnStmtExprResult(E);
3490       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3491     }
3492   }
3493 
3494   return S;
3495 }
3496 
3497 template<typename Derived>
3498 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3499   if (!S)
3500     return S;
3501 
3502   switch (S->getClauseKind()) {
3503   default: break;
3504   // Transform individual clause nodes
3505 #define OPENMP_CLAUSE(Name, Class)                                             \
3506   case OMPC_ ## Name :                                                         \
3507     return getDerived().Transform ## Class(cast<Class>(S));
3508 #include "clang/Basic/OpenMPKinds.def"
3509   }
3510 
3511   return S;
3512 }
3513 
3514 
3515 template<typename Derived>
3516 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3517   if (!E)
3518     return E;
3519 
3520   switch (E->getStmtClass()) {
3521     case Stmt::NoStmtClass: break;
3522 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3523 #define ABSTRACT_STMT(Stmt)
3524 #define EXPR(Node, Parent)                                              \
3525     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3526 #include "clang/AST/StmtNodes.inc"
3527   }
3528 
3529   return E;
3530 }
3531 
3532 template<typename Derived>
3533 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3534                                                         bool NotCopyInit) {
3535   // Initializers are instantiated like expressions, except that various outer
3536   // layers are stripped.
3537   if (!Init)
3538     return Init;
3539 
3540   if (auto *FE = dyn_cast<FullExpr>(Init))
3541     Init = FE->getSubExpr();
3542 
3543   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3544     Init = AIL->getCommonExpr();
3545 
3546   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3547     Init = MTE->getSubExpr();
3548 
3549   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3550     Init = Binder->getSubExpr();
3551 
3552   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3553     Init = ICE->getSubExprAsWritten();
3554 
3555   if (CXXStdInitializerListExpr *ILE =
3556           dyn_cast<CXXStdInitializerListExpr>(Init))
3557     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3558 
3559   // If this is copy-initialization, we only need to reconstruct
3560   // InitListExprs. Other forms of copy-initialization will be a no-op if
3561   // the initializer is already the right type.
3562   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3563   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3564     return getDerived().TransformExpr(Init);
3565 
3566   // Revert value-initialization back to empty parens.
3567   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3568     SourceRange Parens = VIE->getSourceRange();
3569     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3570                                              Parens.getEnd());
3571   }
3572 
3573   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3574   if (isa<ImplicitValueInitExpr>(Init))
3575     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3576                                              SourceLocation());
3577 
3578   // Revert initialization by constructor back to a parenthesized or braced list
3579   // of expressions. Any other form of initializer can just be reused directly.
3580   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3581     return getDerived().TransformExpr(Init);
3582 
3583   // If the initialization implicitly converted an initializer list to a
3584   // std::initializer_list object, unwrap the std::initializer_list too.
3585   if (Construct && Construct->isStdInitListInitialization())
3586     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3587 
3588   // Enter a list-init context if this was list initialization.
3589   EnterExpressionEvaluationContext Context(
3590       getSema(), EnterExpressionEvaluationContext::InitList,
3591       Construct->isListInitialization());
3592 
3593   SmallVector<Expr*, 8> NewArgs;
3594   bool ArgChanged = false;
3595   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3596                                   /*IsCall*/true, NewArgs, &ArgChanged))
3597     return ExprError();
3598 
3599   // If this was list initialization, revert to syntactic list form.
3600   if (Construct->isListInitialization())
3601     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3602                                         Construct->getEndLoc());
3603 
3604   // Build a ParenListExpr to represent anything else.
3605   SourceRange Parens = Construct->getParenOrBraceRange();
3606   if (Parens.isInvalid()) {
3607     // This was a variable declaration's initialization for which no initializer
3608     // was specified.
3609     assert(NewArgs.empty() &&
3610            "no parens or braces but have direct init with arguments?");
3611     return ExprEmpty();
3612   }
3613   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3614                                            Parens.getEnd());
3615 }
3616 
3617 template<typename Derived>
3618 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3619                                             unsigned NumInputs,
3620                                             bool IsCall,
3621                                       SmallVectorImpl<Expr *> &Outputs,
3622                                             bool *ArgChanged) {
3623   for (unsigned I = 0; I != NumInputs; ++I) {
3624     // If requested, drop call arguments that need to be dropped.
3625     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3626       if (ArgChanged)
3627         *ArgChanged = true;
3628 
3629       break;
3630     }
3631 
3632     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3633       Expr *Pattern = Expansion->getPattern();
3634 
3635       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3636       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3637       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3638 
3639       // Determine whether the set of unexpanded parameter packs can and should
3640       // be expanded.
3641       bool Expand = true;
3642       bool RetainExpansion = false;
3643       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3644       Optional<unsigned> NumExpansions = OrigNumExpansions;
3645       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3646                                                Pattern->getSourceRange(),
3647                                                Unexpanded,
3648                                                Expand, RetainExpansion,
3649                                                NumExpansions))
3650         return true;
3651 
3652       if (!Expand) {
3653         // The transform has determined that we should perform a simple
3654         // transformation on the pack expansion, producing another pack
3655         // expansion.
3656         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3657         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3658         if (OutPattern.isInvalid())
3659           return true;
3660 
3661         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3662                                                 Expansion->getEllipsisLoc(),
3663                                                            NumExpansions);
3664         if (Out.isInvalid())
3665           return true;
3666 
3667         if (ArgChanged)
3668           *ArgChanged = true;
3669         Outputs.push_back(Out.get());
3670         continue;
3671       }
3672 
3673       // Record right away that the argument was changed.  This needs
3674       // to happen even if the array expands to nothing.
3675       if (ArgChanged) *ArgChanged = true;
3676 
3677       // The transform has determined that we should perform an elementwise
3678       // expansion of the pattern. Do so.
3679       for (unsigned I = 0; I != *NumExpansions; ++I) {
3680         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3681         ExprResult Out = getDerived().TransformExpr(Pattern);
3682         if (Out.isInvalid())
3683           return true;
3684 
3685         if (Out.get()->containsUnexpandedParameterPack()) {
3686           Out = getDerived().RebuildPackExpansion(
3687               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3688           if (Out.isInvalid())
3689             return true;
3690         }
3691 
3692         Outputs.push_back(Out.get());
3693       }
3694 
3695       // If we're supposed to retain a pack expansion, do so by temporarily
3696       // forgetting the partially-substituted parameter pack.
3697       if (RetainExpansion) {
3698         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3699 
3700         ExprResult Out = getDerived().TransformExpr(Pattern);
3701         if (Out.isInvalid())
3702           return true;
3703 
3704         Out = getDerived().RebuildPackExpansion(
3705             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3706         if (Out.isInvalid())
3707           return true;
3708 
3709         Outputs.push_back(Out.get());
3710       }
3711 
3712       continue;
3713     }
3714 
3715     ExprResult Result =
3716       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3717              : getDerived().TransformExpr(Inputs[I]);
3718     if (Result.isInvalid())
3719       return true;
3720 
3721     if (Result.get() != Inputs[I] && ArgChanged)
3722       *ArgChanged = true;
3723 
3724     Outputs.push_back(Result.get());
3725   }
3726 
3727   return false;
3728 }
3729 
3730 template <typename Derived>
3731 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3732     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3733   if (Var) {
3734     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3735         getDerived().TransformDefinition(Var->getLocation(), Var));
3736 
3737     if (!ConditionVar)
3738       return Sema::ConditionError();
3739 
3740     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3741   }
3742 
3743   if (Expr) {
3744     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3745 
3746     if (CondExpr.isInvalid())
3747       return Sema::ConditionError();
3748 
3749     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3750   }
3751 
3752   return Sema::ConditionResult();
3753 }
3754 
3755 template<typename Derived>
3756 NestedNameSpecifierLoc
3757 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3758                                                     NestedNameSpecifierLoc NNS,
3759                                                      QualType ObjectType,
3760                                              NamedDecl *FirstQualifierInScope) {
3761   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3762   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3763        Qualifier = Qualifier.getPrefix())
3764     Qualifiers.push_back(Qualifier);
3765 
3766   CXXScopeSpec SS;
3767   while (!Qualifiers.empty()) {
3768     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3769     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3770 
3771     switch (QNNS->getKind()) {
3772     case NestedNameSpecifier::Identifier: {
3773       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3774                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3775       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3776                                               SS, FirstQualifierInScope, false))
3777         return NestedNameSpecifierLoc();
3778     }
3779       break;
3780 
3781     case NestedNameSpecifier::Namespace: {
3782       NamespaceDecl *NS
3783         = cast_or_null<NamespaceDecl>(
3784                                     getDerived().TransformDecl(
3785                                                           Q.getLocalBeginLoc(),
3786                                                        QNNS->getAsNamespace()));
3787       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3788       break;
3789     }
3790 
3791     case NestedNameSpecifier::NamespaceAlias: {
3792       NamespaceAliasDecl *Alias
3793         = cast_or_null<NamespaceAliasDecl>(
3794                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3795                                                  QNNS->getAsNamespaceAlias()));
3796       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3797                 Q.getLocalEndLoc());
3798       break;
3799     }
3800 
3801     case NestedNameSpecifier::Global:
3802       // There is no meaningful transformation that one could perform on the
3803       // global scope.
3804       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3805       break;
3806 
3807     case NestedNameSpecifier::Super: {
3808       CXXRecordDecl *RD =
3809           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3810               SourceLocation(), QNNS->getAsRecordDecl()));
3811       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3812       break;
3813     }
3814 
3815     case NestedNameSpecifier::TypeSpecWithTemplate:
3816     case NestedNameSpecifier::TypeSpec: {
3817       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3818                                               FirstQualifierInScope, SS);
3819 
3820       if (!TL)
3821         return NestedNameSpecifierLoc();
3822 
3823       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3824           (SemaRef.getLangOpts().CPlusPlus11 &&
3825            TL.getType()->isEnumeralType())) {
3826         assert(!TL.getType().hasLocalQualifiers() &&
3827                "Can't get cv-qualifiers here");
3828         if (TL.getType()->isEnumeralType())
3829           SemaRef.Diag(TL.getBeginLoc(),
3830                        diag::warn_cxx98_compat_enum_nested_name_spec);
3831         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3832                   Q.getLocalEndLoc());
3833         break;
3834       }
3835       // If the nested-name-specifier is an invalid type def, don't emit an
3836       // error because a previous error should have already been emitted.
3837       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3838       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3839         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3840           << TL.getType() << SS.getRange();
3841       }
3842       return NestedNameSpecifierLoc();
3843     }
3844     }
3845 
3846     // The qualifier-in-scope and object type only apply to the leftmost entity.
3847     FirstQualifierInScope = nullptr;
3848     ObjectType = QualType();
3849   }
3850 
3851   // Don't rebuild the nested-name-specifier if we don't have to.
3852   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3853       !getDerived().AlwaysRebuild())
3854     return NNS;
3855 
3856   // If we can re-use the source-location data from the original
3857   // nested-name-specifier, do so.
3858   if (SS.location_size() == NNS.getDataLength() &&
3859       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3860     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3861 
3862   // Allocate new nested-name-specifier location information.
3863   return SS.getWithLocInContext(SemaRef.Context);
3864 }
3865 
3866 template<typename Derived>
3867 DeclarationNameInfo
3868 TreeTransform<Derived>
3869 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3870   DeclarationName Name = NameInfo.getName();
3871   if (!Name)
3872     return DeclarationNameInfo();
3873 
3874   switch (Name.getNameKind()) {
3875   case DeclarationName::Identifier:
3876   case DeclarationName::ObjCZeroArgSelector:
3877   case DeclarationName::ObjCOneArgSelector:
3878   case DeclarationName::ObjCMultiArgSelector:
3879   case DeclarationName::CXXOperatorName:
3880   case DeclarationName::CXXLiteralOperatorName:
3881   case DeclarationName::CXXUsingDirective:
3882     return NameInfo;
3883 
3884   case DeclarationName::CXXDeductionGuideName: {
3885     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3886     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3887         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3888     if (!NewTemplate)
3889       return DeclarationNameInfo();
3890 
3891     DeclarationNameInfo NewNameInfo(NameInfo);
3892     NewNameInfo.setName(
3893         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3894     return NewNameInfo;
3895   }
3896 
3897   case DeclarationName::CXXConstructorName:
3898   case DeclarationName::CXXDestructorName:
3899   case DeclarationName::CXXConversionFunctionName: {
3900     TypeSourceInfo *NewTInfo;
3901     CanQualType NewCanTy;
3902     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3903       NewTInfo = getDerived().TransformType(OldTInfo);
3904       if (!NewTInfo)
3905         return DeclarationNameInfo();
3906       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3907     }
3908     else {
3909       NewTInfo = nullptr;
3910       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3911       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3912       if (NewT.isNull())
3913         return DeclarationNameInfo();
3914       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3915     }
3916 
3917     DeclarationName NewName
3918       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3919                                                            NewCanTy);
3920     DeclarationNameInfo NewNameInfo(NameInfo);
3921     NewNameInfo.setName(NewName);
3922     NewNameInfo.setNamedTypeInfo(NewTInfo);
3923     return NewNameInfo;
3924   }
3925   }
3926 
3927   llvm_unreachable("Unknown name kind.");
3928 }
3929 
3930 template<typename Derived>
3931 TemplateName
3932 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3933                                               TemplateName Name,
3934                                               SourceLocation NameLoc,
3935                                               QualType ObjectType,
3936                                               NamedDecl *FirstQualifierInScope,
3937                                               bool AllowInjectedClassName) {
3938   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3939     TemplateDecl *Template = QTN->getTemplateDecl();
3940     assert(Template && "qualified template name must refer to a template");
3941 
3942     TemplateDecl *TransTemplate
3943       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3944                                                               Template));
3945     if (!TransTemplate)
3946       return TemplateName();
3947 
3948     if (!getDerived().AlwaysRebuild() &&
3949         SS.getScopeRep() == QTN->getQualifier() &&
3950         TransTemplate == Template)
3951       return Name;
3952 
3953     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3954                                             TransTemplate);
3955   }
3956 
3957   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3958     if (SS.getScopeRep()) {
3959       // These apply to the scope specifier, not the template.
3960       ObjectType = QualType();
3961       FirstQualifierInScope = nullptr;
3962     }
3963 
3964     if (!getDerived().AlwaysRebuild() &&
3965         SS.getScopeRep() == DTN->getQualifier() &&
3966         ObjectType.isNull())
3967       return Name;
3968 
3969     // FIXME: Preserve the location of the "template" keyword.
3970     SourceLocation TemplateKWLoc = NameLoc;
3971 
3972     if (DTN->isIdentifier()) {
3973       return getDerived().RebuildTemplateName(SS,
3974                                               TemplateKWLoc,
3975                                               *DTN->getIdentifier(),
3976                                               NameLoc,
3977                                               ObjectType,
3978                                               FirstQualifierInScope,
3979                                               AllowInjectedClassName);
3980     }
3981 
3982     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3983                                             DTN->getOperator(), NameLoc,
3984                                             ObjectType, AllowInjectedClassName);
3985   }
3986 
3987   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3988     TemplateDecl *TransTemplate
3989       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3990                                                               Template));
3991     if (!TransTemplate)
3992       return TemplateName();
3993 
3994     if (!getDerived().AlwaysRebuild() &&
3995         TransTemplate == Template)
3996       return Name;
3997 
3998     return TemplateName(TransTemplate);
3999   }
4000 
4001   if (SubstTemplateTemplateParmPackStorage *SubstPack
4002       = Name.getAsSubstTemplateTemplateParmPack()) {
4003     TemplateTemplateParmDecl *TransParam
4004     = cast_or_null<TemplateTemplateParmDecl>(
4005             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
4006     if (!TransParam)
4007       return TemplateName();
4008 
4009     if (!getDerived().AlwaysRebuild() &&
4010         TransParam == SubstPack->getParameterPack())
4011       return Name;
4012 
4013     return getDerived().RebuildTemplateName(TransParam,
4014                                             SubstPack->getArgumentPack());
4015   }
4016 
4017   // These should be getting filtered out before they reach the AST.
4018   llvm_unreachable("overloaded function decl survived to here");
4019 }
4020 
4021 template<typename Derived>
4022 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4023                                          const TemplateArgument &Arg,
4024                                          TemplateArgumentLoc &Output) {
4025   SourceLocation Loc = getDerived().getBaseLocation();
4026   switch (Arg.getKind()) {
4027   case TemplateArgument::Null:
4028     llvm_unreachable("null template argument in TreeTransform");
4029     break;
4030 
4031   case TemplateArgument::Type:
4032     Output = TemplateArgumentLoc(Arg,
4033                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
4034 
4035     break;
4036 
4037   case TemplateArgument::Template:
4038   case TemplateArgument::TemplateExpansion: {
4039     NestedNameSpecifierLocBuilder Builder;
4040     TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
4041     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
4042       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
4043     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4044       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
4045 
4046     if (Arg.getKind() == TemplateArgument::Template)
4047       Output = TemplateArgumentLoc(Arg,
4048                                    Builder.getWithLocInContext(SemaRef.Context),
4049                                    Loc);
4050     else
4051       Output = TemplateArgumentLoc(Arg,
4052                                    Builder.getWithLocInContext(SemaRef.Context),
4053                                    Loc, Loc);
4054 
4055     break;
4056   }
4057 
4058   case TemplateArgument::Expression:
4059     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
4060     break;
4061 
4062   case TemplateArgument::Declaration:
4063   case TemplateArgument::Integral:
4064   case TemplateArgument::Pack:
4065   case TemplateArgument::NullPtr:
4066     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
4067     break;
4068   }
4069 }
4070 
4071 template<typename Derived>
4072 bool TreeTransform<Derived>::TransformTemplateArgument(
4073                                          const TemplateArgumentLoc &Input,
4074                                          TemplateArgumentLoc &Output, bool Uneval) {
4075   const TemplateArgument &Arg = Input.getArgument();
4076   switch (Arg.getKind()) {
4077   case TemplateArgument::Null:
4078   case TemplateArgument::Integral:
4079   case TemplateArgument::Pack:
4080   case TemplateArgument::Declaration:
4081   case TemplateArgument::NullPtr:
4082     llvm_unreachable("Unexpected TemplateArgument");
4083 
4084   case TemplateArgument::Type: {
4085     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4086     if (!DI)
4087       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4088 
4089     DI = getDerived().TransformType(DI);
4090     if (!DI) return true;
4091 
4092     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4093     return false;
4094   }
4095 
4096   case TemplateArgument::Template: {
4097     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4098     if (QualifierLoc) {
4099       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4100       if (!QualifierLoc)
4101         return true;
4102     }
4103 
4104     CXXScopeSpec SS;
4105     SS.Adopt(QualifierLoc);
4106     TemplateName Template
4107       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
4108                                            Input.getTemplateNameLoc());
4109     if (Template.isNull())
4110       return true;
4111 
4112     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
4113                                  Input.getTemplateNameLoc());
4114     return false;
4115   }
4116 
4117   case TemplateArgument::TemplateExpansion:
4118     llvm_unreachable("Caller should expand pack expansions");
4119 
4120   case TemplateArgument::Expression: {
4121     // Template argument expressions are constant expressions.
4122     EnterExpressionEvaluationContext Unevaluated(
4123         getSema(),
4124         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4125                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4126         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4127         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4128 
4129     Expr *InputExpr = Input.getSourceExpression();
4130     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4131 
4132     ExprResult E = getDerived().TransformExpr(InputExpr);
4133     E = SemaRef.ActOnConstantExpression(E);
4134     if (E.isInvalid()) return true;
4135     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4136     return false;
4137   }
4138   }
4139 
4140   // Work around bogus GCC warning
4141   return true;
4142 }
4143 
4144 /// Iterator adaptor that invents template argument location information
4145 /// for each of the template arguments in its underlying iterator.
4146 template<typename Derived, typename InputIterator>
4147 class TemplateArgumentLocInventIterator {
4148   TreeTransform<Derived> &Self;
4149   InputIterator Iter;
4150 
4151 public:
4152   typedef TemplateArgumentLoc value_type;
4153   typedef TemplateArgumentLoc reference;
4154   typedef typename std::iterator_traits<InputIterator>::difference_type
4155     difference_type;
4156   typedef std::input_iterator_tag iterator_category;
4157 
4158   class pointer {
4159     TemplateArgumentLoc Arg;
4160 
4161   public:
4162     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4163 
4164     const TemplateArgumentLoc *operator->() const { return &Arg; }
4165   };
4166 
4167   TemplateArgumentLocInventIterator() { }
4168 
4169   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4170                                              InputIterator Iter)
4171     : Self(Self), Iter(Iter) { }
4172 
4173   TemplateArgumentLocInventIterator &operator++() {
4174     ++Iter;
4175     return *this;
4176   }
4177 
4178   TemplateArgumentLocInventIterator operator++(int) {
4179     TemplateArgumentLocInventIterator Old(*this);
4180     ++(*this);
4181     return Old;
4182   }
4183 
4184   reference operator*() const {
4185     TemplateArgumentLoc Result;
4186     Self.InventTemplateArgumentLoc(*Iter, Result);
4187     return Result;
4188   }
4189 
4190   pointer operator->() const { return pointer(**this); }
4191 
4192   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4193                          const TemplateArgumentLocInventIterator &Y) {
4194     return X.Iter == Y.Iter;
4195   }
4196 
4197   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4198                          const TemplateArgumentLocInventIterator &Y) {
4199     return X.Iter != Y.Iter;
4200   }
4201 };
4202 
4203 template<typename Derived>
4204 template<typename InputIterator>
4205 bool TreeTransform<Derived>::TransformTemplateArguments(
4206     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4207     bool Uneval) {
4208   for (; First != Last; ++First) {
4209     TemplateArgumentLoc Out;
4210     TemplateArgumentLoc In = *First;
4211 
4212     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4213       // Unpack argument packs, which we translate them into separate
4214       // arguments.
4215       // FIXME: We could do much better if we could guarantee that the
4216       // TemplateArgumentLocInfo for the pack expansion would be usable for
4217       // all of the template arguments in the argument pack.
4218       typedef TemplateArgumentLocInventIterator<Derived,
4219                                                 TemplateArgument::pack_iterator>
4220         PackLocIterator;
4221       if (TransformTemplateArguments(PackLocIterator(*this,
4222                                                  In.getArgument().pack_begin()),
4223                                      PackLocIterator(*this,
4224                                                    In.getArgument().pack_end()),
4225                                      Outputs, Uneval))
4226         return true;
4227 
4228       continue;
4229     }
4230 
4231     if (In.getArgument().isPackExpansion()) {
4232       // We have a pack expansion, for which we will be substituting into
4233       // the pattern.
4234       SourceLocation Ellipsis;
4235       Optional<unsigned> OrigNumExpansions;
4236       TemplateArgumentLoc Pattern
4237         = getSema().getTemplateArgumentPackExpansionPattern(
4238               In, Ellipsis, OrigNumExpansions);
4239 
4240       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4241       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4242       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4243 
4244       // Determine whether the set of unexpanded parameter packs can and should
4245       // be expanded.
4246       bool Expand = true;
4247       bool RetainExpansion = false;
4248       Optional<unsigned> NumExpansions = OrigNumExpansions;
4249       if (getDerived().TryExpandParameterPacks(Ellipsis,
4250                                                Pattern.getSourceRange(),
4251                                                Unexpanded,
4252                                                Expand,
4253                                                RetainExpansion,
4254                                                NumExpansions))
4255         return true;
4256 
4257       if (!Expand) {
4258         // The transform has determined that we should perform a simple
4259         // transformation on the pack expansion, producing another pack
4260         // expansion.
4261         TemplateArgumentLoc OutPattern;
4262         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4263         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4264           return true;
4265 
4266         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4267                                                 NumExpansions);
4268         if (Out.getArgument().isNull())
4269           return true;
4270 
4271         Outputs.addArgument(Out);
4272         continue;
4273       }
4274 
4275       // The transform has determined that we should perform an elementwise
4276       // expansion of the pattern. Do so.
4277       for (unsigned I = 0; I != *NumExpansions; ++I) {
4278         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4279 
4280         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4281           return true;
4282 
4283         if (Out.getArgument().containsUnexpandedParameterPack()) {
4284           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4285                                                   OrigNumExpansions);
4286           if (Out.getArgument().isNull())
4287             return true;
4288         }
4289 
4290         Outputs.addArgument(Out);
4291       }
4292 
4293       // If we're supposed to retain a pack expansion, do so by temporarily
4294       // forgetting the partially-substituted parameter pack.
4295       if (RetainExpansion) {
4296         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4297 
4298         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4299           return true;
4300 
4301         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4302                                                 OrigNumExpansions);
4303         if (Out.getArgument().isNull())
4304           return true;
4305 
4306         Outputs.addArgument(Out);
4307       }
4308 
4309       continue;
4310     }
4311 
4312     // The simple case:
4313     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4314       return true;
4315 
4316     Outputs.addArgument(Out);
4317   }
4318 
4319   return false;
4320 
4321 }
4322 
4323 //===----------------------------------------------------------------------===//
4324 // Type transformation
4325 //===----------------------------------------------------------------------===//
4326 
4327 template<typename Derived>
4328 QualType TreeTransform<Derived>::TransformType(QualType T) {
4329   if (getDerived().AlreadyTransformed(T))
4330     return T;
4331 
4332   // Temporary workaround.  All of these transformations should
4333   // eventually turn into transformations on TypeLocs.
4334   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4335                                                 getDerived().getBaseLocation());
4336 
4337   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4338 
4339   if (!NewDI)
4340     return QualType();
4341 
4342   return NewDI->getType();
4343 }
4344 
4345 template<typename Derived>
4346 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4347   // Refine the base location to the type's location.
4348   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4349                        getDerived().getBaseEntity());
4350   if (getDerived().AlreadyTransformed(DI->getType()))
4351     return DI;
4352 
4353   TypeLocBuilder TLB;
4354 
4355   TypeLoc TL = DI->getTypeLoc();
4356   TLB.reserve(TL.getFullDataSize());
4357 
4358   QualType Result = getDerived().TransformType(TLB, TL);
4359   if (Result.isNull())
4360     return nullptr;
4361 
4362   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4363 }
4364 
4365 template<typename Derived>
4366 QualType
4367 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4368   switch (T.getTypeLocClass()) {
4369 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4370 #define TYPELOC(CLASS, PARENT)                                                 \
4371   case TypeLoc::CLASS:                                                         \
4372     return getDerived().Transform##CLASS##Type(TLB,                            \
4373                                                T.castAs<CLASS##TypeLoc>());
4374 #include "clang/AST/TypeLocNodes.def"
4375   }
4376 
4377   llvm_unreachable("unhandled type loc!");
4378 }
4379 
4380 template<typename Derived>
4381 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4382   if (!isa<DependentNameType>(T))
4383     return TransformType(T);
4384 
4385   if (getDerived().AlreadyTransformed(T))
4386     return T;
4387   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4388                                                 getDerived().getBaseLocation());
4389   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4390   return NewDI ? NewDI->getType() : QualType();
4391 }
4392 
4393 template<typename Derived>
4394 TypeSourceInfo *
4395 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4396   if (!isa<DependentNameType>(DI->getType()))
4397     return TransformType(DI);
4398 
4399   // Refine the base location to the type's location.
4400   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4401                        getDerived().getBaseEntity());
4402   if (getDerived().AlreadyTransformed(DI->getType()))
4403     return DI;
4404 
4405   TypeLocBuilder TLB;
4406 
4407   TypeLoc TL = DI->getTypeLoc();
4408   TLB.reserve(TL.getFullDataSize());
4409 
4410   auto QTL = TL.getAs<QualifiedTypeLoc>();
4411   if (QTL)
4412     TL = QTL.getUnqualifiedLoc();
4413 
4414   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4415 
4416   QualType Result = getDerived().TransformDependentNameType(
4417       TLB, DNTL, /*DeducedTSTContext*/true);
4418   if (Result.isNull())
4419     return nullptr;
4420 
4421   if (QTL) {
4422     Result = getDerived().RebuildQualifiedType(Result, QTL);
4423     if (Result.isNull())
4424       return nullptr;
4425     TLB.TypeWasModifiedSafely(Result);
4426   }
4427 
4428   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4429 }
4430 
4431 template<typename Derived>
4432 QualType
4433 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4434                                                QualifiedTypeLoc T) {
4435   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4436   if (Result.isNull())
4437     return QualType();
4438 
4439   Result = getDerived().RebuildQualifiedType(Result, T);
4440 
4441   if (Result.isNull())
4442     return QualType();
4443 
4444   // RebuildQualifiedType might have updated the type, but not in a way
4445   // that invalidates the TypeLoc. (There's no location information for
4446   // qualifiers.)
4447   TLB.TypeWasModifiedSafely(Result);
4448 
4449   return Result;
4450 }
4451 
4452 template <typename Derived>
4453 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4454                                                       QualifiedTypeLoc TL) {
4455 
4456   SourceLocation Loc = TL.getBeginLoc();
4457   Qualifiers Quals = TL.getType().getLocalQualifiers();
4458 
4459   if (((T.getAddressSpace() != LangAS::Default &&
4460         Quals.getAddressSpace() != LangAS::Default)) &&
4461       T.getAddressSpace() != Quals.getAddressSpace()) {
4462     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4463         << TL.getType() << T;
4464     return QualType();
4465   }
4466 
4467   // C++ [dcl.fct]p7:
4468   //   [When] adding cv-qualifications on top of the function type [...] the
4469   //   cv-qualifiers are ignored.
4470   if (T->isFunctionType()) {
4471     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4472                                                      Quals.getAddressSpace());
4473     return T;
4474   }
4475 
4476   // C++ [dcl.ref]p1:
4477   //   when the cv-qualifiers are introduced through the use of a typedef-name
4478   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4479   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4480   // applied to a reference type.
4481   if (T->isReferenceType()) {
4482     // The only qualifier that applies to a reference type is restrict.
4483     if (!Quals.hasRestrict())
4484       return T;
4485     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4486   }
4487 
4488   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4489   // resulting type.
4490   if (Quals.hasObjCLifetime()) {
4491     if (!T->isObjCLifetimeType() && !T->isDependentType())
4492       Quals.removeObjCLifetime();
4493     else if (T.getObjCLifetime()) {
4494       // Objective-C ARC:
4495       //   A lifetime qualifier applied to a substituted template parameter
4496       //   overrides the lifetime qualifier from the template argument.
4497       const AutoType *AutoTy;
4498       if (const SubstTemplateTypeParmType *SubstTypeParam
4499                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4500         QualType Replacement = SubstTypeParam->getReplacementType();
4501         Qualifiers Qs = Replacement.getQualifiers();
4502         Qs.removeObjCLifetime();
4503         Replacement = SemaRef.Context.getQualifiedType(
4504             Replacement.getUnqualifiedType(), Qs);
4505         T = SemaRef.Context.getSubstTemplateTypeParmType(
4506             SubstTypeParam->getReplacedParameter(), Replacement);
4507       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4508         // 'auto' types behave the same way as template parameters.
4509         QualType Deduced = AutoTy->getDeducedType();
4510         Qualifiers Qs = Deduced.getQualifiers();
4511         Qs.removeObjCLifetime();
4512         Deduced =
4513             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4514         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4515                                         AutoTy->isDependentType(),
4516                                         /*isPack=*/false,
4517                                         AutoTy->getTypeConstraintConcept(),
4518                                         AutoTy->getTypeConstraintArguments());
4519       } else {
4520         // Otherwise, complain about the addition of a qualifier to an
4521         // already-qualified type.
4522         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4523         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4524         Quals.removeObjCLifetime();
4525       }
4526     }
4527   }
4528 
4529   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4530 }
4531 
4532 template<typename Derived>
4533 TypeLoc
4534 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4535                                                    QualType ObjectType,
4536                                                    NamedDecl *UnqualLookup,
4537                                                    CXXScopeSpec &SS) {
4538   if (getDerived().AlreadyTransformed(TL.getType()))
4539     return TL;
4540 
4541   TypeSourceInfo *TSI =
4542       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4543   if (TSI)
4544     return TSI->getTypeLoc();
4545   return TypeLoc();
4546 }
4547 
4548 template<typename Derived>
4549 TypeSourceInfo *
4550 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4551                                                    QualType ObjectType,
4552                                                    NamedDecl *UnqualLookup,
4553                                                    CXXScopeSpec &SS) {
4554   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4555     return TSInfo;
4556 
4557   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4558                                    UnqualLookup, SS);
4559 }
4560 
4561 template <typename Derived>
4562 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4563     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4564     CXXScopeSpec &SS) {
4565   QualType T = TL.getType();
4566   assert(!getDerived().AlreadyTransformed(T));
4567 
4568   TypeLocBuilder TLB;
4569   QualType Result;
4570 
4571   if (isa<TemplateSpecializationType>(T)) {
4572     TemplateSpecializationTypeLoc SpecTL =
4573         TL.castAs<TemplateSpecializationTypeLoc>();
4574 
4575     TemplateName Template = getDerived().TransformTemplateName(
4576         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4577         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4578     if (Template.isNull())
4579       return nullptr;
4580 
4581     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4582                                                               Template);
4583   } else if (isa<DependentTemplateSpecializationType>(T)) {
4584     DependentTemplateSpecializationTypeLoc SpecTL =
4585         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4586 
4587     TemplateName Template
4588       = getDerived().RebuildTemplateName(SS,
4589                                          SpecTL.getTemplateKeywordLoc(),
4590                                          *SpecTL.getTypePtr()->getIdentifier(),
4591                                          SpecTL.getTemplateNameLoc(),
4592                                          ObjectType, UnqualLookup,
4593                                          /*AllowInjectedClassName*/true);
4594     if (Template.isNull())
4595       return nullptr;
4596 
4597     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4598                                                                        SpecTL,
4599                                                                        Template,
4600                                                                        SS);
4601   } else {
4602     // Nothing special needs to be done for these.
4603     Result = getDerived().TransformType(TLB, TL);
4604   }
4605 
4606   if (Result.isNull())
4607     return nullptr;
4608 
4609   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4610 }
4611 
4612 template <class TyLoc> static inline
4613 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4614   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4615   NewT.setNameLoc(T.getNameLoc());
4616   return T.getType();
4617 }
4618 
4619 template<typename Derived>
4620 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4621                                                       BuiltinTypeLoc T) {
4622   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4623   NewT.setBuiltinLoc(T.getBuiltinLoc());
4624   if (T.needsExtraLocalData())
4625     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4626   return T.getType();
4627 }
4628 
4629 template<typename Derived>
4630 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4631                                                       ComplexTypeLoc T) {
4632   // FIXME: recurse?
4633   return TransformTypeSpecType(TLB, T);
4634 }
4635 
4636 template <typename Derived>
4637 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4638                                                        AdjustedTypeLoc TL) {
4639   // Adjustments applied during transformation are handled elsewhere.
4640   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4641 }
4642 
4643 template<typename Derived>
4644 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4645                                                       DecayedTypeLoc TL) {
4646   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4647   if (OriginalType.isNull())
4648     return QualType();
4649 
4650   QualType Result = TL.getType();
4651   if (getDerived().AlwaysRebuild() ||
4652       OriginalType != TL.getOriginalLoc().getType())
4653     Result = SemaRef.Context.getDecayedType(OriginalType);
4654   TLB.push<DecayedTypeLoc>(Result);
4655   // Nothing to set for DecayedTypeLoc.
4656   return Result;
4657 }
4658 
4659 template<typename Derived>
4660 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4661                                                       PointerTypeLoc TL) {
4662   QualType PointeeType
4663     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4664   if (PointeeType.isNull())
4665     return QualType();
4666 
4667   QualType Result = TL.getType();
4668   if (PointeeType->getAs<ObjCObjectType>()) {
4669     // A dependent pointer type 'T *' has is being transformed such
4670     // that an Objective-C class type is being replaced for 'T'. The
4671     // resulting pointer type is an ObjCObjectPointerType, not a
4672     // PointerType.
4673     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4674 
4675     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4676     NewT.setStarLoc(TL.getStarLoc());
4677     return Result;
4678   }
4679 
4680   if (getDerived().AlwaysRebuild() ||
4681       PointeeType != TL.getPointeeLoc().getType()) {
4682     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4683     if (Result.isNull())
4684       return QualType();
4685   }
4686 
4687   // Objective-C ARC can add lifetime qualifiers to the type that we're
4688   // pointing to.
4689   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4690 
4691   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4692   NewT.setSigilLoc(TL.getSigilLoc());
4693   return Result;
4694 }
4695 
4696 template<typename Derived>
4697 QualType
4698 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4699                                                   BlockPointerTypeLoc TL) {
4700   QualType PointeeType
4701     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4702   if (PointeeType.isNull())
4703     return QualType();
4704 
4705   QualType Result = TL.getType();
4706   if (getDerived().AlwaysRebuild() ||
4707       PointeeType != TL.getPointeeLoc().getType()) {
4708     Result = getDerived().RebuildBlockPointerType(PointeeType,
4709                                                   TL.getSigilLoc());
4710     if (Result.isNull())
4711       return QualType();
4712   }
4713 
4714   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4715   NewT.setSigilLoc(TL.getSigilLoc());
4716   return Result;
4717 }
4718 
4719 /// Transforms a reference type.  Note that somewhat paradoxically we
4720 /// don't care whether the type itself is an l-value type or an r-value
4721 /// type;  we only care if the type was *written* as an l-value type
4722 /// or an r-value type.
4723 template<typename Derived>
4724 QualType
4725 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4726                                                ReferenceTypeLoc TL) {
4727   const ReferenceType *T = TL.getTypePtr();
4728 
4729   // Note that this works with the pointee-as-written.
4730   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4731   if (PointeeType.isNull())
4732     return QualType();
4733 
4734   QualType Result = TL.getType();
4735   if (getDerived().AlwaysRebuild() ||
4736       PointeeType != T->getPointeeTypeAsWritten()) {
4737     Result = getDerived().RebuildReferenceType(PointeeType,
4738                                                T->isSpelledAsLValue(),
4739                                                TL.getSigilLoc());
4740     if (Result.isNull())
4741       return QualType();
4742   }
4743 
4744   // Objective-C ARC can add lifetime qualifiers to the type that we're
4745   // referring to.
4746   TLB.TypeWasModifiedSafely(
4747       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
4748 
4749   // r-value references can be rebuilt as l-value references.
4750   ReferenceTypeLoc NewTL;
4751   if (isa<LValueReferenceType>(Result))
4752     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4753   else
4754     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4755   NewTL.setSigilLoc(TL.getSigilLoc());
4756 
4757   return Result;
4758 }
4759 
4760 template<typename Derived>
4761 QualType
4762 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4763                                                  LValueReferenceTypeLoc TL) {
4764   return TransformReferenceType(TLB, TL);
4765 }
4766 
4767 template<typename Derived>
4768 QualType
4769 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4770                                                  RValueReferenceTypeLoc TL) {
4771   return TransformReferenceType(TLB, TL);
4772 }
4773 
4774 template<typename Derived>
4775 QualType
4776 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4777                                                    MemberPointerTypeLoc TL) {
4778   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4779   if (PointeeType.isNull())
4780     return QualType();
4781 
4782   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4783   TypeSourceInfo *NewClsTInfo = nullptr;
4784   if (OldClsTInfo) {
4785     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4786     if (!NewClsTInfo)
4787       return QualType();
4788   }
4789 
4790   const MemberPointerType *T = TL.getTypePtr();
4791   QualType OldClsType = QualType(T->getClass(), 0);
4792   QualType NewClsType;
4793   if (NewClsTInfo)
4794     NewClsType = NewClsTInfo->getType();
4795   else {
4796     NewClsType = getDerived().TransformType(OldClsType);
4797     if (NewClsType.isNull())
4798       return QualType();
4799   }
4800 
4801   QualType Result = TL.getType();
4802   if (getDerived().AlwaysRebuild() ||
4803       PointeeType != T->getPointeeType() ||
4804       NewClsType != OldClsType) {
4805     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4806                                                    TL.getStarLoc());
4807     if (Result.isNull())
4808       return QualType();
4809   }
4810 
4811   // If we had to adjust the pointee type when building a member pointer, make
4812   // sure to push TypeLoc info for it.
4813   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4814   if (MPT && PointeeType != MPT->getPointeeType()) {
4815     assert(isa<AdjustedType>(MPT->getPointeeType()));
4816     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4817   }
4818 
4819   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4820   NewTL.setSigilLoc(TL.getSigilLoc());
4821   NewTL.setClassTInfo(NewClsTInfo);
4822 
4823   return Result;
4824 }
4825 
4826 template<typename Derived>
4827 QualType
4828 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4829                                                    ConstantArrayTypeLoc TL) {
4830   const ConstantArrayType *T = TL.getTypePtr();
4831   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4832   if (ElementType.isNull())
4833     return QualType();
4834 
4835   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4836   Expr *OldSize = TL.getSizeExpr();
4837   if (!OldSize)
4838     OldSize = const_cast<Expr*>(T->getSizeExpr());
4839   Expr *NewSize = nullptr;
4840   if (OldSize) {
4841     EnterExpressionEvaluationContext Unevaluated(
4842         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4843     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
4844     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
4845   }
4846 
4847   QualType Result = TL.getType();
4848   if (getDerived().AlwaysRebuild() ||
4849       ElementType != T->getElementType() ||
4850       (T->getSizeExpr() && NewSize != OldSize)) {
4851     Result = getDerived().RebuildConstantArrayType(ElementType,
4852                                                    T->getSizeModifier(),
4853                                                    T->getSize(), NewSize,
4854                                              T->getIndexTypeCVRQualifiers(),
4855                                                    TL.getBracketsRange());
4856     if (Result.isNull())
4857       return QualType();
4858   }
4859 
4860   // We might have either a ConstantArrayType or a VariableArrayType now:
4861   // a ConstantArrayType is allowed to have an element type which is a
4862   // VariableArrayType if the type is dependent.  Fortunately, all array
4863   // types have the same location layout.
4864   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4865   NewTL.setLBracketLoc(TL.getLBracketLoc());
4866   NewTL.setRBracketLoc(TL.getRBracketLoc());
4867   NewTL.setSizeExpr(NewSize);
4868 
4869   return Result;
4870 }
4871 
4872 template<typename Derived>
4873 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4874                                               TypeLocBuilder &TLB,
4875                                               IncompleteArrayTypeLoc TL) {
4876   const IncompleteArrayType *T = TL.getTypePtr();
4877   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4878   if (ElementType.isNull())
4879     return QualType();
4880 
4881   QualType Result = TL.getType();
4882   if (getDerived().AlwaysRebuild() ||
4883       ElementType != T->getElementType()) {
4884     Result = getDerived().RebuildIncompleteArrayType(ElementType,
4885                                                      T->getSizeModifier(),
4886                                            T->getIndexTypeCVRQualifiers(),
4887                                                      TL.getBracketsRange());
4888     if (Result.isNull())
4889       return QualType();
4890   }
4891 
4892   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4893   NewTL.setLBracketLoc(TL.getLBracketLoc());
4894   NewTL.setRBracketLoc(TL.getRBracketLoc());
4895   NewTL.setSizeExpr(nullptr);
4896 
4897   return Result;
4898 }
4899 
4900 template<typename Derived>
4901 QualType
4902 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4903                                                    VariableArrayTypeLoc TL) {
4904   const VariableArrayType *T = TL.getTypePtr();
4905   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4906   if (ElementType.isNull())
4907     return QualType();
4908 
4909   ExprResult SizeResult;
4910   {
4911     EnterExpressionEvaluationContext Context(
4912         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4913     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4914   }
4915   if (SizeResult.isInvalid())
4916     return QualType();
4917   SizeResult =
4918       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
4919   if (SizeResult.isInvalid())
4920     return QualType();
4921 
4922   Expr *Size = SizeResult.get();
4923 
4924   QualType Result = TL.getType();
4925   if (getDerived().AlwaysRebuild() ||
4926       ElementType != T->getElementType() ||
4927       Size != T->getSizeExpr()) {
4928     Result = getDerived().RebuildVariableArrayType(ElementType,
4929                                                    T->getSizeModifier(),
4930                                                    Size,
4931                                              T->getIndexTypeCVRQualifiers(),
4932                                                    TL.getBracketsRange());
4933     if (Result.isNull())
4934       return QualType();
4935   }
4936 
4937   // We might have constant size array now, but fortunately it has the same
4938   // location layout.
4939   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4940   NewTL.setLBracketLoc(TL.getLBracketLoc());
4941   NewTL.setRBracketLoc(TL.getRBracketLoc());
4942   NewTL.setSizeExpr(Size);
4943 
4944   return Result;
4945 }
4946 
4947 template<typename Derived>
4948 QualType
4949 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4950                                              DependentSizedArrayTypeLoc TL) {
4951   const DependentSizedArrayType *T = TL.getTypePtr();
4952   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4953   if (ElementType.isNull())
4954     return QualType();
4955 
4956   // Array bounds are constant expressions.
4957   EnterExpressionEvaluationContext Unevaluated(
4958       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4959 
4960   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4961   Expr *origSize = TL.getSizeExpr();
4962   if (!origSize) origSize = T->getSizeExpr();
4963 
4964   ExprResult sizeResult
4965     = getDerived().TransformExpr(origSize);
4966   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4967   if (sizeResult.isInvalid())
4968     return QualType();
4969 
4970   Expr *size = sizeResult.get();
4971 
4972   QualType Result = TL.getType();
4973   if (getDerived().AlwaysRebuild() ||
4974       ElementType != T->getElementType() ||
4975       size != origSize) {
4976     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4977                                                          T->getSizeModifier(),
4978                                                          size,
4979                                                 T->getIndexTypeCVRQualifiers(),
4980                                                         TL.getBracketsRange());
4981     if (Result.isNull())
4982       return QualType();
4983   }
4984 
4985   // We might have any sort of array type now, but fortunately they
4986   // all have the same location layout.
4987   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4988   NewTL.setLBracketLoc(TL.getLBracketLoc());
4989   NewTL.setRBracketLoc(TL.getRBracketLoc());
4990   NewTL.setSizeExpr(size);
4991 
4992   return Result;
4993 }
4994 
4995 template <typename Derived>
4996 QualType TreeTransform<Derived>::TransformDependentVectorType(
4997     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4998   const DependentVectorType *T = TL.getTypePtr();
4999   QualType ElementType = getDerived().TransformType(T->getElementType());
5000   if (ElementType.isNull())
5001     return QualType();
5002 
5003   EnterExpressionEvaluationContext Unevaluated(
5004       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5005 
5006   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5007   Size = SemaRef.ActOnConstantExpression(Size);
5008   if (Size.isInvalid())
5009     return QualType();
5010 
5011   QualType Result = TL.getType();
5012   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5013       Size.get() != T->getSizeExpr()) {
5014     Result = getDerived().RebuildDependentVectorType(
5015         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5016     if (Result.isNull())
5017       return QualType();
5018   }
5019 
5020   // Result might be dependent or not.
5021   if (isa<DependentVectorType>(Result)) {
5022     DependentVectorTypeLoc NewTL =
5023         TLB.push<DependentVectorTypeLoc>(Result);
5024     NewTL.setNameLoc(TL.getNameLoc());
5025   } else {
5026     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5027     NewTL.setNameLoc(TL.getNameLoc());
5028   }
5029 
5030   return Result;
5031 }
5032 
5033 template<typename Derived>
5034 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5035                                       TypeLocBuilder &TLB,
5036                                       DependentSizedExtVectorTypeLoc TL) {
5037   const DependentSizedExtVectorType *T = TL.getTypePtr();
5038 
5039   // FIXME: ext vector locs should be nested
5040   QualType ElementType = getDerived().TransformType(T->getElementType());
5041   if (ElementType.isNull())
5042     return QualType();
5043 
5044   // Vector sizes are constant expressions.
5045   EnterExpressionEvaluationContext Unevaluated(
5046       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5047 
5048   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5049   Size = SemaRef.ActOnConstantExpression(Size);
5050   if (Size.isInvalid())
5051     return QualType();
5052 
5053   QualType Result = TL.getType();
5054   if (getDerived().AlwaysRebuild() ||
5055       ElementType != T->getElementType() ||
5056       Size.get() != T->getSizeExpr()) {
5057     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5058                                                              Size.get(),
5059                                                          T->getAttributeLoc());
5060     if (Result.isNull())
5061       return QualType();
5062   }
5063 
5064   // Result might be dependent or not.
5065   if (isa<DependentSizedExtVectorType>(Result)) {
5066     DependentSizedExtVectorTypeLoc NewTL
5067       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5068     NewTL.setNameLoc(TL.getNameLoc());
5069   } else {
5070     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5071     NewTL.setNameLoc(TL.getNameLoc());
5072   }
5073 
5074   return Result;
5075 }
5076 
5077 template <typename Derived>
5078 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5079     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5080   const DependentAddressSpaceType *T = TL.getTypePtr();
5081 
5082   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5083 
5084   if (pointeeType.isNull())
5085     return QualType();
5086 
5087   // Address spaces are constant expressions.
5088   EnterExpressionEvaluationContext Unevaluated(
5089       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5090 
5091   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5092   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5093   if (AddrSpace.isInvalid())
5094     return QualType();
5095 
5096   QualType Result = TL.getType();
5097   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5098       AddrSpace.get() != T->getAddrSpaceExpr()) {
5099     Result = getDerived().RebuildDependentAddressSpaceType(
5100         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5101     if (Result.isNull())
5102       return QualType();
5103   }
5104 
5105   // Result might be dependent or not.
5106   if (isa<DependentAddressSpaceType>(Result)) {
5107     DependentAddressSpaceTypeLoc NewTL =
5108         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5109 
5110     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5111     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5112     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5113 
5114   } else {
5115     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5116         Result, getDerived().getBaseLocation());
5117     TransformType(TLB, DI->getTypeLoc());
5118   }
5119 
5120   return Result;
5121 }
5122 
5123 template <typename Derived>
5124 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5125                                                      VectorTypeLoc TL) {
5126   const VectorType *T = TL.getTypePtr();
5127   QualType ElementType = getDerived().TransformType(T->getElementType());
5128   if (ElementType.isNull())
5129     return QualType();
5130 
5131   QualType Result = TL.getType();
5132   if (getDerived().AlwaysRebuild() ||
5133       ElementType != T->getElementType()) {
5134     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5135                                             T->getVectorKind());
5136     if (Result.isNull())
5137       return QualType();
5138   }
5139 
5140   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5141   NewTL.setNameLoc(TL.getNameLoc());
5142 
5143   return Result;
5144 }
5145 
5146 template<typename Derived>
5147 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5148                                                         ExtVectorTypeLoc TL) {
5149   const VectorType *T = TL.getTypePtr();
5150   QualType ElementType = getDerived().TransformType(T->getElementType());
5151   if (ElementType.isNull())
5152     return QualType();
5153 
5154   QualType Result = TL.getType();
5155   if (getDerived().AlwaysRebuild() ||
5156       ElementType != T->getElementType()) {
5157     Result = getDerived().RebuildExtVectorType(ElementType,
5158                                                T->getNumElements(),
5159                                                /*FIXME*/ SourceLocation());
5160     if (Result.isNull())
5161       return QualType();
5162   }
5163 
5164   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5165   NewTL.setNameLoc(TL.getNameLoc());
5166 
5167   return Result;
5168 }
5169 
5170 template <typename Derived>
5171 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5172     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5173     bool ExpectParameterPack) {
5174   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5175   TypeSourceInfo *NewDI = nullptr;
5176 
5177   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5178     // If we're substituting into a pack expansion type and we know the
5179     // length we want to expand to, just substitute for the pattern.
5180     TypeLoc OldTL = OldDI->getTypeLoc();
5181     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5182 
5183     TypeLocBuilder TLB;
5184     TypeLoc NewTL = OldDI->getTypeLoc();
5185     TLB.reserve(NewTL.getFullDataSize());
5186 
5187     QualType Result = getDerived().TransformType(TLB,
5188                                                OldExpansionTL.getPatternLoc());
5189     if (Result.isNull())
5190       return nullptr;
5191 
5192     Result = RebuildPackExpansionType(Result,
5193                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5194                                       OldExpansionTL.getEllipsisLoc(),
5195                                       NumExpansions);
5196     if (Result.isNull())
5197       return nullptr;
5198 
5199     PackExpansionTypeLoc NewExpansionTL
5200       = TLB.push<PackExpansionTypeLoc>(Result);
5201     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5202     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5203   } else
5204     NewDI = getDerived().TransformType(OldDI);
5205   if (!NewDI)
5206     return nullptr;
5207 
5208   if (NewDI == OldDI && indexAdjustment == 0)
5209     return OldParm;
5210 
5211   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5212                                              OldParm->getDeclContext(),
5213                                              OldParm->getInnerLocStart(),
5214                                              OldParm->getLocation(),
5215                                              OldParm->getIdentifier(),
5216                                              NewDI->getType(),
5217                                              NewDI,
5218                                              OldParm->getStorageClass(),
5219                                              /* DefArg */ nullptr);
5220   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5221                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5222   return newParm;
5223 }
5224 
5225 template <typename Derived>
5226 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5227     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5228     const QualType *ParamTypes,
5229     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5230     SmallVectorImpl<QualType> &OutParamTypes,
5231     SmallVectorImpl<ParmVarDecl *> *PVars,
5232     Sema::ExtParameterInfoBuilder &PInfos) {
5233   int indexAdjustment = 0;
5234 
5235   unsigned NumParams = Params.size();
5236   for (unsigned i = 0; i != NumParams; ++i) {
5237     if (ParmVarDecl *OldParm = Params[i]) {
5238       assert(OldParm->getFunctionScopeIndex() == i);
5239 
5240       Optional<unsigned> NumExpansions;
5241       ParmVarDecl *NewParm = nullptr;
5242       if (OldParm->isParameterPack()) {
5243         // We have a function parameter pack that may need to be expanded.
5244         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5245 
5246         // Find the parameter packs that could be expanded.
5247         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5248         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5249         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5250         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5251 
5252         // Determine whether we should expand the parameter packs.
5253         bool ShouldExpand = false;
5254         bool RetainExpansion = false;
5255         Optional<unsigned> OrigNumExpansions;
5256         if (Unexpanded.size() > 0) {
5257           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5258           NumExpansions = OrigNumExpansions;
5259           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5260                                                    Pattern.getSourceRange(),
5261                                                    Unexpanded,
5262                                                    ShouldExpand,
5263                                                    RetainExpansion,
5264                                                    NumExpansions)) {
5265             return true;
5266           }
5267         } else {
5268 #ifndef NDEBUG
5269           const AutoType *AT =
5270               Pattern.getType().getTypePtr()->getContainedAutoType();
5271           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5272                  "Could not find parameter packs or undeduced auto type!");
5273 #endif
5274         }
5275 
5276         if (ShouldExpand) {
5277           // Expand the function parameter pack into multiple, separate
5278           // parameters.
5279           getDerived().ExpandingFunctionParameterPack(OldParm);
5280           for (unsigned I = 0; I != *NumExpansions; ++I) {
5281             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5282             ParmVarDecl *NewParm
5283               = getDerived().TransformFunctionTypeParam(OldParm,
5284                                                         indexAdjustment++,
5285                                                         OrigNumExpansions,
5286                                                 /*ExpectParameterPack=*/false);
5287             if (!NewParm)
5288               return true;
5289 
5290             if (ParamInfos)
5291               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5292             OutParamTypes.push_back(NewParm->getType());
5293             if (PVars)
5294               PVars->push_back(NewParm);
5295           }
5296 
5297           // If we're supposed to retain a pack expansion, do so by temporarily
5298           // forgetting the partially-substituted parameter pack.
5299           if (RetainExpansion) {
5300             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5301             ParmVarDecl *NewParm
5302               = getDerived().TransformFunctionTypeParam(OldParm,
5303                                                         indexAdjustment++,
5304                                                         OrigNumExpansions,
5305                                                 /*ExpectParameterPack=*/false);
5306             if (!NewParm)
5307               return true;
5308 
5309             if (ParamInfos)
5310               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5311             OutParamTypes.push_back(NewParm->getType());
5312             if (PVars)
5313               PVars->push_back(NewParm);
5314           }
5315 
5316           // The next parameter should have the same adjustment as the
5317           // last thing we pushed, but we post-incremented indexAdjustment
5318           // on every push.  Also, if we push nothing, the adjustment should
5319           // go down by one.
5320           indexAdjustment--;
5321 
5322           // We're done with the pack expansion.
5323           continue;
5324         }
5325 
5326         // We'll substitute the parameter now without expanding the pack
5327         // expansion.
5328         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5329         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5330                                                           indexAdjustment,
5331                                                           NumExpansions,
5332                                                   /*ExpectParameterPack=*/true);
5333         assert(NewParm->isParameterPack() &&
5334                "Parameter pack no longer a parameter pack after "
5335                "transformation.");
5336       } else {
5337         NewParm = getDerived().TransformFunctionTypeParam(
5338             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5339       }
5340 
5341       if (!NewParm)
5342         return true;
5343 
5344       if (ParamInfos)
5345         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5346       OutParamTypes.push_back(NewParm->getType());
5347       if (PVars)
5348         PVars->push_back(NewParm);
5349       continue;
5350     }
5351 
5352     // Deal with the possibility that we don't have a parameter
5353     // declaration for this parameter.
5354     QualType OldType = ParamTypes[i];
5355     bool IsPackExpansion = false;
5356     Optional<unsigned> NumExpansions;
5357     QualType NewType;
5358     if (const PackExpansionType *Expansion
5359                                        = dyn_cast<PackExpansionType>(OldType)) {
5360       // We have a function parameter pack that may need to be expanded.
5361       QualType Pattern = Expansion->getPattern();
5362       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5363       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5364 
5365       // Determine whether we should expand the parameter packs.
5366       bool ShouldExpand = false;
5367       bool RetainExpansion = false;
5368       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5369                                                Unexpanded,
5370                                                ShouldExpand,
5371                                                RetainExpansion,
5372                                                NumExpansions)) {
5373         return true;
5374       }
5375 
5376       if (ShouldExpand) {
5377         // Expand the function parameter pack into multiple, separate
5378         // parameters.
5379         for (unsigned I = 0; I != *NumExpansions; ++I) {
5380           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5381           QualType NewType = getDerived().TransformType(Pattern);
5382           if (NewType.isNull())
5383             return true;
5384 
5385           if (NewType->containsUnexpandedParameterPack()) {
5386             NewType =
5387                 getSema().getASTContext().getPackExpansionType(NewType, None);
5388 
5389             if (NewType.isNull())
5390               return true;
5391           }
5392 
5393           if (ParamInfos)
5394             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5395           OutParamTypes.push_back(NewType);
5396           if (PVars)
5397             PVars->push_back(nullptr);
5398         }
5399 
5400         // We're done with the pack expansion.
5401         continue;
5402       }
5403 
5404       // If we're supposed to retain a pack expansion, do so by temporarily
5405       // forgetting the partially-substituted parameter pack.
5406       if (RetainExpansion) {
5407         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5408         QualType NewType = getDerived().TransformType(Pattern);
5409         if (NewType.isNull())
5410           return true;
5411 
5412         if (ParamInfos)
5413           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5414         OutParamTypes.push_back(NewType);
5415         if (PVars)
5416           PVars->push_back(nullptr);
5417       }
5418 
5419       // We'll substitute the parameter now without expanding the pack
5420       // expansion.
5421       OldType = Expansion->getPattern();
5422       IsPackExpansion = true;
5423       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5424       NewType = getDerived().TransformType(OldType);
5425     } else {
5426       NewType = getDerived().TransformType(OldType);
5427     }
5428 
5429     if (NewType.isNull())
5430       return true;
5431 
5432     if (IsPackExpansion)
5433       NewType = getSema().Context.getPackExpansionType(NewType,
5434                                                        NumExpansions);
5435 
5436     if (ParamInfos)
5437       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5438     OutParamTypes.push_back(NewType);
5439     if (PVars)
5440       PVars->push_back(nullptr);
5441   }
5442 
5443 #ifndef NDEBUG
5444   if (PVars) {
5445     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5446       if (ParmVarDecl *parm = (*PVars)[i])
5447         assert(parm->getFunctionScopeIndex() == i);
5448   }
5449 #endif
5450 
5451   return false;
5452 }
5453 
5454 template<typename Derived>
5455 QualType
5456 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5457                                                    FunctionProtoTypeLoc TL) {
5458   SmallVector<QualType, 4> ExceptionStorage;
5459   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5460   return getDerived().TransformFunctionProtoType(
5461       TLB, TL, nullptr, Qualifiers(),
5462       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5463         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5464                                             ExceptionStorage, Changed);
5465       });
5466 }
5467 
5468 template<typename Derived> template<typename Fn>
5469 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5470     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5471     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5472 
5473   // Transform the parameters and return type.
5474   //
5475   // We are required to instantiate the params and return type in source order.
5476   // When the function has a trailing return type, we instantiate the
5477   // parameters before the return type,  since the return type can then refer
5478   // to the parameters themselves (via decltype, sizeof, etc.).
5479   //
5480   SmallVector<QualType, 4> ParamTypes;
5481   SmallVector<ParmVarDecl*, 4> ParamDecls;
5482   Sema::ExtParameterInfoBuilder ExtParamInfos;
5483   const FunctionProtoType *T = TL.getTypePtr();
5484 
5485   QualType ResultType;
5486 
5487   if (T->hasTrailingReturn()) {
5488     if (getDerived().TransformFunctionTypeParams(
5489             TL.getBeginLoc(), TL.getParams(),
5490             TL.getTypePtr()->param_type_begin(),
5491             T->getExtParameterInfosOrNull(),
5492             ParamTypes, &ParamDecls, ExtParamInfos))
5493       return QualType();
5494 
5495     {
5496       // C++11 [expr.prim.general]p3:
5497       //   If a declaration declares a member function or member function
5498       //   template of a class X, the expression this is a prvalue of type
5499       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5500       //   and the end of the function-definition, member-declarator, or
5501       //   declarator.
5502       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5503 
5504       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5505       if (ResultType.isNull())
5506         return QualType();
5507     }
5508   }
5509   else {
5510     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5511     if (ResultType.isNull())
5512       return QualType();
5513 
5514     if (getDerived().TransformFunctionTypeParams(
5515             TL.getBeginLoc(), TL.getParams(),
5516             TL.getTypePtr()->param_type_begin(),
5517             T->getExtParameterInfosOrNull(),
5518             ParamTypes, &ParamDecls, ExtParamInfos))
5519       return QualType();
5520   }
5521 
5522   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5523 
5524   bool EPIChanged = false;
5525   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5526     return QualType();
5527 
5528   // Handle extended parameter information.
5529   if (auto NewExtParamInfos =
5530         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5531     if (!EPI.ExtParameterInfos ||
5532         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5533           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5534       EPIChanged = true;
5535     }
5536     EPI.ExtParameterInfos = NewExtParamInfos;
5537   } else if (EPI.ExtParameterInfos) {
5538     EPIChanged = true;
5539     EPI.ExtParameterInfos = nullptr;
5540   }
5541 
5542   QualType Result = TL.getType();
5543   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5544       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5545     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5546     if (Result.isNull())
5547       return QualType();
5548   }
5549 
5550   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5551   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5552   NewTL.setLParenLoc(TL.getLParenLoc());
5553   NewTL.setRParenLoc(TL.getRParenLoc());
5554   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5555   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5556   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5557     NewTL.setParam(i, ParamDecls[i]);
5558 
5559   return Result;
5560 }
5561 
5562 template<typename Derived>
5563 bool TreeTransform<Derived>::TransformExceptionSpec(
5564     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5565     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5566   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5567 
5568   // Instantiate a dynamic noexcept expression, if any.
5569   if (isComputedNoexcept(ESI.Type)) {
5570     EnterExpressionEvaluationContext Unevaluated(
5571         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5572     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5573     if (NoexceptExpr.isInvalid())
5574       return true;
5575 
5576     ExceptionSpecificationType EST = ESI.Type;
5577     NoexceptExpr =
5578         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5579     if (NoexceptExpr.isInvalid())
5580       return true;
5581 
5582     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5583       Changed = true;
5584     ESI.NoexceptExpr = NoexceptExpr.get();
5585     ESI.Type = EST;
5586   }
5587 
5588   if (ESI.Type != EST_Dynamic)
5589     return false;
5590 
5591   // Instantiate a dynamic exception specification's type.
5592   for (QualType T : ESI.Exceptions) {
5593     if (const PackExpansionType *PackExpansion =
5594             T->getAs<PackExpansionType>()) {
5595       Changed = true;
5596 
5597       // We have a pack expansion. Instantiate it.
5598       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5599       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5600                                               Unexpanded);
5601       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5602 
5603       // Determine whether the set of unexpanded parameter packs can and
5604       // should
5605       // be expanded.
5606       bool Expand = false;
5607       bool RetainExpansion = false;
5608       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5609       // FIXME: Track the location of the ellipsis (and track source location
5610       // information for the types in the exception specification in general).
5611       if (getDerived().TryExpandParameterPacks(
5612               Loc, SourceRange(), Unexpanded, Expand,
5613               RetainExpansion, NumExpansions))
5614         return true;
5615 
5616       if (!Expand) {
5617         // We can't expand this pack expansion into separate arguments yet;
5618         // just substitute into the pattern and create a new pack expansion
5619         // type.
5620         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5621         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5622         if (U.isNull())
5623           return true;
5624 
5625         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5626         Exceptions.push_back(U);
5627         continue;
5628       }
5629 
5630       // Substitute into the pack expansion pattern for each slice of the
5631       // pack.
5632       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5633         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5634 
5635         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5636         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5637           return true;
5638 
5639         Exceptions.push_back(U);
5640       }
5641     } else {
5642       QualType U = getDerived().TransformType(T);
5643       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5644         return true;
5645       if (T != U)
5646         Changed = true;
5647 
5648       Exceptions.push_back(U);
5649     }
5650   }
5651 
5652   ESI.Exceptions = Exceptions;
5653   if (ESI.Exceptions.empty())
5654     ESI.Type = EST_DynamicNone;
5655   return false;
5656 }
5657 
5658 template<typename Derived>
5659 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5660                                                  TypeLocBuilder &TLB,
5661                                                  FunctionNoProtoTypeLoc TL) {
5662   const FunctionNoProtoType *T = TL.getTypePtr();
5663   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5664   if (ResultType.isNull())
5665     return QualType();
5666 
5667   QualType Result = TL.getType();
5668   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5669     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5670 
5671   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5672   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5673   NewTL.setLParenLoc(TL.getLParenLoc());
5674   NewTL.setRParenLoc(TL.getRParenLoc());
5675   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5676 
5677   return Result;
5678 }
5679 
5680 template<typename Derived> QualType
5681 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5682                                                  UnresolvedUsingTypeLoc TL) {
5683   const UnresolvedUsingType *T = TL.getTypePtr();
5684   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5685   if (!D)
5686     return QualType();
5687 
5688   QualType Result = TL.getType();
5689   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5690     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5691     if (Result.isNull())
5692       return QualType();
5693   }
5694 
5695   // We might get an arbitrary type spec type back.  We should at
5696   // least always get a type spec type, though.
5697   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5698   NewTL.setNameLoc(TL.getNameLoc());
5699 
5700   return Result;
5701 }
5702 
5703 template<typename Derived>
5704 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5705                                                       TypedefTypeLoc TL) {
5706   const TypedefType *T = TL.getTypePtr();
5707   TypedefNameDecl *Typedef
5708     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5709                                                                T->getDecl()));
5710   if (!Typedef)
5711     return QualType();
5712 
5713   QualType Result = TL.getType();
5714   if (getDerived().AlwaysRebuild() ||
5715       Typedef != T->getDecl()) {
5716     Result = getDerived().RebuildTypedefType(Typedef);
5717     if (Result.isNull())
5718       return QualType();
5719   }
5720 
5721   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5722   NewTL.setNameLoc(TL.getNameLoc());
5723 
5724   return Result;
5725 }
5726 
5727 template<typename Derived>
5728 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5729                                                       TypeOfExprTypeLoc TL) {
5730   // typeof expressions are not potentially evaluated contexts
5731   EnterExpressionEvaluationContext Unevaluated(
5732       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5733       Sema::ReuseLambdaContextDecl);
5734 
5735   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5736   if (E.isInvalid())
5737     return QualType();
5738 
5739   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5740   if (E.isInvalid())
5741     return QualType();
5742 
5743   QualType Result = TL.getType();
5744   if (getDerived().AlwaysRebuild() ||
5745       E.get() != TL.getUnderlyingExpr()) {
5746     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5747     if (Result.isNull())
5748       return QualType();
5749   }
5750   else E.get();
5751 
5752   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5753   NewTL.setTypeofLoc(TL.getTypeofLoc());
5754   NewTL.setLParenLoc(TL.getLParenLoc());
5755   NewTL.setRParenLoc(TL.getRParenLoc());
5756 
5757   return Result;
5758 }
5759 
5760 template<typename Derived>
5761 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5762                                                      TypeOfTypeLoc TL) {
5763   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5764   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5765   if (!New_Under_TI)
5766     return QualType();
5767 
5768   QualType Result = TL.getType();
5769   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5770     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5771     if (Result.isNull())
5772       return QualType();
5773   }
5774 
5775   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5776   NewTL.setTypeofLoc(TL.getTypeofLoc());
5777   NewTL.setLParenLoc(TL.getLParenLoc());
5778   NewTL.setRParenLoc(TL.getRParenLoc());
5779   NewTL.setUnderlyingTInfo(New_Under_TI);
5780 
5781   return Result;
5782 }
5783 
5784 template<typename Derived>
5785 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5786                                                        DecltypeTypeLoc TL) {
5787   const DecltypeType *T = TL.getTypePtr();
5788 
5789   // decltype expressions are not potentially evaluated contexts
5790   EnterExpressionEvaluationContext Unevaluated(
5791       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5792       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5793 
5794   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5795   if (E.isInvalid())
5796     return QualType();
5797 
5798   E = getSema().ActOnDecltypeExpression(E.get());
5799   if (E.isInvalid())
5800     return QualType();
5801 
5802   QualType Result = TL.getType();
5803   if (getDerived().AlwaysRebuild() ||
5804       E.get() != T->getUnderlyingExpr()) {
5805     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5806     if (Result.isNull())
5807       return QualType();
5808   }
5809   else E.get();
5810 
5811   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5812   NewTL.setNameLoc(TL.getNameLoc());
5813 
5814   return Result;
5815 }
5816 
5817 template<typename Derived>
5818 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5819                                                             TypeLocBuilder &TLB,
5820                                                      UnaryTransformTypeLoc TL) {
5821   QualType Result = TL.getType();
5822   if (Result->isDependentType()) {
5823     const UnaryTransformType *T = TL.getTypePtr();
5824     QualType NewBase =
5825       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5826     Result = getDerived().RebuildUnaryTransformType(NewBase,
5827                                                     T->getUTTKind(),
5828                                                     TL.getKWLoc());
5829     if (Result.isNull())
5830       return QualType();
5831   }
5832 
5833   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5834   NewTL.setKWLoc(TL.getKWLoc());
5835   NewTL.setParensRange(TL.getParensRange());
5836   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5837   return Result;
5838 }
5839 
5840 template<typename Derived>
5841 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5842     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5843   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5844 
5845   CXXScopeSpec SS;
5846   TemplateName TemplateName = getDerived().TransformTemplateName(
5847       SS, T->getTemplateName(), TL.getTemplateNameLoc());
5848   if (TemplateName.isNull())
5849     return QualType();
5850 
5851   QualType OldDeduced = T->getDeducedType();
5852   QualType NewDeduced;
5853   if (!OldDeduced.isNull()) {
5854     NewDeduced = getDerived().TransformType(OldDeduced);
5855     if (NewDeduced.isNull())
5856       return QualType();
5857   }
5858 
5859   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5860       TemplateName, NewDeduced);
5861   if (Result.isNull())
5862     return QualType();
5863 
5864   DeducedTemplateSpecializationTypeLoc NewTL =
5865       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5866   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5867 
5868   return Result;
5869 }
5870 
5871 template<typename Derived>
5872 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5873                                                      RecordTypeLoc TL) {
5874   const RecordType *T = TL.getTypePtr();
5875   RecordDecl *Record
5876     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5877                                                           T->getDecl()));
5878   if (!Record)
5879     return QualType();
5880 
5881   QualType Result = TL.getType();
5882   if (getDerived().AlwaysRebuild() ||
5883       Record != T->getDecl()) {
5884     Result = getDerived().RebuildRecordType(Record);
5885     if (Result.isNull())
5886       return QualType();
5887   }
5888 
5889   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5890   NewTL.setNameLoc(TL.getNameLoc());
5891 
5892   return Result;
5893 }
5894 
5895 template<typename Derived>
5896 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5897                                                    EnumTypeLoc TL) {
5898   const EnumType *T = TL.getTypePtr();
5899   EnumDecl *Enum
5900     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5901                                                         T->getDecl()));
5902   if (!Enum)
5903     return QualType();
5904 
5905   QualType Result = TL.getType();
5906   if (getDerived().AlwaysRebuild() ||
5907       Enum != T->getDecl()) {
5908     Result = getDerived().RebuildEnumType(Enum);
5909     if (Result.isNull())
5910       return QualType();
5911   }
5912 
5913   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5914   NewTL.setNameLoc(TL.getNameLoc());
5915 
5916   return Result;
5917 }
5918 
5919 template<typename Derived>
5920 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5921                                          TypeLocBuilder &TLB,
5922                                          InjectedClassNameTypeLoc TL) {
5923   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5924                                        TL.getTypePtr()->getDecl());
5925   if (!D) return QualType();
5926 
5927   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5928   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5929   return T;
5930 }
5931 
5932 template<typename Derived>
5933 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5934                                                 TypeLocBuilder &TLB,
5935                                                 TemplateTypeParmTypeLoc TL) {
5936   return TransformTypeSpecType(TLB, TL);
5937 }
5938 
5939 template<typename Derived>
5940 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5941                                          TypeLocBuilder &TLB,
5942                                          SubstTemplateTypeParmTypeLoc TL) {
5943   const SubstTemplateTypeParmType *T = TL.getTypePtr();
5944 
5945   // Substitute into the replacement type, which itself might involve something
5946   // that needs to be transformed. This only tends to occur with default
5947   // template arguments of template template parameters.
5948   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5949   QualType Replacement = getDerived().TransformType(T->getReplacementType());
5950   if (Replacement.isNull())
5951     return QualType();
5952 
5953   // Always canonicalize the replacement type.
5954   Replacement = SemaRef.Context.getCanonicalType(Replacement);
5955   QualType Result
5956     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5957                                                    Replacement);
5958 
5959   // Propagate type-source information.
5960   SubstTemplateTypeParmTypeLoc NewTL
5961     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5962   NewTL.setNameLoc(TL.getNameLoc());
5963   return Result;
5964 
5965 }
5966 
5967 template<typename Derived>
5968 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5969                                           TypeLocBuilder &TLB,
5970                                           SubstTemplateTypeParmPackTypeLoc TL) {
5971   return TransformTypeSpecType(TLB, TL);
5972 }
5973 
5974 template<typename Derived>
5975 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5976                                                         TypeLocBuilder &TLB,
5977                                            TemplateSpecializationTypeLoc TL) {
5978   const TemplateSpecializationType *T = TL.getTypePtr();
5979 
5980   // The nested-name-specifier never matters in a TemplateSpecializationType,
5981   // because we can't have a dependent nested-name-specifier anyway.
5982   CXXScopeSpec SS;
5983   TemplateName Template
5984     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5985                                          TL.getTemplateNameLoc());
5986   if (Template.isNull())
5987     return QualType();
5988 
5989   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5990 }
5991 
5992 template<typename Derived>
5993 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5994                                                      AtomicTypeLoc TL) {
5995   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5996   if (ValueType.isNull())
5997     return QualType();
5998 
5999   QualType Result = TL.getType();
6000   if (getDerived().AlwaysRebuild() ||
6001       ValueType != TL.getValueLoc().getType()) {
6002     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6003     if (Result.isNull())
6004       return QualType();
6005   }
6006 
6007   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6008   NewTL.setKWLoc(TL.getKWLoc());
6009   NewTL.setLParenLoc(TL.getLParenLoc());
6010   NewTL.setRParenLoc(TL.getRParenLoc());
6011 
6012   return Result;
6013 }
6014 
6015 template <typename Derived>
6016 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6017                                                    PipeTypeLoc TL) {
6018   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6019   if (ValueType.isNull())
6020     return QualType();
6021 
6022   QualType Result = TL.getType();
6023   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6024     const PipeType *PT = Result->castAs<PipeType>();
6025     bool isReadPipe = PT->isReadOnly();
6026     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6027     if (Result.isNull())
6028       return QualType();
6029   }
6030 
6031   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6032   NewTL.setKWLoc(TL.getKWLoc());
6033 
6034   return Result;
6035 }
6036 
6037   /// Simple iterator that traverses the template arguments in a
6038   /// container that provides a \c getArgLoc() member function.
6039   ///
6040   /// This iterator is intended to be used with the iterator form of
6041   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6042   template<typename ArgLocContainer>
6043   class TemplateArgumentLocContainerIterator {
6044     ArgLocContainer *Container;
6045     unsigned Index;
6046 
6047   public:
6048     typedef TemplateArgumentLoc value_type;
6049     typedef TemplateArgumentLoc reference;
6050     typedef int difference_type;
6051     typedef std::input_iterator_tag iterator_category;
6052 
6053     class pointer {
6054       TemplateArgumentLoc Arg;
6055 
6056     public:
6057       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6058 
6059       const TemplateArgumentLoc *operator->() const {
6060         return &Arg;
6061       }
6062     };
6063 
6064 
6065     TemplateArgumentLocContainerIterator() {}
6066 
6067     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6068                                  unsigned Index)
6069       : Container(&Container), Index(Index) { }
6070 
6071     TemplateArgumentLocContainerIterator &operator++() {
6072       ++Index;
6073       return *this;
6074     }
6075 
6076     TemplateArgumentLocContainerIterator operator++(int) {
6077       TemplateArgumentLocContainerIterator Old(*this);
6078       ++(*this);
6079       return Old;
6080     }
6081 
6082     TemplateArgumentLoc operator*() const {
6083       return Container->getArgLoc(Index);
6084     }
6085 
6086     pointer operator->() const {
6087       return pointer(Container->getArgLoc(Index));
6088     }
6089 
6090     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6091                            const TemplateArgumentLocContainerIterator &Y) {
6092       return X.Container == Y.Container && X.Index == Y.Index;
6093     }
6094 
6095     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6096                            const TemplateArgumentLocContainerIterator &Y) {
6097       return !(X == Y);
6098     }
6099   };
6100 
6101 template<typename Derived>
6102 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6103                                                    AutoTypeLoc TL) {
6104   const AutoType *T = TL.getTypePtr();
6105   QualType OldDeduced = T->getDeducedType();
6106   QualType NewDeduced;
6107   if (!OldDeduced.isNull()) {
6108     NewDeduced = getDerived().TransformType(OldDeduced);
6109     if (NewDeduced.isNull())
6110       return QualType();
6111   }
6112 
6113   ConceptDecl *NewCD = nullptr;
6114   TemplateArgumentListInfo NewTemplateArgs;
6115   NestedNameSpecifierLoc NewNestedNameSpec;
6116   if (TL.getTypePtr()->isConstrained()) {
6117     NewCD = cast_or_null<ConceptDecl>(
6118         getDerived().TransformDecl(
6119             TL.getConceptNameLoc(),
6120             TL.getTypePtr()->getTypeConstraintConcept()));
6121 
6122     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6123     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6124     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6125     if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6126                                                 ArgIterator(TL,
6127                                                             TL.getNumArgs()),
6128                                                 NewTemplateArgs))
6129       return QualType();
6130 
6131     if (TL.getNestedNameSpecifierLoc()) {
6132       NewNestedNameSpec
6133         = getDerived().TransformNestedNameSpecifierLoc(
6134             TL.getNestedNameSpecifierLoc());
6135       if (!NewNestedNameSpec)
6136         return QualType();
6137     }
6138   }
6139 
6140   QualType Result = TL.getType();
6141   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6142       T->isDependentType()) {
6143     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6144     NewArgList.reserve(NewArgList.size());
6145     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6146       NewArgList.push_back(ArgLoc.getArgument());
6147     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6148                                           NewArgList);
6149     if (Result.isNull())
6150       return QualType();
6151   }
6152 
6153   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6154   NewTL.setNameLoc(TL.getNameLoc());
6155   NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6156   NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6157   NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6158   NewTL.setFoundDecl(TL.getFoundDecl());
6159   NewTL.setLAngleLoc(TL.getLAngleLoc());
6160   NewTL.setRAngleLoc(TL.getRAngleLoc());
6161   for (unsigned I = 0; I < TL.getNumArgs(); ++I)
6162     NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6163 
6164   return Result;
6165 }
6166 
6167 template <typename Derived>
6168 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6169                                                         TypeLocBuilder &TLB,
6170                                            TemplateSpecializationTypeLoc TL,
6171                                                       TemplateName Template) {
6172   TemplateArgumentListInfo NewTemplateArgs;
6173   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6174   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6175   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6176     ArgIterator;
6177   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6178                                               ArgIterator(TL, TL.getNumArgs()),
6179                                               NewTemplateArgs))
6180     return QualType();
6181 
6182   // FIXME: maybe don't rebuild if all the template arguments are the same.
6183 
6184   QualType Result =
6185     getDerived().RebuildTemplateSpecializationType(Template,
6186                                                    TL.getTemplateNameLoc(),
6187                                                    NewTemplateArgs);
6188 
6189   if (!Result.isNull()) {
6190     // Specializations of template template parameters are represented as
6191     // TemplateSpecializationTypes, and substitution of type alias templates
6192     // within a dependent context can transform them into
6193     // DependentTemplateSpecializationTypes.
6194     if (isa<DependentTemplateSpecializationType>(Result)) {
6195       DependentTemplateSpecializationTypeLoc NewTL
6196         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6197       NewTL.setElaboratedKeywordLoc(SourceLocation());
6198       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6199       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6200       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6201       NewTL.setLAngleLoc(TL.getLAngleLoc());
6202       NewTL.setRAngleLoc(TL.getRAngleLoc());
6203       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6204         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6205       return Result;
6206     }
6207 
6208     TemplateSpecializationTypeLoc NewTL
6209       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6210     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6211     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6212     NewTL.setLAngleLoc(TL.getLAngleLoc());
6213     NewTL.setRAngleLoc(TL.getRAngleLoc());
6214     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6215       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6216   }
6217 
6218   return Result;
6219 }
6220 
6221 template <typename Derived>
6222 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6223                                      TypeLocBuilder &TLB,
6224                                      DependentTemplateSpecializationTypeLoc TL,
6225                                      TemplateName Template,
6226                                      CXXScopeSpec &SS) {
6227   TemplateArgumentListInfo NewTemplateArgs;
6228   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6229   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6230   typedef TemplateArgumentLocContainerIterator<
6231             DependentTemplateSpecializationTypeLoc> ArgIterator;
6232   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6233                                               ArgIterator(TL, TL.getNumArgs()),
6234                                               NewTemplateArgs))
6235     return QualType();
6236 
6237   // FIXME: maybe don't rebuild if all the template arguments are the same.
6238 
6239   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6240     QualType Result
6241       = getSema().Context.getDependentTemplateSpecializationType(
6242                                                 TL.getTypePtr()->getKeyword(),
6243                                                          DTN->getQualifier(),
6244                                                          DTN->getIdentifier(),
6245                                                                NewTemplateArgs);
6246 
6247     DependentTemplateSpecializationTypeLoc NewTL
6248       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6249     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6250     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6251     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6252     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6253     NewTL.setLAngleLoc(TL.getLAngleLoc());
6254     NewTL.setRAngleLoc(TL.getRAngleLoc());
6255     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6256       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6257     return Result;
6258   }
6259 
6260   QualType Result
6261     = getDerived().RebuildTemplateSpecializationType(Template,
6262                                                      TL.getTemplateNameLoc(),
6263                                                      NewTemplateArgs);
6264 
6265   if (!Result.isNull()) {
6266     /// FIXME: Wrap this in an elaborated-type-specifier?
6267     TemplateSpecializationTypeLoc NewTL
6268       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6269     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6270     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6271     NewTL.setLAngleLoc(TL.getLAngleLoc());
6272     NewTL.setRAngleLoc(TL.getRAngleLoc());
6273     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6274       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6275   }
6276 
6277   return Result;
6278 }
6279 
6280 template<typename Derived>
6281 QualType
6282 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6283                                                 ElaboratedTypeLoc TL) {
6284   const ElaboratedType *T = TL.getTypePtr();
6285 
6286   NestedNameSpecifierLoc QualifierLoc;
6287   // NOTE: the qualifier in an ElaboratedType is optional.
6288   if (TL.getQualifierLoc()) {
6289     QualifierLoc
6290       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6291     if (!QualifierLoc)
6292       return QualType();
6293   }
6294 
6295   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6296   if (NamedT.isNull())
6297     return QualType();
6298 
6299   // C++0x [dcl.type.elab]p2:
6300   //   If the identifier resolves to a typedef-name or the simple-template-id
6301   //   resolves to an alias template specialization, the
6302   //   elaborated-type-specifier is ill-formed.
6303   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6304     if (const TemplateSpecializationType *TST =
6305           NamedT->getAs<TemplateSpecializationType>()) {
6306       TemplateName Template = TST->getTemplateName();
6307       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6308               Template.getAsTemplateDecl())) {
6309         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6310                      diag::err_tag_reference_non_tag)
6311             << TAT << Sema::NTK_TypeAliasTemplate
6312             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6313         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6314       }
6315     }
6316   }
6317 
6318   QualType Result = TL.getType();
6319   if (getDerived().AlwaysRebuild() ||
6320       QualifierLoc != TL.getQualifierLoc() ||
6321       NamedT != T->getNamedType()) {
6322     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6323                                                 T->getKeyword(),
6324                                                 QualifierLoc, NamedT);
6325     if (Result.isNull())
6326       return QualType();
6327   }
6328 
6329   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6330   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6331   NewTL.setQualifierLoc(QualifierLoc);
6332   return Result;
6333 }
6334 
6335 template<typename Derived>
6336 QualType TreeTransform<Derived>::TransformAttributedType(
6337                                                 TypeLocBuilder &TLB,
6338                                                 AttributedTypeLoc TL) {
6339   const AttributedType *oldType = TL.getTypePtr();
6340   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6341   if (modifiedType.isNull())
6342     return QualType();
6343 
6344   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6345   const Attr *oldAttr = TL.getAttr();
6346   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6347   if (oldAttr && !newAttr)
6348     return QualType();
6349 
6350   QualType result = TL.getType();
6351 
6352   // FIXME: dependent operand expressions?
6353   if (getDerived().AlwaysRebuild() ||
6354       modifiedType != oldType->getModifiedType()) {
6355     // TODO: this is really lame; we should really be rebuilding the
6356     // equivalent type from first principles.
6357     QualType equivalentType
6358       = getDerived().TransformType(oldType->getEquivalentType());
6359     if (equivalentType.isNull())
6360       return QualType();
6361 
6362     // Check whether we can add nullability; it is only represented as
6363     // type sugar, and therefore cannot be diagnosed in any other way.
6364     if (auto nullability = oldType->getImmediateNullability()) {
6365       if (!modifiedType->canHaveNullability()) {
6366         SemaRef.Diag(TL.getAttr()->getLocation(),
6367                      diag::err_nullability_nonpointer)
6368             << DiagNullabilityKind(*nullability, false) << modifiedType;
6369         return QualType();
6370       }
6371     }
6372 
6373     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6374                                                modifiedType,
6375                                                equivalentType);
6376   }
6377 
6378   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6379   newTL.setAttr(newAttr);
6380   return result;
6381 }
6382 
6383 template<typename Derived>
6384 QualType
6385 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6386                                            ParenTypeLoc TL) {
6387   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6388   if (Inner.isNull())
6389     return QualType();
6390 
6391   QualType Result = TL.getType();
6392   if (getDerived().AlwaysRebuild() ||
6393       Inner != TL.getInnerLoc().getType()) {
6394     Result = getDerived().RebuildParenType(Inner);
6395     if (Result.isNull())
6396       return QualType();
6397   }
6398 
6399   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6400   NewTL.setLParenLoc(TL.getLParenLoc());
6401   NewTL.setRParenLoc(TL.getRParenLoc());
6402   return Result;
6403 }
6404 
6405 template <typename Derived>
6406 QualType
6407 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6408                                                     MacroQualifiedTypeLoc TL) {
6409   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6410   if (Inner.isNull())
6411     return QualType();
6412 
6413   QualType Result = TL.getType();
6414   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6415     Result =
6416         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6417     if (Result.isNull())
6418       return QualType();
6419   }
6420 
6421   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6422   NewTL.setExpansionLoc(TL.getExpansionLoc());
6423   return Result;
6424 }
6425 
6426 template<typename Derived>
6427 QualType TreeTransform<Derived>::TransformDependentNameType(
6428     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6429   return TransformDependentNameType(TLB, TL, false);
6430 }
6431 
6432 template<typename Derived>
6433 QualType TreeTransform<Derived>::TransformDependentNameType(
6434     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6435   const DependentNameType *T = TL.getTypePtr();
6436 
6437   NestedNameSpecifierLoc QualifierLoc
6438     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6439   if (!QualifierLoc)
6440     return QualType();
6441 
6442   QualType Result
6443     = getDerived().RebuildDependentNameType(T->getKeyword(),
6444                                             TL.getElaboratedKeywordLoc(),
6445                                             QualifierLoc,
6446                                             T->getIdentifier(),
6447                                             TL.getNameLoc(),
6448                                             DeducedTSTContext);
6449   if (Result.isNull())
6450     return QualType();
6451 
6452   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6453     QualType NamedT = ElabT->getNamedType();
6454     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6455 
6456     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6457     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6458     NewTL.setQualifierLoc(QualifierLoc);
6459   } else {
6460     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6461     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6462     NewTL.setQualifierLoc(QualifierLoc);
6463     NewTL.setNameLoc(TL.getNameLoc());
6464   }
6465   return Result;
6466 }
6467 
6468 template<typename Derived>
6469 QualType TreeTransform<Derived>::
6470           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6471                                  DependentTemplateSpecializationTypeLoc TL) {
6472   NestedNameSpecifierLoc QualifierLoc;
6473   if (TL.getQualifierLoc()) {
6474     QualifierLoc
6475       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6476     if (!QualifierLoc)
6477       return QualType();
6478   }
6479 
6480   return getDerived()
6481            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6482 }
6483 
6484 template<typename Derived>
6485 QualType TreeTransform<Derived>::
6486 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6487                                    DependentTemplateSpecializationTypeLoc TL,
6488                                        NestedNameSpecifierLoc QualifierLoc) {
6489   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6490 
6491   TemplateArgumentListInfo NewTemplateArgs;
6492   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6493   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6494 
6495   typedef TemplateArgumentLocContainerIterator<
6496   DependentTemplateSpecializationTypeLoc> ArgIterator;
6497   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6498                                               ArgIterator(TL, TL.getNumArgs()),
6499                                               NewTemplateArgs))
6500     return QualType();
6501 
6502   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6503       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6504       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6505       /*AllowInjectedClassName*/ false);
6506   if (Result.isNull())
6507     return QualType();
6508 
6509   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6510     QualType NamedT = ElabT->getNamedType();
6511 
6512     // Copy information relevant to the template specialization.
6513     TemplateSpecializationTypeLoc NamedTL
6514       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6515     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6516     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6517     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6518     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6519     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6520       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6521 
6522     // Copy information relevant to the elaborated type.
6523     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6524     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6525     NewTL.setQualifierLoc(QualifierLoc);
6526   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6527     DependentTemplateSpecializationTypeLoc SpecTL
6528       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6529     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6530     SpecTL.setQualifierLoc(QualifierLoc);
6531     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6532     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6533     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6534     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6535     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6536       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6537   } else {
6538     TemplateSpecializationTypeLoc SpecTL
6539       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6540     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6541     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6542     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6543     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6544     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6545       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6546   }
6547   return Result;
6548 }
6549 
6550 template<typename Derived>
6551 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6552                                                       PackExpansionTypeLoc TL) {
6553   QualType Pattern
6554     = getDerived().TransformType(TLB, TL.getPatternLoc());
6555   if (Pattern.isNull())
6556     return QualType();
6557 
6558   QualType Result = TL.getType();
6559   if (getDerived().AlwaysRebuild() ||
6560       Pattern != TL.getPatternLoc().getType()) {
6561     Result = getDerived().RebuildPackExpansionType(Pattern,
6562                                            TL.getPatternLoc().getSourceRange(),
6563                                                    TL.getEllipsisLoc(),
6564                                            TL.getTypePtr()->getNumExpansions());
6565     if (Result.isNull())
6566       return QualType();
6567   }
6568 
6569   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6570   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6571   return Result;
6572 }
6573 
6574 template<typename Derived>
6575 QualType
6576 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6577                                                    ObjCInterfaceTypeLoc TL) {
6578   // ObjCInterfaceType is never dependent.
6579   TLB.pushFullCopy(TL);
6580   return TL.getType();
6581 }
6582 
6583 template<typename Derived>
6584 QualType
6585 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6586                                                    ObjCTypeParamTypeLoc TL) {
6587   const ObjCTypeParamType *T = TL.getTypePtr();
6588   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6589       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6590   if (!OTP)
6591     return QualType();
6592 
6593   QualType Result = TL.getType();
6594   if (getDerived().AlwaysRebuild() ||
6595       OTP != T->getDecl()) {
6596     Result = getDerived().RebuildObjCTypeParamType(OTP,
6597                  TL.getProtocolLAngleLoc(),
6598                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6599                                     TL.getNumProtocols()),
6600                  TL.getProtocolLocs(),
6601                  TL.getProtocolRAngleLoc());
6602     if (Result.isNull())
6603       return QualType();
6604   }
6605 
6606   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6607   if (TL.getNumProtocols()) {
6608     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6609     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6610       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6611     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6612   }
6613   return Result;
6614 }
6615 
6616 template<typename Derived>
6617 QualType
6618 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6619                                                 ObjCObjectTypeLoc TL) {
6620   // Transform base type.
6621   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6622   if (BaseType.isNull())
6623     return QualType();
6624 
6625   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6626 
6627   // Transform type arguments.
6628   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6629   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6630     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6631     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6632     QualType TypeArg = TypeArgInfo->getType();
6633     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6634       AnyChanged = true;
6635 
6636       // We have a pack expansion. Instantiate it.
6637       const auto *PackExpansion = PackExpansionLoc.getType()
6638                                     ->castAs<PackExpansionType>();
6639       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6640       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6641                                               Unexpanded);
6642       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6643 
6644       // Determine whether the set of unexpanded parameter packs can
6645       // and should be expanded.
6646       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6647       bool Expand = false;
6648       bool RetainExpansion = false;
6649       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6650       if (getDerived().TryExpandParameterPacks(
6651             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6652             Unexpanded, Expand, RetainExpansion, NumExpansions))
6653         return QualType();
6654 
6655       if (!Expand) {
6656         // We can't expand this pack expansion into separate arguments yet;
6657         // just substitute into the pattern and create a new pack expansion
6658         // type.
6659         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6660 
6661         TypeLocBuilder TypeArgBuilder;
6662         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6663         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6664                                                              PatternLoc);
6665         if (NewPatternType.isNull())
6666           return QualType();
6667 
6668         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6669                                       NewPatternType, NumExpansions);
6670         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6671         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6672         NewTypeArgInfos.push_back(
6673           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6674         continue;
6675       }
6676 
6677       // Substitute into the pack expansion pattern for each slice of the
6678       // pack.
6679       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6680         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6681 
6682         TypeLocBuilder TypeArgBuilder;
6683         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6684 
6685         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6686                                                          PatternLoc);
6687         if (NewTypeArg.isNull())
6688           return QualType();
6689 
6690         NewTypeArgInfos.push_back(
6691           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6692       }
6693 
6694       continue;
6695     }
6696 
6697     TypeLocBuilder TypeArgBuilder;
6698     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6699     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6700     if (NewTypeArg.isNull())
6701       return QualType();
6702 
6703     // If nothing changed, just keep the old TypeSourceInfo.
6704     if (NewTypeArg == TypeArg) {
6705       NewTypeArgInfos.push_back(TypeArgInfo);
6706       continue;
6707     }
6708 
6709     NewTypeArgInfos.push_back(
6710       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6711     AnyChanged = true;
6712   }
6713 
6714   QualType Result = TL.getType();
6715   if (getDerived().AlwaysRebuild() || AnyChanged) {
6716     // Rebuild the type.
6717     Result = getDerived().RebuildObjCObjectType(
6718         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6719         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6720         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6721         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6722 
6723     if (Result.isNull())
6724       return QualType();
6725   }
6726 
6727   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6728   NewT.setHasBaseTypeAsWritten(true);
6729   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6730   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6731     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6732   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6733   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6734   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6735     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6736   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6737   return Result;
6738 }
6739 
6740 template<typename Derived>
6741 QualType
6742 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6743                                                ObjCObjectPointerTypeLoc TL) {
6744   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6745   if (PointeeType.isNull())
6746     return QualType();
6747 
6748   QualType Result = TL.getType();
6749   if (getDerived().AlwaysRebuild() ||
6750       PointeeType != TL.getPointeeLoc().getType()) {
6751     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6752                                                        TL.getStarLoc());
6753     if (Result.isNull())
6754       return QualType();
6755   }
6756 
6757   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6758   NewT.setStarLoc(TL.getStarLoc());
6759   return Result;
6760 }
6761 
6762 //===----------------------------------------------------------------------===//
6763 // Statement transformation
6764 //===----------------------------------------------------------------------===//
6765 template<typename Derived>
6766 StmtResult
6767 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6768   return S;
6769 }
6770 
6771 template<typename Derived>
6772 StmtResult
6773 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6774   return getDerived().TransformCompoundStmt(S, false);
6775 }
6776 
6777 template<typename Derived>
6778 StmtResult
6779 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6780                                               bool IsStmtExpr) {
6781   Sema::CompoundScopeRAII CompoundScope(getSema());
6782 
6783   const Stmt *ExprResult = S->getStmtExprResult();
6784   bool SubStmtInvalid = false;
6785   bool SubStmtChanged = false;
6786   SmallVector<Stmt*, 8> Statements;
6787   for (auto *B : S->body()) {
6788     StmtResult Result = getDerived().TransformStmt(
6789         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
6790 
6791     if (Result.isInvalid()) {
6792       // Immediately fail if this was a DeclStmt, since it's very
6793       // likely that this will cause problems for future statements.
6794       if (isa<DeclStmt>(B))
6795         return StmtError();
6796 
6797       // Otherwise, just keep processing substatements and fail later.
6798       SubStmtInvalid = true;
6799       continue;
6800     }
6801 
6802     SubStmtChanged = SubStmtChanged || Result.get() != B;
6803     Statements.push_back(Result.getAs<Stmt>());
6804   }
6805 
6806   if (SubStmtInvalid)
6807     return StmtError();
6808 
6809   if (!getDerived().AlwaysRebuild() &&
6810       !SubStmtChanged)
6811     return S;
6812 
6813   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6814                                           Statements,
6815                                           S->getRBracLoc(),
6816                                           IsStmtExpr);
6817 }
6818 
6819 template<typename Derived>
6820 StmtResult
6821 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6822   ExprResult LHS, RHS;
6823   {
6824     EnterExpressionEvaluationContext Unevaluated(
6825         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6826 
6827     // Transform the left-hand case value.
6828     LHS = getDerived().TransformExpr(S->getLHS());
6829     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6830     if (LHS.isInvalid())
6831       return StmtError();
6832 
6833     // Transform the right-hand case value (for the GNU case-range extension).
6834     RHS = getDerived().TransformExpr(S->getRHS());
6835     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6836     if (RHS.isInvalid())
6837       return StmtError();
6838   }
6839 
6840   // Build the case statement.
6841   // Case statements are always rebuilt so that they will attached to their
6842   // transformed switch statement.
6843   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6844                                                        LHS.get(),
6845                                                        S->getEllipsisLoc(),
6846                                                        RHS.get(),
6847                                                        S->getColonLoc());
6848   if (Case.isInvalid())
6849     return StmtError();
6850 
6851   // Transform the statement following the case
6852   StmtResult SubStmt =
6853       getDerived().TransformStmt(S->getSubStmt());
6854   if (SubStmt.isInvalid())
6855     return StmtError();
6856 
6857   // Attach the body to the case statement
6858   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6859 }
6860 
6861 template <typename Derived>
6862 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6863   // Transform the statement following the default case
6864   StmtResult SubStmt =
6865       getDerived().TransformStmt(S->getSubStmt());
6866   if (SubStmt.isInvalid())
6867     return StmtError();
6868 
6869   // Default statements are always rebuilt
6870   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6871                                          SubStmt.get());
6872 }
6873 
6874 template<typename Derived>
6875 StmtResult
6876 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
6877   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6878   if (SubStmt.isInvalid())
6879     return StmtError();
6880 
6881   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6882                                         S->getDecl());
6883   if (!LD)
6884     return StmtError();
6885 
6886   // If we're transforming "in-place" (we're not creating new local
6887   // declarations), assume we're replacing the old label statement
6888   // and clear out the reference to it.
6889   if (LD == S->getDecl())
6890     S->getDecl()->setStmt(nullptr);
6891 
6892   // FIXME: Pass the real colon location in.
6893   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6894                                        cast<LabelDecl>(LD), SourceLocation(),
6895                                        SubStmt.get());
6896 }
6897 
6898 template <typename Derived>
6899 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6900   if (!R)
6901     return R;
6902 
6903   switch (R->getKind()) {
6904 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6905 #define ATTR(X)
6906 #define PRAGMA_SPELLING_ATTR(X)                                                \
6907   case attr::X:                                                                \
6908     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6909 #include "clang/Basic/AttrList.inc"
6910   default:
6911     return R;
6912   }
6913 }
6914 
6915 template <typename Derived>
6916 StmtResult
6917 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
6918                                                 StmtDiscardKind SDK) {
6919   bool AttrsChanged = false;
6920   SmallVector<const Attr *, 1> Attrs;
6921 
6922   // Visit attributes and keep track if any are transformed.
6923   for (const auto *I : S->getAttrs()) {
6924     const Attr *R = getDerived().TransformAttr(I);
6925     AttrsChanged |= (I != R);
6926     Attrs.push_back(R);
6927   }
6928 
6929   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6930   if (SubStmt.isInvalid())
6931     return StmtError();
6932 
6933   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6934     return S;
6935 
6936   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6937                                             SubStmt.get());
6938 }
6939 
6940 template<typename Derived>
6941 StmtResult
6942 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6943   // Transform the initialization statement
6944   StmtResult Init = getDerived().TransformStmt(S->getInit());
6945   if (Init.isInvalid())
6946     return StmtError();
6947 
6948   // Transform the condition
6949   Sema::ConditionResult Cond = getDerived().TransformCondition(
6950       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6951       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6952                        : Sema::ConditionKind::Boolean);
6953   if (Cond.isInvalid())
6954     return StmtError();
6955 
6956   // If this is a constexpr if, determine which arm we should instantiate.
6957   llvm::Optional<bool> ConstexprConditionValue;
6958   if (S->isConstexpr())
6959     ConstexprConditionValue = Cond.getKnownValue();
6960 
6961   // Transform the "then" branch.
6962   StmtResult Then;
6963   if (!ConstexprConditionValue || *ConstexprConditionValue) {
6964     Then = getDerived().TransformStmt(S->getThen());
6965     if (Then.isInvalid())
6966       return StmtError();
6967   } else {
6968     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6969   }
6970 
6971   // Transform the "else" branch.
6972   StmtResult Else;
6973   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6974     Else = getDerived().TransformStmt(S->getElse());
6975     if (Else.isInvalid())
6976       return StmtError();
6977   }
6978 
6979   if (!getDerived().AlwaysRebuild() &&
6980       Init.get() == S->getInit() &&
6981       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6982       Then.get() == S->getThen() &&
6983       Else.get() == S->getElse())
6984     return S;
6985 
6986   return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6987                                     Init.get(), Then.get(), S->getElseLoc(),
6988                                     Else.get());
6989 }
6990 
6991 template<typename Derived>
6992 StmtResult
6993 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6994   // Transform the initialization statement
6995   StmtResult Init = getDerived().TransformStmt(S->getInit());
6996   if (Init.isInvalid())
6997     return StmtError();
6998 
6999   // Transform the condition.
7000   Sema::ConditionResult Cond = getDerived().TransformCondition(
7001       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7002       Sema::ConditionKind::Switch);
7003   if (Cond.isInvalid())
7004     return StmtError();
7005 
7006   // Rebuild the switch statement.
7007   StmtResult Switch
7008     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
7009   if (Switch.isInvalid())
7010     return StmtError();
7011 
7012   // Transform the body of the switch statement.
7013   StmtResult Body = getDerived().TransformStmt(S->getBody());
7014   if (Body.isInvalid())
7015     return StmtError();
7016 
7017   // Complete the switch statement.
7018   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7019                                             Body.get());
7020 }
7021 
7022 template<typename Derived>
7023 StmtResult
7024 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7025   // Transform the condition
7026   Sema::ConditionResult Cond = getDerived().TransformCondition(
7027       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7028       Sema::ConditionKind::Boolean);
7029   if (Cond.isInvalid())
7030     return StmtError();
7031 
7032   // Transform the body
7033   StmtResult Body = getDerived().TransformStmt(S->getBody());
7034   if (Body.isInvalid())
7035     return StmtError();
7036 
7037   if (!getDerived().AlwaysRebuild() &&
7038       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7039       Body.get() == S->getBody())
7040     return Owned(S);
7041 
7042   return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
7043 }
7044 
7045 template<typename Derived>
7046 StmtResult
7047 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7048   // Transform the body
7049   StmtResult Body = getDerived().TransformStmt(S->getBody());
7050   if (Body.isInvalid())
7051     return StmtError();
7052 
7053   // Transform the condition
7054   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7055   if (Cond.isInvalid())
7056     return StmtError();
7057 
7058   if (!getDerived().AlwaysRebuild() &&
7059       Cond.get() == S->getCond() &&
7060       Body.get() == S->getBody())
7061     return S;
7062 
7063   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7064                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7065                                     S->getRParenLoc());
7066 }
7067 
7068 template<typename Derived>
7069 StmtResult
7070 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7071   if (getSema().getLangOpts().OpenMP)
7072     getSema().startOpenMPLoop();
7073 
7074   // Transform the initialization statement
7075   StmtResult Init = getDerived().TransformStmt(S->getInit());
7076   if (Init.isInvalid())
7077     return StmtError();
7078 
7079   // In OpenMP loop region loop control variable must be captured and be
7080   // private. Perform analysis of first part (if any).
7081   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7082     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7083 
7084   // Transform the condition
7085   Sema::ConditionResult Cond = getDerived().TransformCondition(
7086       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7087       Sema::ConditionKind::Boolean);
7088   if (Cond.isInvalid())
7089     return StmtError();
7090 
7091   // Transform the increment
7092   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7093   if (Inc.isInvalid())
7094     return StmtError();
7095 
7096   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7097   if (S->getInc() && !FullInc.get())
7098     return StmtError();
7099 
7100   // Transform the body
7101   StmtResult Body = getDerived().TransformStmt(S->getBody());
7102   if (Body.isInvalid())
7103     return StmtError();
7104 
7105   if (!getDerived().AlwaysRebuild() &&
7106       Init.get() == S->getInit() &&
7107       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7108       Inc.get() == S->getInc() &&
7109       Body.get() == S->getBody())
7110     return S;
7111 
7112   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7113                                      Init.get(), Cond, FullInc,
7114                                      S->getRParenLoc(), Body.get());
7115 }
7116 
7117 template<typename Derived>
7118 StmtResult
7119 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7120   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7121                                         S->getLabel());
7122   if (!LD)
7123     return StmtError();
7124 
7125   // Goto statements must always be rebuilt, to resolve the label.
7126   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7127                                       cast<LabelDecl>(LD));
7128 }
7129 
7130 template<typename Derived>
7131 StmtResult
7132 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7133   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7134   if (Target.isInvalid())
7135     return StmtError();
7136   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7137 
7138   if (!getDerived().AlwaysRebuild() &&
7139       Target.get() == S->getTarget())
7140     return S;
7141 
7142   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7143                                               Target.get());
7144 }
7145 
7146 template<typename Derived>
7147 StmtResult
7148 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7149   return S;
7150 }
7151 
7152 template<typename Derived>
7153 StmtResult
7154 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7155   return S;
7156 }
7157 
7158 template<typename Derived>
7159 StmtResult
7160 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7161   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7162                                                         /*NotCopyInit*/false);
7163   if (Result.isInvalid())
7164     return StmtError();
7165 
7166   // FIXME: We always rebuild the return statement because there is no way
7167   // to tell whether the return type of the function has changed.
7168   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7169 }
7170 
7171 template<typename Derived>
7172 StmtResult
7173 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7174   bool DeclChanged = false;
7175   SmallVector<Decl *, 4> Decls;
7176   for (auto *D : S->decls()) {
7177     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7178     if (!Transformed)
7179       return StmtError();
7180 
7181     if (Transformed != D)
7182       DeclChanged = true;
7183 
7184     Decls.push_back(Transformed);
7185   }
7186 
7187   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7188     return S;
7189 
7190   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7191 }
7192 
7193 template<typename Derived>
7194 StmtResult
7195 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7196 
7197   SmallVector<Expr*, 8> Constraints;
7198   SmallVector<Expr*, 8> Exprs;
7199   SmallVector<IdentifierInfo *, 4> Names;
7200 
7201   ExprResult AsmString;
7202   SmallVector<Expr*, 8> Clobbers;
7203 
7204   bool ExprsChanged = false;
7205 
7206   // Go through the outputs.
7207   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7208     Names.push_back(S->getOutputIdentifier(I));
7209 
7210     // No need to transform the constraint literal.
7211     Constraints.push_back(S->getOutputConstraintLiteral(I));
7212 
7213     // Transform the output expr.
7214     Expr *OutputExpr = S->getOutputExpr(I);
7215     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7216     if (Result.isInvalid())
7217       return StmtError();
7218 
7219     ExprsChanged |= Result.get() != OutputExpr;
7220 
7221     Exprs.push_back(Result.get());
7222   }
7223 
7224   // Go through the inputs.
7225   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7226     Names.push_back(S->getInputIdentifier(I));
7227 
7228     // No need to transform the constraint literal.
7229     Constraints.push_back(S->getInputConstraintLiteral(I));
7230 
7231     // Transform the input expr.
7232     Expr *InputExpr = S->getInputExpr(I);
7233     ExprResult Result = getDerived().TransformExpr(InputExpr);
7234     if (Result.isInvalid())
7235       return StmtError();
7236 
7237     ExprsChanged |= Result.get() != InputExpr;
7238 
7239     Exprs.push_back(Result.get());
7240   }
7241 
7242   // Go through the Labels.
7243   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7244     Names.push_back(S->getLabelIdentifier(I));
7245 
7246     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7247     if (Result.isInvalid())
7248       return StmtError();
7249     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7250     Exprs.push_back(Result.get());
7251   }
7252   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7253     return S;
7254 
7255   // Go through the clobbers.
7256   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7257     Clobbers.push_back(S->getClobberStringLiteral(I));
7258 
7259   // No need to transform the asm string literal.
7260   AsmString = S->getAsmString();
7261   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7262                                         S->isVolatile(), S->getNumOutputs(),
7263                                         S->getNumInputs(), Names.data(),
7264                                         Constraints, Exprs, AsmString.get(),
7265                                         Clobbers, S->getNumLabels(),
7266                                         S->getRParenLoc());
7267 }
7268 
7269 template<typename Derived>
7270 StmtResult
7271 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7272   ArrayRef<Token> AsmToks =
7273     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7274 
7275   bool HadError = false, HadChange = false;
7276 
7277   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7278   SmallVector<Expr*, 8> TransformedExprs;
7279   TransformedExprs.reserve(SrcExprs.size());
7280   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7281     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7282     if (!Result.isUsable()) {
7283       HadError = true;
7284     } else {
7285       HadChange |= (Result.get() != SrcExprs[i]);
7286       TransformedExprs.push_back(Result.get());
7287     }
7288   }
7289 
7290   if (HadError) return StmtError();
7291   if (!HadChange && !getDerived().AlwaysRebuild())
7292     return Owned(S);
7293 
7294   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7295                                        AsmToks, S->getAsmString(),
7296                                        S->getNumOutputs(), S->getNumInputs(),
7297                                        S->getAllConstraints(), S->getClobbers(),
7298                                        TransformedExprs, S->getEndLoc());
7299 }
7300 
7301 // C++ Coroutines TS
7302 
7303 template<typename Derived>
7304 StmtResult
7305 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7306   auto *ScopeInfo = SemaRef.getCurFunction();
7307   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7308   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7309          ScopeInfo->NeedsCoroutineSuspends &&
7310          ScopeInfo->CoroutineSuspends.first == nullptr &&
7311          ScopeInfo->CoroutineSuspends.second == nullptr &&
7312          "expected clean scope info");
7313 
7314   // Set that we have (possibly-invalid) suspend points before we do anything
7315   // that may fail.
7316   ScopeInfo->setNeedsCoroutineSuspends(false);
7317 
7318   // We re-build the coroutine promise object (and the coroutine parameters its
7319   // type and constructor depend on) based on the types used in our current
7320   // function. We must do so, and set it on the current FunctionScopeInfo,
7321   // before attempting to transform the other parts of the coroutine body
7322   // statement, such as the implicit suspend statements (because those
7323   // statements reference the FunctionScopeInfo::CoroutinePromise).
7324   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7325     return StmtError();
7326   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7327   if (!Promise)
7328     return StmtError();
7329   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7330   ScopeInfo->CoroutinePromise = Promise;
7331 
7332   // Transform the implicit coroutine statements constructed using dependent
7333   // types during the previous parse: initial and final suspensions, the return
7334   // object, and others. We also transform the coroutine function's body.
7335   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7336   if (InitSuspend.isInvalid())
7337     return StmtError();
7338   StmtResult FinalSuspend =
7339       getDerived().TransformStmt(S->getFinalSuspendStmt());
7340   if (FinalSuspend.isInvalid())
7341     return StmtError();
7342   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7343   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7344 
7345   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7346   if (BodyRes.isInvalid())
7347     return StmtError();
7348 
7349   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7350   if (Builder.isInvalid())
7351     return StmtError();
7352 
7353   Expr *ReturnObject = S->getReturnValueInit();
7354   assert(ReturnObject && "the return object is expected to be valid");
7355   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7356                                                      /*NoCopyInit*/ false);
7357   if (Res.isInvalid())
7358     return StmtError();
7359   Builder.ReturnValue = Res.get();
7360 
7361   // If during the previous parse the coroutine still had a dependent promise
7362   // statement, we may need to build some implicit coroutine statements
7363   // (such as exception and fallthrough handlers) for the first time.
7364   if (S->hasDependentPromiseType()) {
7365     // We can only build these statements, however, if the current promise type
7366     // is not dependent.
7367     if (!Promise->getType()->isDependentType()) {
7368       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7369              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7370              "these nodes should not have been built yet");
7371       if (!Builder.buildDependentStatements())
7372         return StmtError();
7373     }
7374   } else {
7375     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7376       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7377       if (Res.isInvalid())
7378         return StmtError();
7379       Builder.OnFallthrough = Res.get();
7380     }
7381 
7382     if (auto *OnException = S->getExceptionHandler()) {
7383       StmtResult Res = getDerived().TransformStmt(OnException);
7384       if (Res.isInvalid())
7385         return StmtError();
7386       Builder.OnException = Res.get();
7387     }
7388 
7389     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7390       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7391       if (Res.isInvalid())
7392         return StmtError();
7393       Builder.ReturnStmtOnAllocFailure = Res.get();
7394     }
7395 
7396     // Transform any additional statements we may have already built
7397     assert(S->getAllocate() && S->getDeallocate() &&
7398            "allocation and deallocation calls must already be built");
7399     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7400     if (AllocRes.isInvalid())
7401       return StmtError();
7402     Builder.Allocate = AllocRes.get();
7403 
7404     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7405     if (DeallocRes.isInvalid())
7406       return StmtError();
7407     Builder.Deallocate = DeallocRes.get();
7408 
7409     assert(S->getResultDecl() && "ResultDecl must already be built");
7410     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7411     if (ResultDecl.isInvalid())
7412       return StmtError();
7413     Builder.ResultDecl = ResultDecl.get();
7414 
7415     if (auto *ReturnStmt = S->getReturnStmt()) {
7416       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7417       if (Res.isInvalid())
7418         return StmtError();
7419       Builder.ReturnStmt = Res.get();
7420     }
7421   }
7422 
7423   return getDerived().RebuildCoroutineBodyStmt(Builder);
7424 }
7425 
7426 template<typename Derived>
7427 StmtResult
7428 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7429   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7430                                                         /*NotCopyInit*/false);
7431   if (Result.isInvalid())
7432     return StmtError();
7433 
7434   // Always rebuild; we don't know if this needs to be injected into a new
7435   // context or if the promise type has changed.
7436   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7437                                           S->isImplicit());
7438 }
7439 
7440 template<typename Derived>
7441 ExprResult
7442 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7443   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7444                                                         /*NotCopyInit*/false);
7445   if (Result.isInvalid())
7446     return ExprError();
7447 
7448   // Always rebuild; we don't know if this needs to be injected into a new
7449   // context or if the promise type has changed.
7450   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7451                                          E->isImplicit());
7452 }
7453 
7454 template <typename Derived>
7455 ExprResult
7456 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7457   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7458                                                         /*NotCopyInit*/ false);
7459   if (OperandResult.isInvalid())
7460     return ExprError();
7461 
7462   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7463           E->getOperatorCoawaitLookup());
7464 
7465   if (LookupResult.isInvalid())
7466     return ExprError();
7467 
7468   // Always rebuild; we don't know if this needs to be injected into a new
7469   // context or if the promise type has changed.
7470   return getDerived().RebuildDependentCoawaitExpr(
7471       E->getKeywordLoc(), OperandResult.get(),
7472       cast<UnresolvedLookupExpr>(LookupResult.get()));
7473 }
7474 
7475 template<typename Derived>
7476 ExprResult
7477 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7478   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7479                                                         /*NotCopyInit*/false);
7480   if (Result.isInvalid())
7481     return ExprError();
7482 
7483   // Always rebuild; we don't know if this needs to be injected into a new
7484   // context or if the promise type has changed.
7485   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7486 }
7487 
7488 // Objective-C Statements.
7489 
7490 template<typename Derived>
7491 StmtResult
7492 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7493   // Transform the body of the @try.
7494   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7495   if (TryBody.isInvalid())
7496     return StmtError();
7497 
7498   // Transform the @catch statements (if present).
7499   bool AnyCatchChanged = false;
7500   SmallVector<Stmt*, 8> CatchStmts;
7501   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7502     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7503     if (Catch.isInvalid())
7504       return StmtError();
7505     if (Catch.get() != S->getCatchStmt(I))
7506       AnyCatchChanged = true;
7507     CatchStmts.push_back(Catch.get());
7508   }
7509 
7510   // Transform the @finally statement (if present).
7511   StmtResult Finally;
7512   if (S->getFinallyStmt()) {
7513     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7514     if (Finally.isInvalid())
7515       return StmtError();
7516   }
7517 
7518   // If nothing changed, just retain this statement.
7519   if (!getDerived().AlwaysRebuild() &&
7520       TryBody.get() == S->getTryBody() &&
7521       !AnyCatchChanged &&
7522       Finally.get() == S->getFinallyStmt())
7523     return S;
7524 
7525   // Build a new statement.
7526   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7527                                            CatchStmts, Finally.get());
7528 }
7529 
7530 template<typename Derived>
7531 StmtResult
7532 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7533   // Transform the @catch parameter, if there is one.
7534   VarDecl *Var = nullptr;
7535   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7536     TypeSourceInfo *TSInfo = nullptr;
7537     if (FromVar->getTypeSourceInfo()) {
7538       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7539       if (!TSInfo)
7540         return StmtError();
7541     }
7542 
7543     QualType T;
7544     if (TSInfo)
7545       T = TSInfo->getType();
7546     else {
7547       T = getDerived().TransformType(FromVar->getType());
7548       if (T.isNull())
7549         return StmtError();
7550     }
7551 
7552     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7553     if (!Var)
7554       return StmtError();
7555   }
7556 
7557   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7558   if (Body.isInvalid())
7559     return StmtError();
7560 
7561   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7562                                              S->getRParenLoc(),
7563                                              Var, Body.get());
7564 }
7565 
7566 template<typename Derived>
7567 StmtResult
7568 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7569   // Transform the body.
7570   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7571   if (Body.isInvalid())
7572     return StmtError();
7573 
7574   // If nothing changed, just retain this statement.
7575   if (!getDerived().AlwaysRebuild() &&
7576       Body.get() == S->getFinallyBody())
7577     return S;
7578 
7579   // Build a new statement.
7580   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7581                                                Body.get());
7582 }
7583 
7584 template<typename Derived>
7585 StmtResult
7586 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7587   ExprResult Operand;
7588   if (S->getThrowExpr()) {
7589     Operand = getDerived().TransformExpr(S->getThrowExpr());
7590     if (Operand.isInvalid())
7591       return StmtError();
7592   }
7593 
7594   if (!getDerived().AlwaysRebuild() &&
7595       Operand.get() == S->getThrowExpr())
7596     return S;
7597 
7598   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7599 }
7600 
7601 template<typename Derived>
7602 StmtResult
7603 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7604                                                   ObjCAtSynchronizedStmt *S) {
7605   // Transform the object we are locking.
7606   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7607   if (Object.isInvalid())
7608     return StmtError();
7609   Object =
7610     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7611                                                   Object.get());
7612   if (Object.isInvalid())
7613     return StmtError();
7614 
7615   // Transform the body.
7616   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7617   if (Body.isInvalid())
7618     return StmtError();
7619 
7620   // If nothing change, just retain the current statement.
7621   if (!getDerived().AlwaysRebuild() &&
7622       Object.get() == S->getSynchExpr() &&
7623       Body.get() == S->getSynchBody())
7624     return S;
7625 
7626   // Build a new statement.
7627   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7628                                                     Object.get(), Body.get());
7629 }
7630 
7631 template<typename Derived>
7632 StmtResult
7633 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7634                                               ObjCAutoreleasePoolStmt *S) {
7635   // Transform the body.
7636   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7637   if (Body.isInvalid())
7638     return StmtError();
7639 
7640   // If nothing changed, just retain this statement.
7641   if (!getDerived().AlwaysRebuild() &&
7642       Body.get() == S->getSubStmt())
7643     return S;
7644 
7645   // Build a new statement.
7646   return getDerived().RebuildObjCAutoreleasePoolStmt(
7647                         S->getAtLoc(), Body.get());
7648 }
7649 
7650 template<typename Derived>
7651 StmtResult
7652 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7653                                                   ObjCForCollectionStmt *S) {
7654   // Transform the element statement.
7655   StmtResult Element =
7656       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7657   if (Element.isInvalid())
7658     return StmtError();
7659 
7660   // Transform the collection expression.
7661   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7662   if (Collection.isInvalid())
7663     return StmtError();
7664 
7665   // Transform the body.
7666   StmtResult Body = getDerived().TransformStmt(S->getBody());
7667   if (Body.isInvalid())
7668     return StmtError();
7669 
7670   // If nothing changed, just retain this statement.
7671   if (!getDerived().AlwaysRebuild() &&
7672       Element.get() == S->getElement() &&
7673       Collection.get() == S->getCollection() &&
7674       Body.get() == S->getBody())
7675     return S;
7676 
7677   // Build a new statement.
7678   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7679                                                    Element.get(),
7680                                                    Collection.get(),
7681                                                    S->getRParenLoc(),
7682                                                    Body.get());
7683 }
7684 
7685 template <typename Derived>
7686 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7687   // Transform the exception declaration, if any.
7688   VarDecl *Var = nullptr;
7689   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7690     TypeSourceInfo *T =
7691         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7692     if (!T)
7693       return StmtError();
7694 
7695     Var = getDerived().RebuildExceptionDecl(
7696         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7697         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7698     if (!Var || Var->isInvalidDecl())
7699       return StmtError();
7700   }
7701 
7702   // Transform the actual exception handler.
7703   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7704   if (Handler.isInvalid())
7705     return StmtError();
7706 
7707   if (!getDerived().AlwaysRebuild() && !Var &&
7708       Handler.get() == S->getHandlerBlock())
7709     return S;
7710 
7711   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7712 }
7713 
7714 template <typename Derived>
7715 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7716   // Transform the try block itself.
7717   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7718   if (TryBlock.isInvalid())
7719     return StmtError();
7720 
7721   // Transform the handlers.
7722   bool HandlerChanged = false;
7723   SmallVector<Stmt *, 8> Handlers;
7724   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7725     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7726     if (Handler.isInvalid())
7727       return StmtError();
7728 
7729     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7730     Handlers.push_back(Handler.getAs<Stmt>());
7731   }
7732 
7733   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7734       !HandlerChanged)
7735     return S;
7736 
7737   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7738                                         Handlers);
7739 }
7740 
7741 template<typename Derived>
7742 StmtResult
7743 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7744   StmtResult Init =
7745       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7746   if (Init.isInvalid())
7747     return StmtError();
7748 
7749   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7750   if (Range.isInvalid())
7751     return StmtError();
7752 
7753   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7754   if (Begin.isInvalid())
7755     return StmtError();
7756   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7757   if (End.isInvalid())
7758     return StmtError();
7759 
7760   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7761   if (Cond.isInvalid())
7762     return StmtError();
7763   if (Cond.get())
7764     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7765   if (Cond.isInvalid())
7766     return StmtError();
7767   if (Cond.get())
7768     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7769 
7770   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7771   if (Inc.isInvalid())
7772     return StmtError();
7773   if (Inc.get())
7774     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7775 
7776   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7777   if (LoopVar.isInvalid())
7778     return StmtError();
7779 
7780   StmtResult NewStmt = S;
7781   if (getDerived().AlwaysRebuild() ||
7782       Init.get() != S->getInit() ||
7783       Range.get() != S->getRangeStmt() ||
7784       Begin.get() != S->getBeginStmt() ||
7785       End.get() != S->getEndStmt() ||
7786       Cond.get() != S->getCond() ||
7787       Inc.get() != S->getInc() ||
7788       LoopVar.get() != S->getLoopVarStmt()) {
7789     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7790                                                   S->getCoawaitLoc(), Init.get(),
7791                                                   S->getColonLoc(), Range.get(),
7792                                                   Begin.get(), End.get(),
7793                                                   Cond.get(),
7794                                                   Inc.get(), LoopVar.get(),
7795                                                   S->getRParenLoc());
7796     if (NewStmt.isInvalid())
7797       return StmtError();
7798   }
7799 
7800   StmtResult Body = getDerived().TransformStmt(S->getBody());
7801   if (Body.isInvalid())
7802     return StmtError();
7803 
7804   // Body has changed but we didn't rebuild the for-range statement. Rebuild
7805   // it now so we have a new statement to attach the body to.
7806   if (Body.get() != S->getBody() && NewStmt.get() == S) {
7807     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7808                                                   S->getCoawaitLoc(), Init.get(),
7809                                                   S->getColonLoc(), Range.get(),
7810                                                   Begin.get(), End.get(),
7811                                                   Cond.get(),
7812                                                   Inc.get(), LoopVar.get(),
7813                                                   S->getRParenLoc());
7814     if (NewStmt.isInvalid())
7815       return StmtError();
7816   }
7817 
7818   if (NewStmt.get() == S)
7819     return S;
7820 
7821   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7822 }
7823 
7824 template<typename Derived>
7825 StmtResult
7826 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7827                                                     MSDependentExistsStmt *S) {
7828   // Transform the nested-name-specifier, if any.
7829   NestedNameSpecifierLoc QualifierLoc;
7830   if (S->getQualifierLoc()) {
7831     QualifierLoc
7832       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7833     if (!QualifierLoc)
7834       return StmtError();
7835   }
7836 
7837   // Transform the declaration name.
7838   DeclarationNameInfo NameInfo = S->getNameInfo();
7839   if (NameInfo.getName()) {
7840     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7841     if (!NameInfo.getName())
7842       return StmtError();
7843   }
7844 
7845   // Check whether anything changed.
7846   if (!getDerived().AlwaysRebuild() &&
7847       QualifierLoc == S->getQualifierLoc() &&
7848       NameInfo.getName() == S->getNameInfo().getName())
7849     return S;
7850 
7851   // Determine whether this name exists, if we can.
7852   CXXScopeSpec SS;
7853   SS.Adopt(QualifierLoc);
7854   bool Dependent = false;
7855   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7856   case Sema::IER_Exists:
7857     if (S->isIfExists())
7858       break;
7859 
7860     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7861 
7862   case Sema::IER_DoesNotExist:
7863     if (S->isIfNotExists())
7864       break;
7865 
7866     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7867 
7868   case Sema::IER_Dependent:
7869     Dependent = true;
7870     break;
7871 
7872   case Sema::IER_Error:
7873     return StmtError();
7874   }
7875 
7876   // We need to continue with the instantiation, so do so now.
7877   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7878   if (SubStmt.isInvalid())
7879     return StmtError();
7880 
7881   // If we have resolved the name, just transform to the substatement.
7882   if (!Dependent)
7883     return SubStmt;
7884 
7885   // The name is still dependent, so build a dependent expression again.
7886   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7887                                                    S->isIfExists(),
7888                                                    QualifierLoc,
7889                                                    NameInfo,
7890                                                    SubStmt.get());
7891 }
7892 
7893 template<typename Derived>
7894 ExprResult
7895 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7896   NestedNameSpecifierLoc QualifierLoc;
7897   if (E->getQualifierLoc()) {
7898     QualifierLoc
7899     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7900     if (!QualifierLoc)
7901       return ExprError();
7902   }
7903 
7904   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7905     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7906   if (!PD)
7907     return ExprError();
7908 
7909   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7910   if (Base.isInvalid())
7911     return ExprError();
7912 
7913   return new (SemaRef.getASTContext())
7914       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7915                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7916                         QualifierLoc, E->getMemberLoc());
7917 }
7918 
7919 template <typename Derived>
7920 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7921     MSPropertySubscriptExpr *E) {
7922   auto BaseRes = getDerived().TransformExpr(E->getBase());
7923   if (BaseRes.isInvalid())
7924     return ExprError();
7925   auto IdxRes = getDerived().TransformExpr(E->getIdx());
7926   if (IdxRes.isInvalid())
7927     return ExprError();
7928 
7929   if (!getDerived().AlwaysRebuild() &&
7930       BaseRes.get() == E->getBase() &&
7931       IdxRes.get() == E->getIdx())
7932     return E;
7933 
7934   return getDerived().RebuildArraySubscriptExpr(
7935       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7936 }
7937 
7938 template <typename Derived>
7939 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7940   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7941   if (TryBlock.isInvalid())
7942     return StmtError();
7943 
7944   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7945   if (Handler.isInvalid())
7946     return StmtError();
7947 
7948   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7949       Handler.get() == S->getHandler())
7950     return S;
7951 
7952   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7953                                         TryBlock.get(), Handler.get());
7954 }
7955 
7956 template <typename Derived>
7957 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7958   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7959   if (Block.isInvalid())
7960     return StmtError();
7961 
7962   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7963 }
7964 
7965 template <typename Derived>
7966 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7967   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7968   if (FilterExpr.isInvalid())
7969     return StmtError();
7970 
7971   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7972   if (Block.isInvalid())
7973     return StmtError();
7974 
7975   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7976                                            Block.get());
7977 }
7978 
7979 template <typename Derived>
7980 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7981   if (isa<SEHFinallyStmt>(Handler))
7982     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7983   else
7984     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7985 }
7986 
7987 template<typename Derived>
7988 StmtResult
7989 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7990   return S;
7991 }
7992 
7993 //===----------------------------------------------------------------------===//
7994 // OpenMP directive transformation
7995 //===----------------------------------------------------------------------===//
7996 template <typename Derived>
7997 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7998     OMPExecutableDirective *D) {
7999 
8000   // Transform the clauses
8001   llvm::SmallVector<OMPClause *, 16> TClauses;
8002   ArrayRef<OMPClause *> Clauses = D->clauses();
8003   TClauses.reserve(Clauses.size());
8004   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8005        I != E; ++I) {
8006     if (*I) {
8007       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8008       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8009       getDerived().getSema().EndOpenMPClause();
8010       if (Clause)
8011         TClauses.push_back(Clause);
8012     } else {
8013       TClauses.push_back(nullptr);
8014     }
8015   }
8016   StmtResult AssociatedStmt;
8017   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8018     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8019                                                   /*CurScope=*/nullptr);
8020     StmtResult Body;
8021     {
8022       Sema::CompoundScopeRAII CompoundScope(getSema());
8023       Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
8024       Body = getDerived().TransformStmt(CS);
8025     }
8026     AssociatedStmt =
8027         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8028     if (AssociatedStmt.isInvalid()) {
8029       return StmtError();
8030     }
8031   }
8032   if (TClauses.size() != Clauses.size()) {
8033     return StmtError();
8034   }
8035 
8036   // Transform directive name for 'omp critical' directive.
8037   DeclarationNameInfo DirName;
8038   if (D->getDirectiveKind() == OMPD_critical) {
8039     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8040     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8041   }
8042   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8043   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8044     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8045   } else if (D->getDirectiveKind() == OMPD_cancel) {
8046     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8047   }
8048 
8049   return getDerived().RebuildOMPExecutableDirective(
8050       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8051       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8052 }
8053 
8054 template <typename Derived>
8055 StmtResult
8056 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8057   DeclarationNameInfo DirName;
8058   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8059                                              D->getBeginLoc());
8060   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8061   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8062   return Res;
8063 }
8064 
8065 template <typename Derived>
8066 StmtResult
8067 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8068   DeclarationNameInfo DirName;
8069   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8070                                              D->getBeginLoc());
8071   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8072   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8073   return Res;
8074 }
8075 
8076 template <typename Derived>
8077 StmtResult
8078 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8079   DeclarationNameInfo DirName;
8080   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8081                                              D->getBeginLoc());
8082   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8083   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8084   return Res;
8085 }
8086 
8087 template <typename Derived>
8088 StmtResult
8089 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8090   DeclarationNameInfo DirName;
8091   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8092                                              D->getBeginLoc());
8093   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8094   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8095   return Res;
8096 }
8097 
8098 template <typename Derived>
8099 StmtResult
8100 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8101   DeclarationNameInfo DirName;
8102   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8103                                              D->getBeginLoc());
8104   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8105   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8106   return Res;
8107 }
8108 
8109 template <typename Derived>
8110 StmtResult
8111 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8112   DeclarationNameInfo DirName;
8113   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8114                                              D->getBeginLoc());
8115   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8116   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8117   return Res;
8118 }
8119 
8120 template <typename Derived>
8121 StmtResult
8122 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8123   DeclarationNameInfo DirName;
8124   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8125                                              D->getBeginLoc());
8126   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8127   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8128   return Res;
8129 }
8130 
8131 template <typename Derived>
8132 StmtResult
8133 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8134   DeclarationNameInfo DirName;
8135   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8136                                              D->getBeginLoc());
8137   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8138   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8139   return Res;
8140 }
8141 
8142 template <typename Derived>
8143 StmtResult
8144 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8145   getDerived().getSema().StartOpenMPDSABlock(
8146       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8147   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8148   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8149   return Res;
8150 }
8151 
8152 template <typename Derived>
8153 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8154     OMPParallelForDirective *D) {
8155   DeclarationNameInfo DirName;
8156   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8157                                              nullptr, D->getBeginLoc());
8158   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8159   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8160   return Res;
8161 }
8162 
8163 template <typename Derived>
8164 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8165     OMPParallelForSimdDirective *D) {
8166   DeclarationNameInfo DirName;
8167   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8168                                              nullptr, D->getBeginLoc());
8169   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8170   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8171   return Res;
8172 }
8173 
8174 template <typename Derived>
8175 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8176     OMPParallelMasterDirective *D) {
8177   DeclarationNameInfo DirName;
8178   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8179                                              nullptr, D->getBeginLoc());
8180   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8181   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8182   return Res;
8183 }
8184 
8185 template <typename Derived>
8186 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8187     OMPParallelSectionsDirective *D) {
8188   DeclarationNameInfo DirName;
8189   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8190                                              nullptr, D->getBeginLoc());
8191   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8192   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8193   return Res;
8194 }
8195 
8196 template <typename Derived>
8197 StmtResult
8198 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8199   DeclarationNameInfo DirName;
8200   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8201                                              D->getBeginLoc());
8202   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8203   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8204   return Res;
8205 }
8206 
8207 template <typename Derived>
8208 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8209     OMPTaskyieldDirective *D) {
8210   DeclarationNameInfo DirName;
8211   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8212                                              D->getBeginLoc());
8213   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8214   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8215   return Res;
8216 }
8217 
8218 template <typename Derived>
8219 StmtResult
8220 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8221   DeclarationNameInfo DirName;
8222   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8223                                              D->getBeginLoc());
8224   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8225   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8226   return Res;
8227 }
8228 
8229 template <typename Derived>
8230 StmtResult
8231 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8232   DeclarationNameInfo DirName;
8233   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8234                                              D->getBeginLoc());
8235   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8236   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8237   return Res;
8238 }
8239 
8240 template <typename Derived>
8241 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8242     OMPTaskgroupDirective *D) {
8243   DeclarationNameInfo DirName;
8244   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8245                                              D->getBeginLoc());
8246   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8247   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8248   return Res;
8249 }
8250 
8251 template <typename Derived>
8252 StmtResult
8253 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8254   DeclarationNameInfo DirName;
8255   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8256                                              D->getBeginLoc());
8257   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8258   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8259   return Res;
8260 }
8261 
8262 template <typename Derived>
8263 StmtResult
8264 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8265   DeclarationNameInfo DirName;
8266   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8267                                              D->getBeginLoc());
8268   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8269   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8270   return Res;
8271 }
8272 
8273 template <typename Derived>
8274 StmtResult
8275 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8276   DeclarationNameInfo DirName;
8277   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8278                                              D->getBeginLoc());
8279   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8280   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8281   return Res;
8282 }
8283 
8284 template <typename Derived>
8285 StmtResult
8286 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8287   DeclarationNameInfo DirName;
8288   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8289                                              D->getBeginLoc());
8290   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8291   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8292   return Res;
8293 }
8294 
8295 template <typename Derived>
8296 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8297     OMPTargetDataDirective *D) {
8298   DeclarationNameInfo DirName;
8299   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8300                                              D->getBeginLoc());
8301   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8302   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8303   return Res;
8304 }
8305 
8306 template <typename Derived>
8307 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8308     OMPTargetEnterDataDirective *D) {
8309   DeclarationNameInfo DirName;
8310   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8311                                              nullptr, D->getBeginLoc());
8312   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8313   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8314   return Res;
8315 }
8316 
8317 template <typename Derived>
8318 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8319     OMPTargetExitDataDirective *D) {
8320   DeclarationNameInfo DirName;
8321   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8322                                              nullptr, D->getBeginLoc());
8323   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8324   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8325   return Res;
8326 }
8327 
8328 template <typename Derived>
8329 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8330     OMPTargetParallelDirective *D) {
8331   DeclarationNameInfo DirName;
8332   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8333                                              nullptr, D->getBeginLoc());
8334   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8335   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8336   return Res;
8337 }
8338 
8339 template <typename Derived>
8340 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8341     OMPTargetParallelForDirective *D) {
8342   DeclarationNameInfo DirName;
8343   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8344                                              nullptr, D->getBeginLoc());
8345   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8346   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8347   return Res;
8348 }
8349 
8350 template <typename Derived>
8351 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8352     OMPTargetUpdateDirective *D) {
8353   DeclarationNameInfo DirName;
8354   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8355                                              nullptr, D->getBeginLoc());
8356   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8357   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8358   return Res;
8359 }
8360 
8361 template <typename Derived>
8362 StmtResult
8363 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8364   DeclarationNameInfo DirName;
8365   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8366                                              D->getBeginLoc());
8367   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8368   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8369   return Res;
8370 }
8371 
8372 template <typename Derived>
8373 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8374     OMPCancellationPointDirective *D) {
8375   DeclarationNameInfo DirName;
8376   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8377                                              nullptr, D->getBeginLoc());
8378   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8379   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8380   return Res;
8381 }
8382 
8383 template <typename Derived>
8384 StmtResult
8385 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8386   DeclarationNameInfo DirName;
8387   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8388                                              D->getBeginLoc());
8389   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8390   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8391   return Res;
8392 }
8393 
8394 template <typename Derived>
8395 StmtResult
8396 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8397   DeclarationNameInfo DirName;
8398   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8399                                              D->getBeginLoc());
8400   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8401   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8402   return Res;
8403 }
8404 
8405 template <typename Derived>
8406 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8407     OMPTaskLoopSimdDirective *D) {
8408   DeclarationNameInfo DirName;
8409   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8410                                              nullptr, D->getBeginLoc());
8411   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8412   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8413   return Res;
8414 }
8415 
8416 template <typename Derived>
8417 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8418     OMPMasterTaskLoopDirective *D) {
8419   DeclarationNameInfo DirName;
8420   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8421                                              nullptr, D->getBeginLoc());
8422   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8423   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8424   return Res;
8425 }
8426 
8427 template <typename Derived>
8428 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
8429     OMPMasterTaskLoopSimdDirective *D) {
8430   DeclarationNameInfo DirName;
8431   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8432                                              nullptr, D->getBeginLoc());
8433   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8434   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8435   return Res;
8436 }
8437 
8438 template <typename Derived>
8439 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8440     OMPParallelMasterTaskLoopDirective *D) {
8441   DeclarationNameInfo DirName;
8442   getDerived().getSema().StartOpenMPDSABlock(
8443       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
8444   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8445   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8446   return Res;
8447 }
8448 
8449 template <typename Derived>
8450 StmtResult
8451 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
8452     OMPParallelMasterTaskLoopSimdDirective *D) {
8453   DeclarationNameInfo DirName;
8454   getDerived().getSema().StartOpenMPDSABlock(
8455       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
8456   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8457   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8458   return Res;
8459 }
8460 
8461 template <typename Derived>
8462 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8463     OMPDistributeDirective *D) {
8464   DeclarationNameInfo DirName;
8465   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8466                                              D->getBeginLoc());
8467   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8468   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8469   return Res;
8470 }
8471 
8472 template <typename Derived>
8473 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8474     OMPDistributeParallelForDirective *D) {
8475   DeclarationNameInfo DirName;
8476   getDerived().getSema().StartOpenMPDSABlock(
8477       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8478   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8479   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8480   return Res;
8481 }
8482 
8483 template <typename Derived>
8484 StmtResult
8485 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8486     OMPDistributeParallelForSimdDirective *D) {
8487   DeclarationNameInfo DirName;
8488   getDerived().getSema().StartOpenMPDSABlock(
8489       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8490   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8491   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8492   return Res;
8493 }
8494 
8495 template <typename Derived>
8496 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8497     OMPDistributeSimdDirective *D) {
8498   DeclarationNameInfo DirName;
8499   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8500                                              nullptr, D->getBeginLoc());
8501   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8502   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8503   return Res;
8504 }
8505 
8506 template <typename Derived>
8507 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8508     OMPTargetParallelForSimdDirective *D) {
8509   DeclarationNameInfo DirName;
8510   getDerived().getSema().StartOpenMPDSABlock(
8511       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8512   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8513   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8514   return Res;
8515 }
8516 
8517 template <typename Derived>
8518 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8519     OMPTargetSimdDirective *D) {
8520   DeclarationNameInfo DirName;
8521   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8522                                              D->getBeginLoc());
8523   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8524   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8525   return Res;
8526 }
8527 
8528 template <typename Derived>
8529 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8530     OMPTeamsDistributeDirective *D) {
8531   DeclarationNameInfo DirName;
8532   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8533                                              nullptr, D->getBeginLoc());
8534   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8535   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8536   return Res;
8537 }
8538 
8539 template <typename Derived>
8540 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8541     OMPTeamsDistributeSimdDirective *D) {
8542   DeclarationNameInfo DirName;
8543   getDerived().getSema().StartOpenMPDSABlock(
8544       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8545   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8546   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8547   return Res;
8548 }
8549 
8550 template <typename Derived>
8551 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8552     OMPTeamsDistributeParallelForSimdDirective *D) {
8553   DeclarationNameInfo DirName;
8554   getDerived().getSema().StartOpenMPDSABlock(
8555       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8556       D->getBeginLoc());
8557   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8558   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8559   return Res;
8560 }
8561 
8562 template <typename Derived>
8563 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8564     OMPTeamsDistributeParallelForDirective *D) {
8565   DeclarationNameInfo DirName;
8566   getDerived().getSema().StartOpenMPDSABlock(
8567       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8568   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8569   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8570   return Res;
8571 }
8572 
8573 template <typename Derived>
8574 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8575     OMPTargetTeamsDirective *D) {
8576   DeclarationNameInfo DirName;
8577   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8578                                              nullptr, D->getBeginLoc());
8579   auto Res = getDerived().TransformOMPExecutableDirective(D);
8580   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8581   return Res;
8582 }
8583 
8584 template <typename Derived>
8585 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8586     OMPTargetTeamsDistributeDirective *D) {
8587   DeclarationNameInfo DirName;
8588   getDerived().getSema().StartOpenMPDSABlock(
8589       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8590   auto Res = getDerived().TransformOMPExecutableDirective(D);
8591   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8592   return Res;
8593 }
8594 
8595 template <typename Derived>
8596 StmtResult
8597 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8598     OMPTargetTeamsDistributeParallelForDirective *D) {
8599   DeclarationNameInfo DirName;
8600   getDerived().getSema().StartOpenMPDSABlock(
8601       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8602       D->getBeginLoc());
8603   auto Res = getDerived().TransformOMPExecutableDirective(D);
8604   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8605   return Res;
8606 }
8607 
8608 template <typename Derived>
8609 StmtResult TreeTransform<Derived>::
8610     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8611         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8612   DeclarationNameInfo DirName;
8613   getDerived().getSema().StartOpenMPDSABlock(
8614       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8615       D->getBeginLoc());
8616   auto Res = getDerived().TransformOMPExecutableDirective(D);
8617   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8618   return Res;
8619 }
8620 
8621 template <typename Derived>
8622 StmtResult
8623 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8624     OMPTargetTeamsDistributeSimdDirective *D) {
8625   DeclarationNameInfo DirName;
8626   getDerived().getSema().StartOpenMPDSABlock(
8627       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8628   auto Res = getDerived().TransformOMPExecutableDirective(D);
8629   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8630   return Res;
8631 }
8632 
8633 
8634 //===----------------------------------------------------------------------===//
8635 // OpenMP clause transformation
8636 //===----------------------------------------------------------------------===//
8637 template <typename Derived>
8638 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8639   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8640   if (Cond.isInvalid())
8641     return nullptr;
8642   return getDerived().RebuildOMPIfClause(
8643       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8644       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8645 }
8646 
8647 template <typename Derived>
8648 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8649   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8650   if (Cond.isInvalid())
8651     return nullptr;
8652   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8653                                             C->getLParenLoc(), C->getEndLoc());
8654 }
8655 
8656 template <typename Derived>
8657 OMPClause *
8658 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8659   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8660   if (NumThreads.isInvalid())
8661     return nullptr;
8662   return getDerived().RebuildOMPNumThreadsClause(
8663       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8664 }
8665 
8666 template <typename Derived>
8667 OMPClause *
8668 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8669   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8670   if (E.isInvalid())
8671     return nullptr;
8672   return getDerived().RebuildOMPSafelenClause(
8673       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8674 }
8675 
8676 template <typename Derived>
8677 OMPClause *
8678 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8679   ExprResult E = getDerived().TransformExpr(C->getAllocator());
8680   if (E.isInvalid())
8681     return nullptr;
8682   return getDerived().RebuildOMPAllocatorClause(
8683       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8684 }
8685 
8686 template <typename Derived>
8687 OMPClause *
8688 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8689   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8690   if (E.isInvalid())
8691     return nullptr;
8692   return getDerived().RebuildOMPSimdlenClause(
8693       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8694 }
8695 
8696 template <typename Derived>
8697 OMPClause *
8698 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8699   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8700   if (E.isInvalid())
8701     return nullptr;
8702   return getDerived().RebuildOMPCollapseClause(
8703       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8704 }
8705 
8706 template <typename Derived>
8707 OMPClause *
8708 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8709   return getDerived().RebuildOMPDefaultClause(
8710       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8711       C->getLParenLoc(), C->getEndLoc());
8712 }
8713 
8714 template <typename Derived>
8715 OMPClause *
8716 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8717   return getDerived().RebuildOMPProcBindClause(
8718       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8719       C->getLParenLoc(), C->getEndLoc());
8720 }
8721 
8722 template <typename Derived>
8723 OMPClause *
8724 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8725   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8726   if (E.isInvalid())
8727     return nullptr;
8728   return getDerived().RebuildOMPScheduleClause(
8729       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8730       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8731       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8732       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8733 }
8734 
8735 template <typename Derived>
8736 OMPClause *
8737 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8738   ExprResult E;
8739   if (auto *Num = C->getNumForLoops()) {
8740     E = getDerived().TransformExpr(Num);
8741     if (E.isInvalid())
8742       return nullptr;
8743   }
8744   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8745                                               C->getLParenLoc(), E.get());
8746 }
8747 
8748 template <typename Derived>
8749 OMPClause *
8750 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8751   // No need to rebuild this clause, no template-dependent parameters.
8752   return C;
8753 }
8754 
8755 template <typename Derived>
8756 OMPClause *
8757 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8758   // No need to rebuild this clause, no template-dependent parameters.
8759   return C;
8760 }
8761 
8762 template <typename Derived>
8763 OMPClause *
8764 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8765   // No need to rebuild this clause, no template-dependent parameters.
8766   return C;
8767 }
8768 
8769 template <typename Derived>
8770 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8771   // No need to rebuild this clause, no template-dependent parameters.
8772   return C;
8773 }
8774 
8775 template <typename Derived>
8776 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8777   // No need to rebuild this clause, no template-dependent parameters.
8778   return C;
8779 }
8780 
8781 template <typename Derived>
8782 OMPClause *
8783 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8784   // No need to rebuild this clause, no template-dependent parameters.
8785   return C;
8786 }
8787 
8788 template <typename Derived>
8789 OMPClause *
8790 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8791   // No need to rebuild this clause, no template-dependent parameters.
8792   return C;
8793 }
8794 
8795 template <typename Derived>
8796 OMPClause *
8797 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8798   // No need to rebuild this clause, no template-dependent parameters.
8799   return C;
8800 }
8801 
8802 template <typename Derived>
8803 OMPClause *
8804 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8805   // No need to rebuild this clause, no template-dependent parameters.
8806   return C;
8807 }
8808 
8809 template <typename Derived>
8810 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8811   // No need to rebuild this clause, no template-dependent parameters.
8812   return C;
8813 }
8814 
8815 template <typename Derived>
8816 OMPClause *
8817 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8818   // No need to rebuild this clause, no template-dependent parameters.
8819   return C;
8820 }
8821 
8822 template <typename Derived>
8823 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8824     OMPUnifiedAddressClause *C) {
8825   llvm_unreachable("unified_address clause cannot appear in dependent context");
8826 }
8827 
8828 template <typename Derived>
8829 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8830     OMPUnifiedSharedMemoryClause *C) {
8831   llvm_unreachable(
8832       "unified_shared_memory clause cannot appear in dependent context");
8833 }
8834 
8835 template <typename Derived>
8836 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8837     OMPReverseOffloadClause *C) {
8838   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8839 }
8840 
8841 template <typename Derived>
8842 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8843     OMPDynamicAllocatorsClause *C) {
8844   llvm_unreachable(
8845       "dynamic_allocators clause cannot appear in dependent context");
8846 }
8847 
8848 template <typename Derived>
8849 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8850     OMPAtomicDefaultMemOrderClause *C) {
8851   llvm_unreachable(
8852       "atomic_default_mem_order clause cannot appear in dependent context");
8853 }
8854 
8855 template <typename Derived>
8856 OMPClause *
8857 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8858   llvm::SmallVector<Expr *, 16> Vars;
8859   Vars.reserve(C->varlist_size());
8860   for (auto *VE : C->varlists()) {
8861     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8862     if (EVar.isInvalid())
8863       return nullptr;
8864     Vars.push_back(EVar.get());
8865   }
8866   return getDerived().RebuildOMPPrivateClause(
8867       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8868 }
8869 
8870 template <typename Derived>
8871 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8872     OMPFirstprivateClause *C) {
8873   llvm::SmallVector<Expr *, 16> Vars;
8874   Vars.reserve(C->varlist_size());
8875   for (auto *VE : C->varlists()) {
8876     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8877     if (EVar.isInvalid())
8878       return nullptr;
8879     Vars.push_back(EVar.get());
8880   }
8881   return getDerived().RebuildOMPFirstprivateClause(
8882       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8883 }
8884 
8885 template <typename Derived>
8886 OMPClause *
8887 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8888   llvm::SmallVector<Expr *, 16> Vars;
8889   Vars.reserve(C->varlist_size());
8890   for (auto *VE : C->varlists()) {
8891     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8892     if (EVar.isInvalid())
8893       return nullptr;
8894     Vars.push_back(EVar.get());
8895   }
8896   return getDerived().RebuildOMPLastprivateClause(
8897       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
8898       C->getLParenLoc(), C->getEndLoc());
8899 }
8900 
8901 template <typename Derived>
8902 OMPClause *
8903 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8904   llvm::SmallVector<Expr *, 16> Vars;
8905   Vars.reserve(C->varlist_size());
8906   for (auto *VE : C->varlists()) {
8907     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8908     if (EVar.isInvalid())
8909       return nullptr;
8910     Vars.push_back(EVar.get());
8911   }
8912   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8913                                              C->getLParenLoc(), C->getEndLoc());
8914 }
8915 
8916 template <typename Derived>
8917 OMPClause *
8918 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8919   llvm::SmallVector<Expr *, 16> Vars;
8920   Vars.reserve(C->varlist_size());
8921   for (auto *VE : C->varlists()) {
8922     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8923     if (EVar.isInvalid())
8924       return nullptr;
8925     Vars.push_back(EVar.get());
8926   }
8927   CXXScopeSpec ReductionIdScopeSpec;
8928   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8929 
8930   DeclarationNameInfo NameInfo = C->getNameInfo();
8931   if (NameInfo.getName()) {
8932     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8933     if (!NameInfo.getName())
8934       return nullptr;
8935   }
8936   // Build a list of all UDR decls with the same names ranged by the Scopes.
8937   // The Scope boundary is a duplication of the previous decl.
8938   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8939   for (auto *E : C->reduction_ops()) {
8940     // Transform all the decls.
8941     if (E) {
8942       auto *ULE = cast<UnresolvedLookupExpr>(E);
8943       UnresolvedSet<8> Decls;
8944       for (auto *D : ULE->decls()) {
8945         NamedDecl *InstD =
8946             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8947         Decls.addDecl(InstD, InstD->getAccess());
8948       }
8949       UnresolvedReductions.push_back(
8950        UnresolvedLookupExpr::Create(
8951           SemaRef.Context, /*NamingClass=*/nullptr,
8952           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8953           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8954           Decls.begin(), Decls.end()));
8955     } else
8956       UnresolvedReductions.push_back(nullptr);
8957   }
8958   return getDerived().RebuildOMPReductionClause(
8959       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8960       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8961 }
8962 
8963 template <typename Derived>
8964 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8965     OMPTaskReductionClause *C) {
8966   llvm::SmallVector<Expr *, 16> Vars;
8967   Vars.reserve(C->varlist_size());
8968   for (auto *VE : C->varlists()) {
8969     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8970     if (EVar.isInvalid())
8971       return nullptr;
8972     Vars.push_back(EVar.get());
8973   }
8974   CXXScopeSpec ReductionIdScopeSpec;
8975   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8976 
8977   DeclarationNameInfo NameInfo = C->getNameInfo();
8978   if (NameInfo.getName()) {
8979     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8980     if (!NameInfo.getName())
8981       return nullptr;
8982   }
8983   // Build a list of all UDR decls with the same names ranged by the Scopes.
8984   // The Scope boundary is a duplication of the previous decl.
8985   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8986   for (auto *E : C->reduction_ops()) {
8987     // Transform all the decls.
8988     if (E) {
8989       auto *ULE = cast<UnresolvedLookupExpr>(E);
8990       UnresolvedSet<8> Decls;
8991       for (auto *D : ULE->decls()) {
8992         NamedDecl *InstD =
8993             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8994         Decls.addDecl(InstD, InstD->getAccess());
8995       }
8996       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8997           SemaRef.Context, /*NamingClass=*/nullptr,
8998           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8999           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9000     } else
9001       UnresolvedReductions.push_back(nullptr);
9002   }
9003   return getDerived().RebuildOMPTaskReductionClause(
9004       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9005       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9006 }
9007 
9008 template <typename Derived>
9009 OMPClause *
9010 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *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   CXXScopeSpec ReductionIdScopeSpec;
9020   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9021 
9022   DeclarationNameInfo NameInfo = C->getNameInfo();
9023   if (NameInfo.getName()) {
9024     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9025     if (!NameInfo.getName())
9026       return nullptr;
9027   }
9028   // Build a list of all UDR decls with the same names ranged by the Scopes.
9029   // The Scope boundary is a duplication of the previous decl.
9030   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9031   for (auto *E : C->reduction_ops()) {
9032     // Transform all the decls.
9033     if (E) {
9034       auto *ULE = cast<UnresolvedLookupExpr>(E);
9035       UnresolvedSet<8> Decls;
9036       for (auto *D : ULE->decls()) {
9037         NamedDecl *InstD =
9038             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9039         Decls.addDecl(InstD, InstD->getAccess());
9040       }
9041       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9042           SemaRef.Context, /*NamingClass=*/nullptr,
9043           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9044           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9045     } else
9046       UnresolvedReductions.push_back(nullptr);
9047   }
9048   return getDerived().RebuildOMPInReductionClause(
9049       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9050       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9051 }
9052 
9053 template <typename Derived>
9054 OMPClause *
9055 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
9056   llvm::SmallVector<Expr *, 16> Vars;
9057   Vars.reserve(C->varlist_size());
9058   for (auto *VE : C->varlists()) {
9059     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9060     if (EVar.isInvalid())
9061       return nullptr;
9062     Vars.push_back(EVar.get());
9063   }
9064   ExprResult Step = getDerived().TransformExpr(C->getStep());
9065   if (Step.isInvalid())
9066     return nullptr;
9067   return getDerived().RebuildOMPLinearClause(
9068       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
9069       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
9070 }
9071 
9072 template <typename Derived>
9073 OMPClause *
9074 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
9075   llvm::SmallVector<Expr *, 16> Vars;
9076   Vars.reserve(C->varlist_size());
9077   for (auto *VE : C->varlists()) {
9078     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9079     if (EVar.isInvalid())
9080       return nullptr;
9081     Vars.push_back(EVar.get());
9082   }
9083   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
9084   if (Alignment.isInvalid())
9085     return nullptr;
9086   return getDerived().RebuildOMPAlignedClause(
9087       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
9088       C->getColonLoc(), C->getEndLoc());
9089 }
9090 
9091 template <typename Derived>
9092 OMPClause *
9093 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
9094   llvm::SmallVector<Expr *, 16> Vars;
9095   Vars.reserve(C->varlist_size());
9096   for (auto *VE : C->varlists()) {
9097     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9098     if (EVar.isInvalid())
9099       return nullptr;
9100     Vars.push_back(EVar.get());
9101   }
9102   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
9103                                              C->getLParenLoc(), C->getEndLoc());
9104 }
9105 
9106 template <typename Derived>
9107 OMPClause *
9108 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
9109   llvm::SmallVector<Expr *, 16> Vars;
9110   Vars.reserve(C->varlist_size());
9111   for (auto *VE : C->varlists()) {
9112     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9113     if (EVar.isInvalid())
9114       return nullptr;
9115     Vars.push_back(EVar.get());
9116   }
9117   return getDerived().RebuildOMPCopyprivateClause(
9118       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9119 }
9120 
9121 template <typename Derived>
9122 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
9123   llvm::SmallVector<Expr *, 16> Vars;
9124   Vars.reserve(C->varlist_size());
9125   for (auto *VE : C->varlists()) {
9126     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9127     if (EVar.isInvalid())
9128       return nullptr;
9129     Vars.push_back(EVar.get());
9130   }
9131   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9132                                             C->getLParenLoc(), C->getEndLoc());
9133 }
9134 
9135 template <typename Derived>
9136 OMPClause *
9137 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9138   llvm::SmallVector<Expr *, 16> Vars;
9139   Vars.reserve(C->varlist_size());
9140   for (auto *VE : C->varlists()) {
9141     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9142     if (EVar.isInvalid())
9143       return nullptr;
9144     Vars.push_back(EVar.get());
9145   }
9146   return getDerived().RebuildOMPDependClause(
9147       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
9148       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9149 }
9150 
9151 template <typename Derived>
9152 OMPClause *
9153 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9154   ExprResult E = getDerived().TransformExpr(C->getDevice());
9155   if (E.isInvalid())
9156     return nullptr;
9157   return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
9158                                              C->getLParenLoc(), C->getEndLoc());
9159 }
9160 
9161 template <typename Derived, class T>
9162 bool transformOMPMappableExprListClause(
9163     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9164     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9165     DeclarationNameInfo &MapperIdInfo,
9166     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9167   // Transform expressions in the list.
9168   Vars.reserve(C->varlist_size());
9169   for (auto *VE : C->varlists()) {
9170     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9171     if (EVar.isInvalid())
9172       return true;
9173     Vars.push_back(EVar.get());
9174   }
9175   // Transform mapper scope specifier and identifier.
9176   NestedNameSpecifierLoc QualifierLoc;
9177   if (C->getMapperQualifierLoc()) {
9178     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9179         C->getMapperQualifierLoc());
9180     if (!QualifierLoc)
9181       return true;
9182   }
9183   MapperIdScopeSpec.Adopt(QualifierLoc);
9184   MapperIdInfo = C->getMapperIdInfo();
9185   if (MapperIdInfo.getName()) {
9186     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9187     if (!MapperIdInfo.getName())
9188       return true;
9189   }
9190   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9191   // the previous user-defined mapper lookup in dependent environment.
9192   for (auto *E : C->mapperlists()) {
9193     // Transform all the decls.
9194     if (E) {
9195       auto *ULE = cast<UnresolvedLookupExpr>(E);
9196       UnresolvedSet<8> Decls;
9197       for (auto *D : ULE->decls()) {
9198         NamedDecl *InstD =
9199             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9200         Decls.addDecl(InstD, InstD->getAccess());
9201       }
9202       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9203           TT.getSema().Context, /*NamingClass=*/nullptr,
9204           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9205           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9206           Decls.end()));
9207     } else {
9208       UnresolvedMappers.push_back(nullptr);
9209     }
9210   }
9211   return false;
9212 }
9213 
9214 template <typename Derived>
9215 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9216   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9217   llvm::SmallVector<Expr *, 16> Vars;
9218   CXXScopeSpec MapperIdScopeSpec;
9219   DeclarationNameInfo MapperIdInfo;
9220   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9221   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9222           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9223     return nullptr;
9224   return getDerived().RebuildOMPMapClause(
9225       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9226       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9227       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9228 }
9229 
9230 template <typename Derived>
9231 OMPClause *
9232 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9233   Expr *Allocator = C->getAllocator();
9234   if (Allocator) {
9235     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9236     if (AllocatorRes.isInvalid())
9237       return nullptr;
9238     Allocator = AllocatorRes.get();
9239   }
9240   llvm::SmallVector<Expr *, 16> Vars;
9241   Vars.reserve(C->varlist_size());
9242   for (auto *VE : C->varlists()) {
9243     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9244     if (EVar.isInvalid())
9245       return nullptr;
9246     Vars.push_back(EVar.get());
9247   }
9248   return getDerived().RebuildOMPAllocateClause(
9249       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9250       C->getEndLoc());
9251 }
9252 
9253 template <typename Derived>
9254 OMPClause *
9255 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9256   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9257   if (E.isInvalid())
9258     return nullptr;
9259   return getDerived().RebuildOMPNumTeamsClause(
9260       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9261 }
9262 
9263 template <typename Derived>
9264 OMPClause *
9265 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9266   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9267   if (E.isInvalid())
9268     return nullptr;
9269   return getDerived().RebuildOMPThreadLimitClause(
9270       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9271 }
9272 
9273 template <typename Derived>
9274 OMPClause *
9275 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9276   ExprResult E = getDerived().TransformExpr(C->getPriority());
9277   if (E.isInvalid())
9278     return nullptr;
9279   return getDerived().RebuildOMPPriorityClause(
9280       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9281 }
9282 
9283 template <typename Derived>
9284 OMPClause *
9285 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9286   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9287   if (E.isInvalid())
9288     return nullptr;
9289   return getDerived().RebuildOMPGrainsizeClause(
9290       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9291 }
9292 
9293 template <typename Derived>
9294 OMPClause *
9295 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9296   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9297   if (E.isInvalid())
9298     return nullptr;
9299   return getDerived().RebuildOMPNumTasksClause(
9300       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9301 }
9302 
9303 template <typename Derived>
9304 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9305   ExprResult E = getDerived().TransformExpr(C->getHint());
9306   if (E.isInvalid())
9307     return nullptr;
9308   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9309                                            C->getLParenLoc(), C->getEndLoc());
9310 }
9311 
9312 template <typename Derived>
9313 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9314     OMPDistScheduleClause *C) {
9315   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9316   if (E.isInvalid())
9317     return nullptr;
9318   return getDerived().RebuildOMPDistScheduleClause(
9319       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9320       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9321 }
9322 
9323 template <typename Derived>
9324 OMPClause *
9325 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9326   // Rebuild Defaultmap Clause since we need to invoke the checking of
9327   // defaultmap(none:variable-category) after template initialization.
9328   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
9329                                                  C->getDefaultmapKind(),
9330                                                  C->getBeginLoc(),
9331                                                  C->getLParenLoc(),
9332                                                  C->getDefaultmapModifierLoc(),
9333                                                  C->getDefaultmapKindLoc(),
9334                                                  C->getEndLoc());
9335 }
9336 
9337 template <typename Derived>
9338 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9339   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9340   llvm::SmallVector<Expr *, 16> Vars;
9341   CXXScopeSpec MapperIdScopeSpec;
9342   DeclarationNameInfo MapperIdInfo;
9343   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9344   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9345           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9346     return nullptr;
9347   return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9348                                          Locs, UnresolvedMappers);
9349 }
9350 
9351 template <typename Derived>
9352 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9353   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9354   llvm::SmallVector<Expr *, 16> Vars;
9355   CXXScopeSpec MapperIdScopeSpec;
9356   DeclarationNameInfo MapperIdInfo;
9357   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9358   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9359           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9360     return nullptr;
9361   return getDerived().RebuildOMPFromClause(
9362       Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9363 }
9364 
9365 template <typename Derived>
9366 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9367     OMPUseDevicePtrClause *C) {
9368   llvm::SmallVector<Expr *, 16> Vars;
9369   Vars.reserve(C->varlist_size());
9370   for (auto *VE : C->varlists()) {
9371     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9372     if (EVar.isInvalid())
9373       return nullptr;
9374     Vars.push_back(EVar.get());
9375   }
9376   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9377   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9378 }
9379 
9380 template <typename Derived>
9381 OMPClause *
9382 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9383   llvm::SmallVector<Expr *, 16> Vars;
9384   Vars.reserve(C->varlist_size());
9385   for (auto *VE : C->varlists()) {
9386     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9387     if (EVar.isInvalid())
9388       return nullptr;
9389     Vars.push_back(EVar.get());
9390   }
9391   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9392   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9393 }
9394 
9395 template <typename Derived>
9396 OMPClause *
9397 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
9398   llvm::SmallVector<Expr *, 16> Vars;
9399   Vars.reserve(C->varlist_size());
9400   for (auto *VE : C->varlists()) {
9401     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9402     if (EVar.isInvalid())
9403       return nullptr;
9404     Vars.push_back(EVar.get());
9405   }
9406   return getDerived().RebuildOMPNontemporalClause(
9407       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9408 }
9409 
9410 //===----------------------------------------------------------------------===//
9411 // Expression transformation
9412 //===----------------------------------------------------------------------===//
9413 template<typename Derived>
9414 ExprResult
9415 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9416   return TransformExpr(E->getSubExpr());
9417 }
9418 
9419 template<typename Derived>
9420 ExprResult
9421 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9422   if (!E->isTypeDependent())
9423     return E;
9424 
9425   return getDerived().RebuildPredefinedExpr(E->getLocation(),
9426                                             E->getIdentKind());
9427 }
9428 
9429 template<typename Derived>
9430 ExprResult
9431 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9432   NestedNameSpecifierLoc QualifierLoc;
9433   if (E->getQualifierLoc()) {
9434     QualifierLoc
9435       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9436     if (!QualifierLoc)
9437       return ExprError();
9438   }
9439 
9440   ValueDecl *ND
9441     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9442                                                          E->getDecl()));
9443   if (!ND)
9444     return ExprError();
9445 
9446   NamedDecl *Found = ND;
9447   if (E->getFoundDecl() != E->getDecl()) {
9448     Found = cast_or_null<NamedDecl>(
9449         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9450     if (!Found)
9451       return ExprError();
9452   }
9453 
9454   DeclarationNameInfo NameInfo = E->getNameInfo();
9455   if (NameInfo.getName()) {
9456     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9457     if (!NameInfo.getName())
9458       return ExprError();
9459   }
9460 
9461   if (!getDerived().AlwaysRebuild() &&
9462       QualifierLoc == E->getQualifierLoc() &&
9463       ND == E->getDecl() &&
9464       Found == E->getFoundDecl() &&
9465       NameInfo.getName() == E->getDecl()->getDeclName() &&
9466       !E->hasExplicitTemplateArgs()) {
9467 
9468     // Mark it referenced in the new context regardless.
9469     // FIXME: this is a bit instantiation-specific.
9470     SemaRef.MarkDeclRefReferenced(E);
9471 
9472     return E;
9473   }
9474 
9475   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9476   if (E->hasExplicitTemplateArgs()) {
9477     TemplateArgs = &TransArgs;
9478     TransArgs.setLAngleLoc(E->getLAngleLoc());
9479     TransArgs.setRAngleLoc(E->getRAngleLoc());
9480     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9481                                                 E->getNumTemplateArgs(),
9482                                                 TransArgs))
9483       return ExprError();
9484   }
9485 
9486   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9487                                          Found, TemplateArgs);
9488 }
9489 
9490 template<typename Derived>
9491 ExprResult
9492 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9493   return E;
9494 }
9495 
9496 template <typename Derived>
9497 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9498     FixedPointLiteral *E) {
9499   return E;
9500 }
9501 
9502 template<typename Derived>
9503 ExprResult
9504 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9505   return E;
9506 }
9507 
9508 template<typename Derived>
9509 ExprResult
9510 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9511   return E;
9512 }
9513 
9514 template<typename Derived>
9515 ExprResult
9516 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9517   return E;
9518 }
9519 
9520 template<typename Derived>
9521 ExprResult
9522 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9523   return E;
9524 }
9525 
9526 template<typename Derived>
9527 ExprResult
9528 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9529   if (FunctionDecl *FD = E->getDirectCallee())
9530     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9531   return SemaRef.MaybeBindToTemporary(E);
9532 }
9533 
9534 template<typename Derived>
9535 ExprResult
9536 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9537   ExprResult ControllingExpr =
9538     getDerived().TransformExpr(E->getControllingExpr());
9539   if (ControllingExpr.isInvalid())
9540     return ExprError();
9541 
9542   SmallVector<Expr *, 4> AssocExprs;
9543   SmallVector<TypeSourceInfo *, 4> AssocTypes;
9544   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
9545     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9546     if (TSI) {
9547       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9548       if (!AssocType)
9549         return ExprError();
9550       AssocTypes.push_back(AssocType);
9551     } else {
9552       AssocTypes.push_back(nullptr);
9553     }
9554 
9555     ExprResult AssocExpr =
9556         getDerived().TransformExpr(Assoc.getAssociationExpr());
9557     if (AssocExpr.isInvalid())
9558       return ExprError();
9559     AssocExprs.push_back(AssocExpr.get());
9560   }
9561 
9562   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9563                                                   E->getDefaultLoc(),
9564                                                   E->getRParenLoc(),
9565                                                   ControllingExpr.get(),
9566                                                   AssocTypes,
9567                                                   AssocExprs);
9568 }
9569 
9570 template<typename Derived>
9571 ExprResult
9572 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9573   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9574   if (SubExpr.isInvalid())
9575     return ExprError();
9576 
9577   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9578     return E;
9579 
9580   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9581                                        E->getRParen());
9582 }
9583 
9584 /// The operand of a unary address-of operator has special rules: it's
9585 /// allowed to refer to a non-static member of a class even if there's no 'this'
9586 /// object available.
9587 template<typename Derived>
9588 ExprResult
9589 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9590   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9591     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9592   else
9593     return getDerived().TransformExpr(E);
9594 }
9595 
9596 template<typename Derived>
9597 ExprResult
9598 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9599   ExprResult SubExpr;
9600   if (E->getOpcode() == UO_AddrOf)
9601     SubExpr = TransformAddressOfOperand(E->getSubExpr());
9602   else
9603     SubExpr = TransformExpr(E->getSubExpr());
9604   if (SubExpr.isInvalid())
9605     return ExprError();
9606 
9607   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9608     return E;
9609 
9610   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9611                                            E->getOpcode(),
9612                                            SubExpr.get());
9613 }
9614 
9615 template<typename Derived>
9616 ExprResult
9617 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9618   // Transform the type.
9619   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9620   if (!Type)
9621     return ExprError();
9622 
9623   // Transform all of the components into components similar to what the
9624   // parser uses.
9625   // FIXME: It would be slightly more efficient in the non-dependent case to
9626   // just map FieldDecls, rather than requiring the rebuilder to look for
9627   // the fields again. However, __builtin_offsetof is rare enough in
9628   // template code that we don't care.
9629   bool ExprChanged = false;
9630   typedef Sema::OffsetOfComponent Component;
9631   SmallVector<Component, 4> Components;
9632   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9633     const OffsetOfNode &ON = E->getComponent(I);
9634     Component Comp;
9635     Comp.isBrackets = true;
9636     Comp.LocStart = ON.getSourceRange().getBegin();
9637     Comp.LocEnd = ON.getSourceRange().getEnd();
9638     switch (ON.getKind()) {
9639     case OffsetOfNode::Array: {
9640       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9641       ExprResult Index = getDerived().TransformExpr(FromIndex);
9642       if (Index.isInvalid())
9643         return ExprError();
9644 
9645       ExprChanged = ExprChanged || Index.get() != FromIndex;
9646       Comp.isBrackets = true;
9647       Comp.U.E = Index.get();
9648       break;
9649     }
9650 
9651     case OffsetOfNode::Field:
9652     case OffsetOfNode::Identifier:
9653       Comp.isBrackets = false;
9654       Comp.U.IdentInfo = ON.getFieldName();
9655       if (!Comp.U.IdentInfo)
9656         continue;
9657 
9658       break;
9659 
9660     case OffsetOfNode::Base:
9661       // Will be recomputed during the rebuild.
9662       continue;
9663     }
9664 
9665     Components.push_back(Comp);
9666   }
9667 
9668   // If nothing changed, retain the existing expression.
9669   if (!getDerived().AlwaysRebuild() &&
9670       Type == E->getTypeSourceInfo() &&
9671       !ExprChanged)
9672     return E;
9673 
9674   // Build a new offsetof expression.
9675   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9676                                           Components, E->getRParenLoc());
9677 }
9678 
9679 template<typename Derived>
9680 ExprResult
9681 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9682   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9683          "opaque value expression requires transformation");
9684   return E;
9685 }
9686 
9687 template<typename Derived>
9688 ExprResult
9689 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9690   return E;
9691 }
9692 
9693 template<typename Derived>
9694 ExprResult
9695 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9696   // Rebuild the syntactic form.  The original syntactic form has
9697   // opaque-value expressions in it, so strip those away and rebuild
9698   // the result.  This is a really awful way of doing this, but the
9699   // better solution (rebuilding the semantic expressions and
9700   // rebinding OVEs as necessary) doesn't work; we'd need
9701   // TreeTransform to not strip away implicit conversions.
9702   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9703   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9704   if (result.isInvalid()) return ExprError();
9705 
9706   // If that gives us a pseudo-object result back, the pseudo-object
9707   // expression must have been an lvalue-to-rvalue conversion which we
9708   // should reapply.
9709   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9710     result = SemaRef.checkPseudoObjectRValue(result.get());
9711 
9712   return result;
9713 }
9714 
9715 template<typename Derived>
9716 ExprResult
9717 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9718                                                 UnaryExprOrTypeTraitExpr *E) {
9719   if (E->isArgumentType()) {
9720     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9721 
9722     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9723     if (!NewT)
9724       return ExprError();
9725 
9726     if (!getDerived().AlwaysRebuild() && OldT == NewT)
9727       return E;
9728 
9729     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9730                                                     E->getKind(),
9731                                                     E->getSourceRange());
9732   }
9733 
9734   // C++0x [expr.sizeof]p1:
9735   //   The operand is either an expression, which is an unevaluated operand
9736   //   [...]
9737   EnterExpressionEvaluationContext Unevaluated(
9738       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9739       Sema::ReuseLambdaContextDecl);
9740 
9741   // Try to recover if we have something like sizeof(T::X) where X is a type.
9742   // Notably, there must be *exactly* one set of parens if X is a type.
9743   TypeSourceInfo *RecoveryTSI = nullptr;
9744   ExprResult SubExpr;
9745   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9746   if (auto *DRE =
9747           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9748     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9749         PE, DRE, false, &RecoveryTSI);
9750   else
9751     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9752 
9753   if (RecoveryTSI) {
9754     return getDerived().RebuildUnaryExprOrTypeTrait(
9755         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9756   } else if (SubExpr.isInvalid())
9757     return ExprError();
9758 
9759   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9760     return E;
9761 
9762   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9763                                                   E->getOperatorLoc(),
9764                                                   E->getKind(),
9765                                                   E->getSourceRange());
9766 }
9767 
9768 template<typename Derived>
9769 ExprResult
9770 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9771   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9772   if (LHS.isInvalid())
9773     return ExprError();
9774 
9775   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9776   if (RHS.isInvalid())
9777     return ExprError();
9778 
9779 
9780   if (!getDerived().AlwaysRebuild() &&
9781       LHS.get() == E->getLHS() &&
9782       RHS.get() == E->getRHS())
9783     return E;
9784 
9785   return getDerived().RebuildArraySubscriptExpr(
9786       LHS.get(),
9787       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9788 }
9789 
9790 template <typename Derived>
9791 ExprResult
9792 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9793   ExprResult Base = getDerived().TransformExpr(E->getBase());
9794   if (Base.isInvalid())
9795     return ExprError();
9796 
9797   ExprResult LowerBound;
9798   if (E->getLowerBound()) {
9799     LowerBound = getDerived().TransformExpr(E->getLowerBound());
9800     if (LowerBound.isInvalid())
9801       return ExprError();
9802   }
9803 
9804   ExprResult Length;
9805   if (E->getLength()) {
9806     Length = getDerived().TransformExpr(E->getLength());
9807     if (Length.isInvalid())
9808       return ExprError();
9809   }
9810 
9811   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9812       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9813     return E;
9814 
9815   return getDerived().RebuildOMPArraySectionExpr(
9816       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9817       Length.get(), E->getRBracketLoc());
9818 }
9819 
9820 template<typename Derived>
9821 ExprResult
9822 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9823   // Transform the callee.
9824   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9825   if (Callee.isInvalid())
9826     return ExprError();
9827 
9828   // Transform arguments.
9829   bool ArgChanged = false;
9830   SmallVector<Expr*, 8> Args;
9831   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9832                                   &ArgChanged))
9833     return ExprError();
9834 
9835   if (!getDerived().AlwaysRebuild() &&
9836       Callee.get() == E->getCallee() &&
9837       !ArgChanged)
9838     return SemaRef.MaybeBindToTemporary(E);
9839 
9840   // FIXME: Wrong source location information for the '('.
9841   SourceLocation FakeLParenLoc
9842     = ((Expr *)Callee.get())->getSourceRange().getBegin();
9843   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9844                                       Args,
9845                                       E->getRParenLoc());
9846 }
9847 
9848 template<typename Derived>
9849 ExprResult
9850 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9851   ExprResult Base = getDerived().TransformExpr(E->getBase());
9852   if (Base.isInvalid())
9853     return ExprError();
9854 
9855   NestedNameSpecifierLoc QualifierLoc;
9856   if (E->hasQualifier()) {
9857     QualifierLoc
9858       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9859 
9860     if (!QualifierLoc)
9861       return ExprError();
9862   }
9863   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9864 
9865   ValueDecl *Member
9866     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9867                                                          E->getMemberDecl()));
9868   if (!Member)
9869     return ExprError();
9870 
9871   NamedDecl *FoundDecl = E->getFoundDecl();
9872   if (FoundDecl == E->getMemberDecl()) {
9873     FoundDecl = Member;
9874   } else {
9875     FoundDecl = cast_or_null<NamedDecl>(
9876                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9877     if (!FoundDecl)
9878       return ExprError();
9879   }
9880 
9881   if (!getDerived().AlwaysRebuild() &&
9882       Base.get() == E->getBase() &&
9883       QualifierLoc == E->getQualifierLoc() &&
9884       Member == E->getMemberDecl() &&
9885       FoundDecl == E->getFoundDecl() &&
9886       !E->hasExplicitTemplateArgs()) {
9887 
9888     // Mark it referenced in the new context regardless.
9889     // FIXME: this is a bit instantiation-specific.
9890     SemaRef.MarkMemberReferenced(E);
9891 
9892     return E;
9893   }
9894 
9895   TemplateArgumentListInfo TransArgs;
9896   if (E->hasExplicitTemplateArgs()) {
9897     TransArgs.setLAngleLoc(E->getLAngleLoc());
9898     TransArgs.setRAngleLoc(E->getRAngleLoc());
9899     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9900                                                 E->getNumTemplateArgs(),
9901                                                 TransArgs))
9902       return ExprError();
9903   }
9904 
9905   // FIXME: Bogus source location for the operator
9906   SourceLocation FakeOperatorLoc =
9907       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9908 
9909   // FIXME: to do this check properly, we will need to preserve the
9910   // first-qualifier-in-scope here, just in case we had a dependent
9911   // base (and therefore couldn't do the check) and a
9912   // nested-name-qualifier (and therefore could do the lookup).
9913   NamedDecl *FirstQualifierInScope = nullptr;
9914   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9915   if (MemberNameInfo.getName()) {
9916     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9917     if (!MemberNameInfo.getName())
9918       return ExprError();
9919   }
9920 
9921   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9922                                         E->isArrow(),
9923                                         QualifierLoc,
9924                                         TemplateKWLoc,
9925                                         MemberNameInfo,
9926                                         Member,
9927                                         FoundDecl,
9928                                         (E->hasExplicitTemplateArgs()
9929                                            ? &TransArgs : nullptr),
9930                                         FirstQualifierInScope);
9931 }
9932 
9933 template<typename Derived>
9934 ExprResult
9935 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9936   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9937   if (LHS.isInvalid())
9938     return ExprError();
9939 
9940   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9941   if (RHS.isInvalid())
9942     return ExprError();
9943 
9944   if (!getDerived().AlwaysRebuild() &&
9945       LHS.get() == E->getLHS() &&
9946       RHS.get() == E->getRHS())
9947     return E;
9948 
9949   Sema::FPContractStateRAII FPContractState(getSema());
9950   getSema().FPFeatures = E->getFPFeatures();
9951 
9952   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9953                                             LHS.get(), RHS.get());
9954 }
9955 
9956 template <typename Derived>
9957 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
9958     CXXRewrittenBinaryOperator *E) {
9959   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
9960 
9961   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
9962   if (LHS.isInvalid())
9963     return ExprError();
9964 
9965   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
9966   if (RHS.isInvalid())
9967     return ExprError();
9968 
9969   if (!getDerived().AlwaysRebuild() &&
9970       LHS.get() == Decomp.LHS &&
9971       RHS.get() == Decomp.RHS)
9972     return E;
9973 
9974   // Extract the already-resolved callee declarations so that we can restrict
9975   // ourselves to using them as the unqualified lookup results when rebuilding.
9976   UnresolvedSet<2> UnqualLookups;
9977   Expr *PossibleBinOps[] = {E->getSemanticForm(),
9978                             const_cast<Expr *>(Decomp.InnerBinOp)};
9979   for (Expr *PossibleBinOp : PossibleBinOps) {
9980     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
9981     if (!Op)
9982       continue;
9983     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
9984     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
9985       continue;
9986 
9987     // Transform the callee in case we built a call to a local extern
9988     // declaration.
9989     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
9990         E->getOperatorLoc(), Callee->getFoundDecl()));
9991     if (!Found)
9992       return ExprError();
9993     UnqualLookups.addDecl(Found);
9994   }
9995 
9996   return getDerived().RebuildCXXRewrittenBinaryOperator(
9997       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
9998 }
9999 
10000 template<typename Derived>
10001 ExprResult
10002 TreeTransform<Derived>::TransformCompoundAssignOperator(
10003                                                       CompoundAssignOperator *E) {
10004   return getDerived().TransformBinaryOperator(E);
10005 }
10006 
10007 template<typename Derived>
10008 ExprResult TreeTransform<Derived>::
10009 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
10010   // Just rebuild the common and RHS expressions and see whether we
10011   // get any changes.
10012 
10013   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
10014   if (commonExpr.isInvalid())
10015     return ExprError();
10016 
10017   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
10018   if (rhs.isInvalid())
10019     return ExprError();
10020 
10021   if (!getDerived().AlwaysRebuild() &&
10022       commonExpr.get() == e->getCommon() &&
10023       rhs.get() == e->getFalseExpr())
10024     return e;
10025 
10026   return getDerived().RebuildConditionalOperator(commonExpr.get(),
10027                                                  e->getQuestionLoc(),
10028                                                  nullptr,
10029                                                  e->getColonLoc(),
10030                                                  rhs.get());
10031 }
10032 
10033 template<typename Derived>
10034 ExprResult
10035 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
10036   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10037   if (Cond.isInvalid())
10038     return ExprError();
10039 
10040   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10041   if (LHS.isInvalid())
10042     return ExprError();
10043 
10044   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10045   if (RHS.isInvalid())
10046     return ExprError();
10047 
10048   if (!getDerived().AlwaysRebuild() &&
10049       Cond.get() == E->getCond() &&
10050       LHS.get() == E->getLHS() &&
10051       RHS.get() == E->getRHS())
10052     return E;
10053 
10054   return getDerived().RebuildConditionalOperator(Cond.get(),
10055                                                  E->getQuestionLoc(),
10056                                                  LHS.get(),
10057                                                  E->getColonLoc(),
10058                                                  RHS.get());
10059 }
10060 
10061 template<typename Derived>
10062 ExprResult
10063 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
10064   // Implicit casts are eliminated during transformation, since they
10065   // will be recomputed by semantic analysis after transformation.
10066   return getDerived().TransformExpr(E->getSubExprAsWritten());
10067 }
10068 
10069 template<typename Derived>
10070 ExprResult
10071 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
10072   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10073   if (!Type)
10074     return ExprError();
10075 
10076   ExprResult SubExpr
10077     = getDerived().TransformExpr(E->getSubExprAsWritten());
10078   if (SubExpr.isInvalid())
10079     return ExprError();
10080 
10081   if (!getDerived().AlwaysRebuild() &&
10082       Type == E->getTypeInfoAsWritten() &&
10083       SubExpr.get() == E->getSubExpr())
10084     return E;
10085 
10086   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
10087                                             Type,
10088                                             E->getRParenLoc(),
10089                                             SubExpr.get());
10090 }
10091 
10092 template<typename Derived>
10093 ExprResult
10094 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
10095   TypeSourceInfo *OldT = E->getTypeSourceInfo();
10096   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10097   if (!NewT)
10098     return ExprError();
10099 
10100   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
10101   if (Init.isInvalid())
10102     return ExprError();
10103 
10104   if (!getDerived().AlwaysRebuild() &&
10105       OldT == NewT &&
10106       Init.get() == E->getInitializer())
10107     return SemaRef.MaybeBindToTemporary(E);
10108 
10109   // Note: the expression type doesn't necessarily match the
10110   // type-as-written, but that's okay, because it should always be
10111   // derivable from the initializer.
10112 
10113   return getDerived().RebuildCompoundLiteralExpr(
10114       E->getLParenLoc(), NewT,
10115       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
10116 }
10117 
10118 template<typename Derived>
10119 ExprResult
10120 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
10121   ExprResult Base = getDerived().TransformExpr(E->getBase());
10122   if (Base.isInvalid())
10123     return ExprError();
10124 
10125   if (!getDerived().AlwaysRebuild() &&
10126       Base.get() == E->getBase())
10127     return E;
10128 
10129   // FIXME: Bad source location
10130   SourceLocation FakeOperatorLoc =
10131       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
10132   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
10133                                                   E->getAccessorLoc(),
10134                                                   E->getAccessor());
10135 }
10136 
10137 template<typename Derived>
10138 ExprResult
10139 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
10140   if (InitListExpr *Syntactic = E->getSyntacticForm())
10141     E = Syntactic;
10142 
10143   bool InitChanged = false;
10144 
10145   EnterExpressionEvaluationContext Context(
10146       getSema(), EnterExpressionEvaluationContext::InitList);
10147 
10148   SmallVector<Expr*, 4> Inits;
10149   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
10150                                   Inits, &InitChanged))
10151     return ExprError();
10152 
10153   if (!getDerived().AlwaysRebuild() && !InitChanged) {
10154     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
10155     // in some cases. We can't reuse it in general, because the syntactic and
10156     // semantic forms are linked, and we can't know that semantic form will
10157     // match even if the syntactic form does.
10158   }
10159 
10160   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
10161                                       E->getRBraceLoc());
10162 }
10163 
10164 template<typename Derived>
10165 ExprResult
10166 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
10167   Designation Desig;
10168 
10169   // transform the initializer value
10170   ExprResult Init = getDerived().TransformExpr(E->getInit());
10171   if (Init.isInvalid())
10172     return ExprError();
10173 
10174   // transform the designators.
10175   SmallVector<Expr*, 4> ArrayExprs;
10176   bool ExprChanged = false;
10177   for (const DesignatedInitExpr::Designator &D : E->designators()) {
10178     if (D.isFieldDesignator()) {
10179       Desig.AddDesignator(Designator::getField(D.getFieldName(),
10180                                                D.getDotLoc(),
10181                                                D.getFieldLoc()));
10182       if (D.getField()) {
10183         FieldDecl *Field = cast_or_null<FieldDecl>(
10184             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
10185         if (Field != D.getField())
10186           // Rebuild the expression when the transformed FieldDecl is
10187           // different to the already assigned FieldDecl.
10188           ExprChanged = true;
10189       } else {
10190         // Ensure that the designator expression is rebuilt when there isn't
10191         // a resolved FieldDecl in the designator as we don't want to assign
10192         // a FieldDecl to a pattern designator that will be instantiated again.
10193         ExprChanged = true;
10194       }
10195       continue;
10196     }
10197 
10198     if (D.isArrayDesignator()) {
10199       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
10200       if (Index.isInvalid())
10201         return ExprError();
10202 
10203       Desig.AddDesignator(
10204           Designator::getArray(Index.get(), D.getLBracketLoc()));
10205 
10206       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
10207       ArrayExprs.push_back(Index.get());
10208       continue;
10209     }
10210 
10211     assert(D.isArrayRangeDesignator() && "New kind of designator?");
10212     ExprResult Start
10213       = getDerived().TransformExpr(E->getArrayRangeStart(D));
10214     if (Start.isInvalid())
10215       return ExprError();
10216 
10217     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
10218     if (End.isInvalid())
10219       return ExprError();
10220 
10221     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
10222                                                   End.get(),
10223                                                   D.getLBracketLoc(),
10224                                                   D.getEllipsisLoc()));
10225 
10226     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
10227                   End.get() != E->getArrayRangeEnd(D);
10228 
10229     ArrayExprs.push_back(Start.get());
10230     ArrayExprs.push_back(End.get());
10231   }
10232 
10233   if (!getDerived().AlwaysRebuild() &&
10234       Init.get() == E->getInit() &&
10235       !ExprChanged)
10236     return E;
10237 
10238   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
10239                                                 E->getEqualOrColonLoc(),
10240                                                 E->usesGNUSyntax(), Init.get());
10241 }
10242 
10243 // Seems that if TransformInitListExpr() only works on the syntactic form of an
10244 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
10245 template<typename Derived>
10246 ExprResult
10247 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
10248     DesignatedInitUpdateExpr *E) {
10249   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
10250                    "initializer");
10251   return ExprError();
10252 }
10253 
10254 template<typename Derived>
10255 ExprResult
10256 TreeTransform<Derived>::TransformNoInitExpr(
10257     NoInitExpr *E) {
10258   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
10259   return ExprError();
10260 }
10261 
10262 template<typename Derived>
10263 ExprResult
10264 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
10265   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
10266   return ExprError();
10267 }
10268 
10269 template<typename Derived>
10270 ExprResult
10271 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
10272   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
10273   return ExprError();
10274 }
10275 
10276 template<typename Derived>
10277 ExprResult
10278 TreeTransform<Derived>::TransformImplicitValueInitExpr(
10279                                                      ImplicitValueInitExpr *E) {
10280   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
10281 
10282   // FIXME: Will we ever have proper type location here? Will we actually
10283   // need to transform the type?
10284   QualType T = getDerived().TransformType(E->getType());
10285   if (T.isNull())
10286     return ExprError();
10287 
10288   if (!getDerived().AlwaysRebuild() &&
10289       T == E->getType())
10290     return E;
10291 
10292   return getDerived().RebuildImplicitValueInitExpr(T);
10293 }
10294 
10295 template<typename Derived>
10296 ExprResult
10297 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10298   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10299   if (!TInfo)
10300     return ExprError();
10301 
10302   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10303   if (SubExpr.isInvalid())
10304     return ExprError();
10305 
10306   if (!getDerived().AlwaysRebuild() &&
10307       TInfo == E->getWrittenTypeInfo() &&
10308       SubExpr.get() == E->getSubExpr())
10309     return E;
10310 
10311   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10312                                        TInfo, E->getRParenLoc());
10313 }
10314 
10315 template<typename Derived>
10316 ExprResult
10317 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10318   bool ArgumentChanged = false;
10319   SmallVector<Expr*, 4> Inits;
10320   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10321                      &ArgumentChanged))
10322     return ExprError();
10323 
10324   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10325                                            Inits,
10326                                            E->getRParenLoc());
10327 }
10328 
10329 /// Transform an address-of-label expression.
10330 ///
10331 /// By default, the transformation of an address-of-label expression always
10332 /// rebuilds the expression, so that the label identifier can be resolved to
10333 /// the corresponding label statement by semantic analysis.
10334 template<typename Derived>
10335 ExprResult
10336 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10337   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10338                                         E->getLabel());
10339   if (!LD)
10340     return ExprError();
10341 
10342   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10343                                            cast<LabelDecl>(LD));
10344 }
10345 
10346 template<typename Derived>
10347 ExprResult
10348 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10349   SemaRef.ActOnStartStmtExpr();
10350   StmtResult SubStmt
10351     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10352   if (SubStmt.isInvalid()) {
10353     SemaRef.ActOnStmtExprError();
10354     return ExprError();
10355   }
10356 
10357   unsigned OldDepth = E->getTemplateDepth();
10358   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
10359 
10360   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
10361       SubStmt.get() == E->getSubStmt()) {
10362     // Calling this an 'error' is unintuitive, but it does the right thing.
10363     SemaRef.ActOnStmtExprError();
10364     return SemaRef.MaybeBindToTemporary(E);
10365   }
10366 
10367   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
10368                                       E->getRParenLoc(), NewDepth);
10369 }
10370 
10371 template<typename Derived>
10372 ExprResult
10373 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10374   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10375   if (Cond.isInvalid())
10376     return ExprError();
10377 
10378   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10379   if (LHS.isInvalid())
10380     return ExprError();
10381 
10382   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10383   if (RHS.isInvalid())
10384     return ExprError();
10385 
10386   if (!getDerived().AlwaysRebuild() &&
10387       Cond.get() == E->getCond() &&
10388       LHS.get() == E->getLHS() &&
10389       RHS.get() == E->getRHS())
10390     return E;
10391 
10392   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10393                                         Cond.get(), LHS.get(), RHS.get(),
10394                                         E->getRParenLoc());
10395 }
10396 
10397 template<typename Derived>
10398 ExprResult
10399 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10400   return E;
10401 }
10402 
10403 template<typename Derived>
10404 ExprResult
10405 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10406   switch (E->getOperator()) {
10407   case OO_New:
10408   case OO_Delete:
10409   case OO_Array_New:
10410   case OO_Array_Delete:
10411     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
10412 
10413   case OO_Call: {
10414     // This is a call to an object's operator().
10415     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
10416 
10417     // Transform the object itself.
10418     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10419     if (Object.isInvalid())
10420       return ExprError();
10421 
10422     // FIXME: Poor location information
10423     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10424         static_cast<Expr *>(Object.get())->getEndLoc());
10425 
10426     // Transform the call arguments.
10427     SmallVector<Expr*, 8> Args;
10428     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10429                                     Args))
10430       return ExprError();
10431 
10432     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10433                                         E->getEndLoc());
10434   }
10435 
10436 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10437   case OO_##Name:
10438 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10439 #include "clang/Basic/OperatorKinds.def"
10440   case OO_Subscript:
10441     // Handled below.
10442     break;
10443 
10444   case OO_Conditional:
10445     llvm_unreachable("conditional operator is not actually overloadable");
10446 
10447   case OO_None:
10448   case NUM_OVERLOADED_OPERATORS:
10449     llvm_unreachable("not an overloaded operator?");
10450   }
10451 
10452   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10453   if (Callee.isInvalid())
10454     return ExprError();
10455 
10456   ExprResult First;
10457   if (E->getOperator() == OO_Amp)
10458     First = getDerived().TransformAddressOfOperand(E->getArg(0));
10459   else
10460     First = getDerived().TransformExpr(E->getArg(0));
10461   if (First.isInvalid())
10462     return ExprError();
10463 
10464   ExprResult Second;
10465   if (E->getNumArgs() == 2) {
10466     Second = getDerived().TransformExpr(E->getArg(1));
10467     if (Second.isInvalid())
10468       return ExprError();
10469   }
10470 
10471   if (!getDerived().AlwaysRebuild() &&
10472       Callee.get() == E->getCallee() &&
10473       First.get() == E->getArg(0) &&
10474       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10475     return SemaRef.MaybeBindToTemporary(E);
10476 
10477   Sema::FPContractStateRAII FPContractState(getSema());
10478   getSema().FPFeatures = E->getFPFeatures();
10479 
10480   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10481                                                  E->getOperatorLoc(),
10482                                                  Callee.get(),
10483                                                  First.get(),
10484                                                  Second.get());
10485 }
10486 
10487 template<typename Derived>
10488 ExprResult
10489 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10490   return getDerived().TransformCallExpr(E);
10491 }
10492 
10493 template <typename Derived>
10494 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10495   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10496                          getSema().CurContext != E->getParentContext();
10497 
10498   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10499     return E;
10500 
10501   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10502                                            E->getEndLoc(),
10503                                            getSema().CurContext);
10504 }
10505 
10506 template<typename Derived>
10507 ExprResult
10508 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10509   // Transform the callee.
10510   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10511   if (Callee.isInvalid())
10512     return ExprError();
10513 
10514   // Transform exec config.
10515   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10516   if (EC.isInvalid())
10517     return ExprError();
10518 
10519   // Transform arguments.
10520   bool ArgChanged = false;
10521   SmallVector<Expr*, 8> Args;
10522   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10523                                   &ArgChanged))
10524     return ExprError();
10525 
10526   if (!getDerived().AlwaysRebuild() &&
10527       Callee.get() == E->getCallee() &&
10528       !ArgChanged)
10529     return SemaRef.MaybeBindToTemporary(E);
10530 
10531   // FIXME: Wrong source location information for the '('.
10532   SourceLocation FakeLParenLoc
10533     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10534   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10535                                       Args,
10536                                       E->getRParenLoc(), EC.get());
10537 }
10538 
10539 template<typename Derived>
10540 ExprResult
10541 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10542   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10543   if (!Type)
10544     return ExprError();
10545 
10546   ExprResult SubExpr
10547     = getDerived().TransformExpr(E->getSubExprAsWritten());
10548   if (SubExpr.isInvalid())
10549     return ExprError();
10550 
10551   if (!getDerived().AlwaysRebuild() &&
10552       Type == E->getTypeInfoAsWritten() &&
10553       SubExpr.get() == E->getSubExpr())
10554     return E;
10555   return getDerived().RebuildCXXNamedCastExpr(
10556       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10557       Type, E->getAngleBrackets().getEnd(),
10558       // FIXME. this should be '(' location
10559       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10560 }
10561 
10562 template<typename Derived>
10563 ExprResult
10564 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10565   TypeSourceInfo *TSI =
10566       getDerived().TransformType(BCE->getTypeInfoAsWritten());
10567   if (!TSI)
10568     return ExprError();
10569 
10570   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10571   if (Sub.isInvalid())
10572     return ExprError();
10573 
10574   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10575                                                 Sub.get(), BCE->getEndLoc());
10576 }
10577 
10578 template<typename Derived>
10579 ExprResult
10580 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10581   return getDerived().TransformCXXNamedCastExpr(E);
10582 }
10583 
10584 template<typename Derived>
10585 ExprResult
10586 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10587   return getDerived().TransformCXXNamedCastExpr(E);
10588 }
10589 
10590 template<typename Derived>
10591 ExprResult
10592 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10593                                                       CXXReinterpretCastExpr *E) {
10594   return getDerived().TransformCXXNamedCastExpr(E);
10595 }
10596 
10597 template<typename Derived>
10598 ExprResult
10599 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10600   return getDerived().TransformCXXNamedCastExpr(E);
10601 }
10602 
10603 template<typename Derived>
10604 ExprResult
10605 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10606                                                      CXXFunctionalCastExpr *E) {
10607   TypeSourceInfo *Type =
10608       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10609   if (!Type)
10610     return ExprError();
10611 
10612   ExprResult SubExpr
10613     = getDerived().TransformExpr(E->getSubExprAsWritten());
10614   if (SubExpr.isInvalid())
10615     return ExprError();
10616 
10617   if (!getDerived().AlwaysRebuild() &&
10618       Type == E->getTypeInfoAsWritten() &&
10619       SubExpr.get() == E->getSubExpr())
10620     return E;
10621 
10622   return getDerived().RebuildCXXFunctionalCastExpr(Type,
10623                                                    E->getLParenLoc(),
10624                                                    SubExpr.get(),
10625                                                    E->getRParenLoc(),
10626                                                    E->isListInitialization());
10627 }
10628 
10629 template<typename Derived>
10630 ExprResult
10631 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10632   if (E->isTypeOperand()) {
10633     TypeSourceInfo *TInfo
10634       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10635     if (!TInfo)
10636       return ExprError();
10637 
10638     if (!getDerived().AlwaysRebuild() &&
10639         TInfo == E->getTypeOperandSourceInfo())
10640       return E;
10641 
10642     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10643                                              TInfo, E->getEndLoc());
10644   }
10645 
10646   // We don't know whether the subexpression is potentially evaluated until
10647   // after we perform semantic analysis.  We speculatively assume it is
10648   // unevaluated; it will get fixed later if the subexpression is in fact
10649   // potentially evaluated.
10650   EnterExpressionEvaluationContext Unevaluated(
10651       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10652       Sema::ReuseLambdaContextDecl);
10653 
10654   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10655   if (SubExpr.isInvalid())
10656     return ExprError();
10657 
10658   if (!getDerived().AlwaysRebuild() &&
10659       SubExpr.get() == E->getExprOperand())
10660     return E;
10661 
10662   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10663                                            SubExpr.get(), E->getEndLoc());
10664 }
10665 
10666 template<typename Derived>
10667 ExprResult
10668 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10669   if (E->isTypeOperand()) {
10670     TypeSourceInfo *TInfo
10671       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10672     if (!TInfo)
10673       return ExprError();
10674 
10675     if (!getDerived().AlwaysRebuild() &&
10676         TInfo == E->getTypeOperandSourceInfo())
10677       return E;
10678 
10679     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10680                                              TInfo, E->getEndLoc());
10681   }
10682 
10683   EnterExpressionEvaluationContext Unevaluated(
10684       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10685 
10686   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10687   if (SubExpr.isInvalid())
10688     return ExprError();
10689 
10690   if (!getDerived().AlwaysRebuild() &&
10691       SubExpr.get() == E->getExprOperand())
10692     return E;
10693 
10694   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10695                                            SubExpr.get(), E->getEndLoc());
10696 }
10697 
10698 template<typename Derived>
10699 ExprResult
10700 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10701   return E;
10702 }
10703 
10704 template<typename Derived>
10705 ExprResult
10706 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10707                                                      CXXNullPtrLiteralExpr *E) {
10708   return E;
10709 }
10710 
10711 template<typename Derived>
10712 ExprResult
10713 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10714   QualType T = getSema().getCurrentThisType();
10715 
10716   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10717     // Mark it referenced in the new context regardless.
10718     // FIXME: this is a bit instantiation-specific.
10719     getSema().MarkThisReferenced(E);
10720     return E;
10721   }
10722 
10723   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10724 }
10725 
10726 template<typename Derived>
10727 ExprResult
10728 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10729   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10730   if (SubExpr.isInvalid())
10731     return ExprError();
10732 
10733   if (!getDerived().AlwaysRebuild() &&
10734       SubExpr.get() == E->getSubExpr())
10735     return E;
10736 
10737   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10738                                           E->isThrownVariableInScope());
10739 }
10740 
10741 template<typename Derived>
10742 ExprResult
10743 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10744   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10745       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10746   if (!Param)
10747     return ExprError();
10748 
10749   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10750       E->getUsedContext() == SemaRef.CurContext)
10751     return E;
10752 
10753   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10754 }
10755 
10756 template<typename Derived>
10757 ExprResult
10758 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10759   FieldDecl *Field = cast_or_null<FieldDecl>(
10760       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10761   if (!Field)
10762     return ExprError();
10763 
10764   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10765       E->getUsedContext() == SemaRef.CurContext)
10766     return E;
10767 
10768   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10769 }
10770 
10771 template<typename Derived>
10772 ExprResult
10773 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10774                                                     CXXScalarValueInitExpr *E) {
10775   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10776   if (!T)
10777     return ExprError();
10778 
10779   if (!getDerived().AlwaysRebuild() &&
10780       T == E->getTypeSourceInfo())
10781     return E;
10782 
10783   return getDerived().RebuildCXXScalarValueInitExpr(T,
10784                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
10785                                                     E->getRParenLoc());
10786 }
10787 
10788 template<typename Derived>
10789 ExprResult
10790 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10791   // Transform the type that we're allocating
10792   TypeSourceInfo *AllocTypeInfo =
10793       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10794   if (!AllocTypeInfo)
10795     return ExprError();
10796 
10797   // Transform the size of the array we're allocating (if any).
10798   Optional<Expr *> ArraySize;
10799   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10800     ExprResult NewArraySize;
10801     if (*OldArraySize) {
10802       NewArraySize = getDerived().TransformExpr(*OldArraySize);
10803       if (NewArraySize.isInvalid())
10804         return ExprError();
10805     }
10806     ArraySize = NewArraySize.get();
10807   }
10808 
10809   // Transform the placement arguments (if any).
10810   bool ArgumentChanged = false;
10811   SmallVector<Expr*, 8> PlacementArgs;
10812   if (getDerived().TransformExprs(E->getPlacementArgs(),
10813                                   E->getNumPlacementArgs(), true,
10814                                   PlacementArgs, &ArgumentChanged))
10815     return ExprError();
10816 
10817   // Transform the initializer (if any).
10818   Expr *OldInit = E->getInitializer();
10819   ExprResult NewInit;
10820   if (OldInit)
10821     NewInit = getDerived().TransformInitializer(OldInit, true);
10822   if (NewInit.isInvalid())
10823     return ExprError();
10824 
10825   // Transform new operator and delete operator.
10826   FunctionDecl *OperatorNew = nullptr;
10827   if (E->getOperatorNew()) {
10828     OperatorNew = cast_or_null<FunctionDecl>(
10829         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10830     if (!OperatorNew)
10831       return ExprError();
10832   }
10833 
10834   FunctionDecl *OperatorDelete = nullptr;
10835   if (E->getOperatorDelete()) {
10836     OperatorDelete = cast_or_null<FunctionDecl>(
10837         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10838     if (!OperatorDelete)
10839       return ExprError();
10840   }
10841 
10842   if (!getDerived().AlwaysRebuild() &&
10843       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10844       ArraySize == E->getArraySize() &&
10845       NewInit.get() == OldInit &&
10846       OperatorNew == E->getOperatorNew() &&
10847       OperatorDelete == E->getOperatorDelete() &&
10848       !ArgumentChanged) {
10849     // Mark any declarations we need as referenced.
10850     // FIXME: instantiation-specific.
10851     if (OperatorNew)
10852       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10853     if (OperatorDelete)
10854       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10855 
10856     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10857       QualType ElementType
10858         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10859       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10860         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10861         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10862           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10863         }
10864       }
10865     }
10866 
10867     return E;
10868   }
10869 
10870   QualType AllocType = AllocTypeInfo->getType();
10871   if (!ArraySize) {
10872     // If no array size was specified, but the new expression was
10873     // instantiated with an array type (e.g., "new T" where T is
10874     // instantiated with "int[4]"), extract the outer bound from the
10875     // array type as our array size. We do this with constant and
10876     // dependently-sized array types.
10877     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10878     if (!ArrayT) {
10879       // Do nothing
10880     } else if (const ConstantArrayType *ConsArrayT
10881                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
10882       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10883                                          SemaRef.Context.getSizeType(),
10884                                          /*FIXME:*/ E->getBeginLoc());
10885       AllocType = ConsArrayT->getElementType();
10886     } else if (const DependentSizedArrayType *DepArrayT
10887                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10888       if (DepArrayT->getSizeExpr()) {
10889         ArraySize = DepArrayT->getSizeExpr();
10890         AllocType = DepArrayT->getElementType();
10891       }
10892     }
10893   }
10894 
10895   return getDerived().RebuildCXXNewExpr(
10896       E->getBeginLoc(), E->isGlobalNew(),
10897       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10898       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10899       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10900 }
10901 
10902 template<typename Derived>
10903 ExprResult
10904 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10905   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10906   if (Operand.isInvalid())
10907     return ExprError();
10908 
10909   // Transform the delete operator, if known.
10910   FunctionDecl *OperatorDelete = nullptr;
10911   if (E->getOperatorDelete()) {
10912     OperatorDelete = cast_or_null<FunctionDecl>(
10913         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10914     if (!OperatorDelete)
10915       return ExprError();
10916   }
10917 
10918   if (!getDerived().AlwaysRebuild() &&
10919       Operand.get() == E->getArgument() &&
10920       OperatorDelete == E->getOperatorDelete()) {
10921     // Mark any declarations we need as referenced.
10922     // FIXME: instantiation-specific.
10923     if (OperatorDelete)
10924       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10925 
10926     if (!E->getArgument()->isTypeDependent()) {
10927       QualType Destroyed = SemaRef.Context.getBaseElementType(
10928                                                          E->getDestroyedType());
10929       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10930         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10931         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10932                                        SemaRef.LookupDestructor(Record));
10933       }
10934     }
10935 
10936     return E;
10937   }
10938 
10939   return getDerived().RebuildCXXDeleteExpr(
10940       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10941 }
10942 
10943 template<typename Derived>
10944 ExprResult
10945 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10946                                                      CXXPseudoDestructorExpr *E) {
10947   ExprResult Base = getDerived().TransformExpr(E->getBase());
10948   if (Base.isInvalid())
10949     return ExprError();
10950 
10951   ParsedType ObjectTypePtr;
10952   bool MayBePseudoDestructor = false;
10953   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10954                                               E->getOperatorLoc(),
10955                                         E->isArrow()? tok::arrow : tok::period,
10956                                               ObjectTypePtr,
10957                                               MayBePseudoDestructor);
10958   if (Base.isInvalid())
10959     return ExprError();
10960 
10961   QualType ObjectType = ObjectTypePtr.get();
10962   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10963   if (QualifierLoc) {
10964     QualifierLoc
10965       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10966     if (!QualifierLoc)
10967       return ExprError();
10968   }
10969   CXXScopeSpec SS;
10970   SS.Adopt(QualifierLoc);
10971 
10972   PseudoDestructorTypeStorage Destroyed;
10973   if (E->getDestroyedTypeInfo()) {
10974     TypeSourceInfo *DestroyedTypeInfo
10975       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10976                                                 ObjectType, nullptr, SS);
10977     if (!DestroyedTypeInfo)
10978       return ExprError();
10979     Destroyed = DestroyedTypeInfo;
10980   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10981     // We aren't likely to be able to resolve the identifier down to a type
10982     // now anyway, so just retain the identifier.
10983     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10984                                             E->getDestroyedTypeLoc());
10985   } else {
10986     // Look for a destructor known with the given name.
10987     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10988                                               *E->getDestroyedTypeIdentifier(),
10989                                                 E->getDestroyedTypeLoc(),
10990                                                 /*Scope=*/nullptr,
10991                                                 SS, ObjectTypePtr,
10992                                                 false);
10993     if (!T)
10994       return ExprError();
10995 
10996     Destroyed
10997       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10998                                                  E->getDestroyedTypeLoc());
10999   }
11000 
11001   TypeSourceInfo *ScopeTypeInfo = nullptr;
11002   if (E->getScopeTypeInfo()) {
11003     CXXScopeSpec EmptySS;
11004     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
11005                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
11006     if (!ScopeTypeInfo)
11007       return ExprError();
11008   }
11009 
11010   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
11011                                                      E->getOperatorLoc(),
11012                                                      E->isArrow(),
11013                                                      SS,
11014                                                      ScopeTypeInfo,
11015                                                      E->getColonColonLoc(),
11016                                                      E->getTildeLoc(),
11017                                                      Destroyed);
11018 }
11019 
11020 template <typename Derived>
11021 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
11022                                                         bool RequiresADL,
11023                                                         LookupResult &R) {
11024   // Transform all the decls.
11025   bool AllEmptyPacks = true;
11026   for (auto *OldD : Old->decls()) {
11027     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
11028     if (!InstD) {
11029       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
11030       // This can happen because of dependent hiding.
11031       if (isa<UsingShadowDecl>(OldD))
11032         continue;
11033       else {
11034         R.clear();
11035         return true;
11036       }
11037     }
11038 
11039     // Expand using pack declarations.
11040     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
11041     ArrayRef<NamedDecl*> Decls = SingleDecl;
11042     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
11043       Decls = UPD->expansions();
11044 
11045     // Expand using declarations.
11046     for (auto *D : Decls) {
11047       if (auto *UD = dyn_cast<UsingDecl>(D)) {
11048         for (auto *SD : UD->shadows())
11049           R.addDecl(SD);
11050       } else {
11051         R.addDecl(D);
11052       }
11053     }
11054 
11055     AllEmptyPacks &= Decls.empty();
11056   };
11057 
11058   // C++ [temp.res]/8.4.2:
11059   //   The program is ill-formed, no diagnostic required, if [...] lookup for
11060   //   a name in the template definition found a using-declaration, but the
11061   //   lookup in the corresponding scope in the instantiation odoes not find
11062   //   any declarations because the using-declaration was a pack expansion and
11063   //   the corresponding pack is empty
11064   if (AllEmptyPacks && !RequiresADL) {
11065     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
11066         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
11067     return true;
11068   }
11069 
11070   // Resolve a kind, but don't do any further analysis.  If it's
11071   // ambiguous, the callee needs to deal with it.
11072   R.resolveKind();
11073   return false;
11074 }
11075 
11076 template<typename Derived>
11077 ExprResult
11078 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
11079                                                   UnresolvedLookupExpr *Old) {
11080   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
11081                  Sema::LookupOrdinaryName);
11082 
11083   // Transform the declaration set.
11084   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
11085     return ExprError();
11086 
11087   // Rebuild the nested-name qualifier, if present.
11088   CXXScopeSpec SS;
11089   if (Old->getQualifierLoc()) {
11090     NestedNameSpecifierLoc QualifierLoc
11091       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11092     if (!QualifierLoc)
11093       return ExprError();
11094 
11095     SS.Adopt(QualifierLoc);
11096   }
11097 
11098   if (Old->getNamingClass()) {
11099     CXXRecordDecl *NamingClass
11100       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11101                                                             Old->getNameLoc(),
11102                                                         Old->getNamingClass()));
11103     if (!NamingClass) {
11104       R.clear();
11105       return ExprError();
11106     }
11107 
11108     R.setNamingClass(NamingClass);
11109   }
11110 
11111   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11112 
11113   // If we have neither explicit template arguments, nor the template keyword,
11114   // it's a normal declaration name or member reference.
11115   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
11116     NamedDecl *D = R.getAsSingle<NamedDecl>();
11117     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
11118     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
11119     // give a good diagnostic.
11120     if (D && D->isCXXInstanceMember()) {
11121       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11122                                                      /*TemplateArgs=*/nullptr,
11123                                                      /*Scope=*/nullptr);
11124     }
11125 
11126     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
11127   }
11128 
11129   // If we have template arguments, rebuild them, then rebuild the
11130   // templateid expression.
11131   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
11132   if (Old->hasExplicitTemplateArgs() &&
11133       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11134                                               Old->getNumTemplateArgs(),
11135                                               TransArgs)) {
11136     R.clear();
11137     return ExprError();
11138   }
11139 
11140   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
11141                                             Old->requiresADL(), &TransArgs);
11142 }
11143 
11144 template<typename Derived>
11145 ExprResult
11146 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
11147   bool ArgChanged = false;
11148   SmallVector<TypeSourceInfo *, 4> Args;
11149   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
11150     TypeSourceInfo *From = E->getArg(I);
11151     TypeLoc FromTL = From->getTypeLoc();
11152     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
11153       TypeLocBuilder TLB;
11154       TLB.reserve(FromTL.getFullDataSize());
11155       QualType To = getDerived().TransformType(TLB, FromTL);
11156       if (To.isNull())
11157         return ExprError();
11158 
11159       if (To == From->getType())
11160         Args.push_back(From);
11161       else {
11162         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11163         ArgChanged = true;
11164       }
11165       continue;
11166     }
11167 
11168     ArgChanged = true;
11169 
11170     // We have a pack expansion. Instantiate it.
11171     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
11172     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
11173     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11174     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
11175 
11176     // Determine whether the set of unexpanded parameter packs can and should
11177     // be expanded.
11178     bool Expand = true;
11179     bool RetainExpansion = false;
11180     Optional<unsigned> OrigNumExpansions =
11181         ExpansionTL.getTypePtr()->getNumExpansions();
11182     Optional<unsigned> NumExpansions = OrigNumExpansions;
11183     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
11184                                              PatternTL.getSourceRange(),
11185                                              Unexpanded,
11186                                              Expand, RetainExpansion,
11187                                              NumExpansions))
11188       return ExprError();
11189 
11190     if (!Expand) {
11191       // The transform has determined that we should perform a simple
11192       // transformation on the pack expansion, producing another pack
11193       // expansion.
11194       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11195 
11196       TypeLocBuilder TLB;
11197       TLB.reserve(From->getTypeLoc().getFullDataSize());
11198 
11199       QualType To = getDerived().TransformType(TLB, PatternTL);
11200       if (To.isNull())
11201         return ExprError();
11202 
11203       To = getDerived().RebuildPackExpansionType(To,
11204                                                  PatternTL.getSourceRange(),
11205                                                  ExpansionTL.getEllipsisLoc(),
11206                                                  NumExpansions);
11207       if (To.isNull())
11208         return ExprError();
11209 
11210       PackExpansionTypeLoc ToExpansionTL
11211         = TLB.push<PackExpansionTypeLoc>(To);
11212       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11213       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11214       continue;
11215     }
11216 
11217     // Expand the pack expansion by substituting for each argument in the
11218     // pack(s).
11219     for (unsigned I = 0; I != *NumExpansions; ++I) {
11220       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
11221       TypeLocBuilder TLB;
11222       TLB.reserve(PatternTL.getFullDataSize());
11223       QualType To = getDerived().TransformType(TLB, PatternTL);
11224       if (To.isNull())
11225         return ExprError();
11226 
11227       if (To->containsUnexpandedParameterPack()) {
11228         To = getDerived().RebuildPackExpansionType(To,
11229                                                    PatternTL.getSourceRange(),
11230                                                    ExpansionTL.getEllipsisLoc(),
11231                                                    NumExpansions);
11232         if (To.isNull())
11233           return ExprError();
11234 
11235         PackExpansionTypeLoc ToExpansionTL
11236           = TLB.push<PackExpansionTypeLoc>(To);
11237         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11238       }
11239 
11240       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11241     }
11242 
11243     if (!RetainExpansion)
11244       continue;
11245 
11246     // If we're supposed to retain a pack expansion, do so by temporarily
11247     // forgetting the partially-substituted parameter pack.
11248     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11249 
11250     TypeLocBuilder TLB;
11251     TLB.reserve(From->getTypeLoc().getFullDataSize());
11252 
11253     QualType To = getDerived().TransformType(TLB, PatternTL);
11254     if (To.isNull())
11255       return ExprError();
11256 
11257     To = getDerived().RebuildPackExpansionType(To,
11258                                                PatternTL.getSourceRange(),
11259                                                ExpansionTL.getEllipsisLoc(),
11260                                                NumExpansions);
11261     if (To.isNull())
11262       return ExprError();
11263 
11264     PackExpansionTypeLoc ToExpansionTL
11265       = TLB.push<PackExpansionTypeLoc>(To);
11266     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11267     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11268   }
11269 
11270   if (!getDerived().AlwaysRebuild() && !ArgChanged)
11271     return E;
11272 
11273   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
11274                                        E->getEndLoc());
11275 }
11276 
11277 template<typename Derived>
11278 ExprResult
11279 TreeTransform<Derived>::TransformConceptSpecializationExpr(
11280                                                  ConceptSpecializationExpr *E) {
11281   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
11282   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
11283   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11284                                               Old->NumTemplateArgs, TransArgs))
11285     return ExprError();
11286 
11287   return getDerived().RebuildConceptSpecializationExpr(
11288       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
11289       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
11290       &TransArgs);
11291 }
11292 
11293 template<typename Derived>
11294 ExprResult
11295 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
11296   SmallVector<ParmVarDecl*, 4> TransParams;
11297   SmallVector<QualType, 4> TransParamTypes;
11298   Sema::ExtParameterInfoBuilder ExtParamInfos;
11299 
11300   // C++2a [expr.prim.req]p2
11301   // Expressions appearing within a requirement-body are unevaluated operands.
11302   EnterExpressionEvaluationContext Ctx(
11303       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11304 
11305   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
11306       getSema().Context, E->getBody()->getDeclContext(),
11307       E->getBody()->getBeginLoc());
11308 
11309   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
11310 
11311   if (getDerived().TransformFunctionTypeParams(E->getRequiresKWLoc(),
11312                                                E->getLocalParameters(),
11313                                                /*ParamTypes=*/nullptr,
11314                                                /*ParamInfos=*/nullptr,
11315                                                TransParamTypes, &TransParams,
11316                                                ExtParamInfos))
11317     return ExprError();
11318 
11319   for (ParmVarDecl *Param : TransParams)
11320     Param->setDeclContext(Body);
11321 
11322   SmallVector<concepts::Requirement *, 4> TransReqs;
11323   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
11324                                                      TransReqs))
11325     return ExprError();
11326 
11327   for (concepts::Requirement *Req : TransReqs) {
11328     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
11329       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
11330         ER->getReturnTypeRequirement()
11331                 .getTypeConstraintTemplateParameterList()->getParam(0)
11332                 ->setDeclContext(Body);
11333       }
11334     }
11335   }
11336 
11337   return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
11338                                           TransParams, TransReqs,
11339                                           E->getRBraceLoc());
11340 }
11341 
11342 template<typename Derived>
11343 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
11344     ArrayRef<concepts::Requirement *> Reqs,
11345     SmallVectorImpl<concepts::Requirement *> &Transformed) {
11346   for (concepts::Requirement *Req : Reqs) {
11347     concepts::Requirement *TransReq = nullptr;
11348     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
11349       TransReq = getDerived().TransformTypeRequirement(TypeReq);
11350     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
11351       TransReq = getDerived().TransformExprRequirement(ExprReq);
11352     else
11353       TransReq = getDerived().TransformNestedRequirement(
11354                      cast<concepts::NestedRequirement>(Req));
11355     if (!TransReq)
11356       return true;
11357     Transformed.push_back(TransReq);
11358   }
11359   return false;
11360 }
11361 
11362 template<typename Derived>
11363 concepts::TypeRequirement *
11364 TreeTransform<Derived>::TransformTypeRequirement(
11365     concepts::TypeRequirement *Req) {
11366   if (Req->isSubstitutionFailure()) {
11367     if (getDerived().AlwaysRebuild())
11368       return getDerived().RebuildTypeRequirement(
11369               Req->getSubstitutionDiagnostic());
11370     return Req;
11371   }
11372   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
11373   if (!TransType)
11374     return nullptr;
11375   return getDerived().RebuildTypeRequirement(TransType);
11376 }
11377 
11378 template<typename Derived>
11379 concepts::ExprRequirement *
11380 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
11381   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
11382   if (Req->isExprSubstitutionFailure())
11383     TransExpr = Req->getExprSubstitutionDiagnostic();
11384   else {
11385     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
11386     if (TransExprRes.isInvalid())
11387       return nullptr;
11388     TransExpr = TransExprRes.get();
11389   }
11390 
11391   llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
11392   const auto &RetReq = Req->getReturnTypeRequirement();
11393   if (RetReq.isEmpty())
11394     TransRetReq.emplace();
11395   else if (RetReq.isSubstitutionFailure())
11396     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
11397   else if (RetReq.isTypeConstraint()) {
11398     TemplateParameterList *OrigTPL =
11399         RetReq.getTypeConstraintTemplateParameterList();
11400     TemplateParameterList *TPL =
11401         getDerived().TransformTemplateParameterList(OrigTPL);
11402     if (!TPL)
11403       return nullptr;
11404     TransRetReq.emplace(TPL);
11405   }
11406   assert(TransRetReq.hasValue() &&
11407          "All code paths leading here must set TransRetReq");
11408   if (Expr *E = TransExpr.dyn_cast<Expr *>())
11409     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
11410                                                Req->getNoexceptLoc(),
11411                                                std::move(*TransRetReq));
11412   return getDerived().RebuildExprRequirement(
11413       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
11414       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
11415 }
11416 
11417 template<typename Derived>
11418 concepts::NestedRequirement *
11419 TreeTransform<Derived>::TransformNestedRequirement(
11420     concepts::NestedRequirement *Req) {
11421   if (Req->isSubstitutionFailure()) {
11422     if (getDerived().AlwaysRebuild())
11423       return getDerived().RebuildNestedRequirement(
11424           Req->getSubstitutionDiagnostic());
11425     return Req;
11426   }
11427   ExprResult TransConstraint =
11428       getDerived().TransformExpr(Req->getConstraintExpr());
11429   if (TransConstraint.isInvalid())
11430     return nullptr;
11431   return getDerived().RebuildNestedRequirement(TransConstraint.get());
11432 }
11433 
11434 template<typename Derived>
11435 ExprResult
11436 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
11437   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
11438   if (!T)
11439     return ExprError();
11440 
11441   if (!getDerived().AlwaysRebuild() &&
11442       T == E->getQueriedTypeSourceInfo())
11443     return E;
11444 
11445   ExprResult SubExpr;
11446   {
11447     EnterExpressionEvaluationContext Unevaluated(
11448         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11449     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
11450     if (SubExpr.isInvalid())
11451       return ExprError();
11452 
11453     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11454       return E;
11455   }
11456 
11457   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11458                                             SubExpr.get(), E->getEndLoc());
11459 }
11460 
11461 template<typename Derived>
11462 ExprResult
11463 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11464   ExprResult SubExpr;
11465   {
11466     EnterExpressionEvaluationContext Unevaluated(
11467         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11468     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11469     if (SubExpr.isInvalid())
11470       return ExprError();
11471 
11472     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11473       return E;
11474   }
11475 
11476   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11477                                              SubExpr.get(), E->getEndLoc());
11478 }
11479 
11480 template <typename Derived>
11481 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11482     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11483     TypeSourceInfo **RecoveryTSI) {
11484   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11485       DRE, AddrTaken, RecoveryTSI);
11486 
11487   // Propagate both errors and recovered types, which return ExprEmpty.
11488   if (!NewDRE.isUsable())
11489     return NewDRE;
11490 
11491   // We got an expr, wrap it up in parens.
11492   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11493     return PE;
11494   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11495                                        PE->getRParen());
11496 }
11497 
11498 template <typename Derived>
11499 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11500     DependentScopeDeclRefExpr *E) {
11501   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11502                                             nullptr);
11503 }
11504 
11505 template<typename Derived>
11506 ExprResult
11507 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11508                                                DependentScopeDeclRefExpr *E,
11509                                                bool IsAddressOfOperand,
11510                                                TypeSourceInfo **RecoveryTSI) {
11511   assert(E->getQualifierLoc());
11512   NestedNameSpecifierLoc QualifierLoc
11513   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11514   if (!QualifierLoc)
11515     return ExprError();
11516   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11517 
11518   // TODO: If this is a conversion-function-id, verify that the
11519   // destination type name (if present) resolves the same way after
11520   // instantiation as it did in the local scope.
11521 
11522   DeclarationNameInfo NameInfo
11523     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11524   if (!NameInfo.getName())
11525     return ExprError();
11526 
11527   if (!E->hasExplicitTemplateArgs()) {
11528     if (!getDerived().AlwaysRebuild() &&
11529         QualifierLoc == E->getQualifierLoc() &&
11530         // Note: it is sufficient to compare the Name component of NameInfo:
11531         // if name has not changed, DNLoc has not changed either.
11532         NameInfo.getName() == E->getDeclName())
11533       return E;
11534 
11535     return getDerived().RebuildDependentScopeDeclRefExpr(
11536         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11537         IsAddressOfOperand, RecoveryTSI);
11538   }
11539 
11540   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11541   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11542                                               E->getNumTemplateArgs(),
11543                                               TransArgs))
11544     return ExprError();
11545 
11546   return getDerived().RebuildDependentScopeDeclRefExpr(
11547       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11548       RecoveryTSI);
11549 }
11550 
11551 template<typename Derived>
11552 ExprResult
11553 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11554   // CXXConstructExprs other than for list-initialization and
11555   // CXXTemporaryObjectExpr are always implicit, so when we have
11556   // a 1-argument construction we just transform that argument.
11557   if ((E->getNumArgs() == 1 ||
11558        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11559       (!getDerived().DropCallArgument(E->getArg(0))) &&
11560       !E->isListInitialization())
11561     return getDerived().TransformExpr(E->getArg(0));
11562 
11563   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11564 
11565   QualType T = getDerived().TransformType(E->getType());
11566   if (T.isNull())
11567     return ExprError();
11568 
11569   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11570       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11571   if (!Constructor)
11572     return ExprError();
11573 
11574   bool ArgumentChanged = false;
11575   SmallVector<Expr*, 8> Args;
11576   {
11577     EnterExpressionEvaluationContext Context(
11578         getSema(), EnterExpressionEvaluationContext::InitList,
11579         E->isListInitialization());
11580     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11581                                     &ArgumentChanged))
11582       return ExprError();
11583   }
11584 
11585   if (!getDerived().AlwaysRebuild() &&
11586       T == E->getType() &&
11587       Constructor == E->getConstructor() &&
11588       !ArgumentChanged) {
11589     // Mark the constructor as referenced.
11590     // FIXME: Instantiation-specific
11591     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11592     return E;
11593   }
11594 
11595   return getDerived().RebuildCXXConstructExpr(
11596       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11597       E->hadMultipleCandidates(), E->isListInitialization(),
11598       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11599       E->getConstructionKind(), E->getParenOrBraceRange());
11600 }
11601 
11602 template<typename Derived>
11603 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11604     CXXInheritedCtorInitExpr *E) {
11605   QualType T = getDerived().TransformType(E->getType());
11606   if (T.isNull())
11607     return ExprError();
11608 
11609   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11610       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11611   if (!Constructor)
11612     return ExprError();
11613 
11614   if (!getDerived().AlwaysRebuild() &&
11615       T == E->getType() &&
11616       Constructor == E->getConstructor()) {
11617     // Mark the constructor as referenced.
11618     // FIXME: Instantiation-specific
11619     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11620     return E;
11621   }
11622 
11623   return getDerived().RebuildCXXInheritedCtorInitExpr(
11624       T, E->getLocation(), Constructor,
11625       E->constructsVBase(), E->inheritedFromVBase());
11626 }
11627 
11628 /// Transform a C++ temporary-binding expression.
11629 ///
11630 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11631 /// transform the subexpression and return that.
11632 template<typename Derived>
11633 ExprResult
11634 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11635   return getDerived().TransformExpr(E->getSubExpr());
11636 }
11637 
11638 /// Transform a C++ expression that contains cleanups that should
11639 /// be run after the expression is evaluated.
11640 ///
11641 /// Since ExprWithCleanups nodes are implicitly generated, we
11642 /// just transform the subexpression and return that.
11643 template<typename Derived>
11644 ExprResult
11645 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11646   return getDerived().TransformExpr(E->getSubExpr());
11647 }
11648 
11649 template<typename Derived>
11650 ExprResult
11651 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11652                                                     CXXTemporaryObjectExpr *E) {
11653   TypeSourceInfo *T =
11654       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11655   if (!T)
11656     return ExprError();
11657 
11658   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11659       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11660   if (!Constructor)
11661     return ExprError();
11662 
11663   bool ArgumentChanged = false;
11664   SmallVector<Expr*, 8> Args;
11665   Args.reserve(E->getNumArgs());
11666   {
11667     EnterExpressionEvaluationContext Context(
11668         getSema(), EnterExpressionEvaluationContext::InitList,
11669         E->isListInitialization());
11670     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11671                        &ArgumentChanged))
11672       return ExprError();
11673   }
11674 
11675   if (!getDerived().AlwaysRebuild() &&
11676       T == E->getTypeSourceInfo() &&
11677       Constructor == E->getConstructor() &&
11678       !ArgumentChanged) {
11679     // FIXME: Instantiation-specific
11680     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11681     return SemaRef.MaybeBindToTemporary(E);
11682   }
11683 
11684   // FIXME: We should just pass E->isListInitialization(), but we're not
11685   // prepared to handle list-initialization without a child InitListExpr.
11686   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11687   return getDerived().RebuildCXXTemporaryObjectExpr(
11688       T, LParenLoc, Args, E->getEndLoc(),
11689       /*ListInitialization=*/LParenLoc.isInvalid());
11690 }
11691 
11692 template<typename Derived>
11693 ExprResult
11694 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11695   // Transform any init-capture expressions before entering the scope of the
11696   // lambda body, because they are not semantically within that scope.
11697   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11698   struct TransformedInitCapture {
11699     // The location of the ... if the result is retaining a pack expansion.
11700     SourceLocation EllipsisLoc;
11701     // Zero or more expansions of the init-capture.
11702     SmallVector<InitCaptureInfoTy, 4> Expansions;
11703   };
11704   SmallVector<TransformedInitCapture, 4> InitCaptures;
11705   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11706   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11707                                     CEnd = E->capture_end();
11708        C != CEnd; ++C) {
11709     if (!E->isInitCapture(C))
11710       continue;
11711 
11712     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11713     VarDecl *OldVD = C->getCapturedVar();
11714 
11715     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11716                                 Optional<unsigned> NumExpansions) {
11717       ExprResult NewExprInitResult = getDerived().TransformInitializer(
11718           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11719 
11720       if (NewExprInitResult.isInvalid()) {
11721         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11722         return;
11723       }
11724       Expr *NewExprInit = NewExprInitResult.get();
11725 
11726       QualType NewInitCaptureType =
11727           getSema().buildLambdaInitCaptureInitialization(
11728               C->getLocation(), OldVD->getType()->isReferenceType(),
11729               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11730               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11731               NewExprInit);
11732       Result.Expansions.push_back(
11733           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11734     };
11735 
11736     // If this is an init-capture pack, consider expanding the pack now.
11737     if (OldVD->isParameterPack()) {
11738       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11739                                              ->getTypeLoc()
11740                                              .castAs<PackExpansionTypeLoc>();
11741       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11742       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11743 
11744       // Determine whether the set of unexpanded parameter packs can and should
11745       // be expanded.
11746       bool Expand = true;
11747       bool RetainExpansion = false;
11748       Optional<unsigned> OrigNumExpansions =
11749           ExpansionTL.getTypePtr()->getNumExpansions();
11750       Optional<unsigned> NumExpansions = OrigNumExpansions;
11751       if (getDerived().TryExpandParameterPacks(
11752               ExpansionTL.getEllipsisLoc(),
11753               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11754               RetainExpansion, NumExpansions))
11755         return ExprError();
11756       if (Expand) {
11757         for (unsigned I = 0; I != *NumExpansions; ++I) {
11758           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11759           SubstInitCapture(SourceLocation(), None);
11760         }
11761       }
11762       if (!Expand || RetainExpansion) {
11763         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11764         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11765         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11766       }
11767     } else {
11768       SubstInitCapture(SourceLocation(), None);
11769     }
11770   }
11771 
11772   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11773   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11774 
11775   // Transform the template parameters, and add them to the current
11776   // instantiation scope. The null case is handled correctly.
11777   auto TPL = getDerived().TransformTemplateParameterList(
11778       E->getTemplateParameterList());
11779   LSI->GLTemplateParameterList = TPL;
11780 
11781   // Transform the type of the original lambda's call operator.
11782   // The transformation MUST be done in the CurrentInstantiationScope since
11783   // it introduces a mapping of the original to the newly created
11784   // transformed parameters.
11785   TypeSourceInfo *NewCallOpTSI = nullptr;
11786   {
11787     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11788     FunctionProtoTypeLoc OldCallOpFPTL =
11789         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11790 
11791     TypeLocBuilder NewCallOpTLBuilder;
11792     SmallVector<QualType, 4> ExceptionStorage;
11793     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11794     QualType NewCallOpType = TransformFunctionProtoType(
11795         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11796         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11797           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11798                                               ExceptionStorage, Changed);
11799         });
11800     if (NewCallOpType.isNull())
11801       return ExprError();
11802     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11803                                                         NewCallOpType);
11804   }
11805 
11806   // Transform the trailing requires clause
11807   ExprResult NewTrailingRequiresClause;
11808   if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
11809     // FIXME: Concepts: Substitution into requires clause should only happen
11810     //                  when checking satisfaction.
11811     NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
11812 
11813   // Create the local class that will describe the lambda.
11814   // FIXME: KnownDependent below is wrong when substituting inside a templated
11815   // context that isn't a DeclContext (such as a variable template).
11816   CXXRecordDecl *OldClass = E->getLambdaClass();
11817   CXXRecordDecl *Class
11818     = getSema().createLambdaClosureType(E->getIntroducerRange(),
11819                                         NewCallOpTSI,
11820                                         /*KnownDependent=*/false,
11821                                         E->getCaptureDefault());
11822   getDerived().transformedLocalDecl(OldClass, {Class});
11823 
11824   Optional<std::tuple<unsigned, bool, Decl *>> Mangling;
11825   if (getDerived().ReplacingOriginal())
11826     Mangling = std::make_tuple(OldClass->getLambdaManglingNumber(),
11827                                OldClass->hasKnownLambdaInternalLinkage(),
11828                                OldClass->getLambdaContextDecl());
11829 
11830   // Build the call operator.
11831   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11832       Class, E->getIntroducerRange(), NewCallOpTSI,
11833       E->getCallOperator()->getEndLoc(),
11834       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11835       E->getCallOperator()->getConstexprKind(),
11836       NewTrailingRequiresClause.get());
11837 
11838   LSI->CallOperator = NewCallOperator;
11839 
11840   for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11841        I != NumParams; ++I) {
11842     auto *P = NewCallOperator->getParamDecl(I);
11843     if (P->hasUninstantiatedDefaultArg()) {
11844       EnterExpressionEvaluationContext Eval(
11845           getSema(),
11846           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11847       ExprResult R = getDerived().TransformExpr(
11848           E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11849       P->setDefaultArg(R.get());
11850     }
11851   }
11852 
11853   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11854   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11855 
11856   // Number the lambda for linkage purposes if necessary.
11857   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
11858 
11859   // Introduce the context of the call operator.
11860   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11861                                  /*NewThisContext*/false);
11862 
11863   // Enter the scope of the lambda.
11864   getSema().buildLambdaScope(LSI, NewCallOperator,
11865                              E->getIntroducerRange(),
11866                              E->getCaptureDefault(),
11867                              E->getCaptureDefaultLoc(),
11868                              E->hasExplicitParameters(),
11869                              E->hasExplicitResultType(),
11870                              E->isMutable());
11871 
11872   bool Invalid = false;
11873 
11874   // Transform captures.
11875   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11876                                  CEnd = E->capture_end();
11877        C != CEnd; ++C) {
11878     // When we hit the first implicit capture, tell Sema that we've finished
11879     // the list of explicit captures.
11880     if (C->isImplicit())
11881       break;
11882 
11883     // Capturing 'this' is trivial.
11884     if (C->capturesThis()) {
11885       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11886                                     /*BuildAndDiagnose*/ true, nullptr,
11887                                     C->getCaptureKind() == LCK_StarThis);
11888       continue;
11889     }
11890     // Captured expression will be recaptured during captured variables
11891     // rebuilding.
11892     if (C->capturesVLAType())
11893       continue;
11894 
11895     // Rebuild init-captures, including the implied field declaration.
11896     if (E->isInitCapture(C)) {
11897       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11898 
11899       VarDecl *OldVD = C->getCapturedVar();
11900       llvm::SmallVector<Decl*, 4> NewVDs;
11901 
11902       for (InitCaptureInfoTy &Info : NewC.Expansions) {
11903         ExprResult Init = Info.first;
11904         QualType InitQualType = Info.second;
11905         if (Init.isInvalid() || InitQualType.isNull()) {
11906           Invalid = true;
11907           break;
11908         }
11909         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11910             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11911             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11912         if (!NewVD) {
11913           Invalid = true;
11914           break;
11915         }
11916         NewVDs.push_back(NewVD);
11917         getSema().addInitCapture(LSI, NewVD);
11918       }
11919 
11920       if (Invalid)
11921         break;
11922 
11923       getDerived().transformedLocalDecl(OldVD, NewVDs);
11924       continue;
11925     }
11926 
11927     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11928 
11929     // Determine the capture kind for Sema.
11930     Sema::TryCaptureKind Kind
11931       = C->isImplicit()? Sema::TryCapture_Implicit
11932                        : C->getCaptureKind() == LCK_ByCopy
11933                            ? Sema::TryCapture_ExplicitByVal
11934                            : Sema::TryCapture_ExplicitByRef;
11935     SourceLocation EllipsisLoc;
11936     if (C->isPackExpansion()) {
11937       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11938       bool ShouldExpand = false;
11939       bool RetainExpansion = false;
11940       Optional<unsigned> NumExpansions;
11941       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11942                                                C->getLocation(),
11943                                                Unexpanded,
11944                                                ShouldExpand, RetainExpansion,
11945                                                NumExpansions)) {
11946         Invalid = true;
11947         continue;
11948       }
11949 
11950       if (ShouldExpand) {
11951         // The transform has determined that we should perform an expansion;
11952         // transform and capture each of the arguments.
11953         // expansion of the pattern. Do so.
11954         VarDecl *Pack = C->getCapturedVar();
11955         for (unsigned I = 0; I != *NumExpansions; ++I) {
11956           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11957           VarDecl *CapturedVar
11958             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11959                                                                Pack));
11960           if (!CapturedVar) {
11961             Invalid = true;
11962             continue;
11963           }
11964 
11965           // Capture the transformed variable.
11966           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11967         }
11968 
11969         // FIXME: Retain a pack expansion if RetainExpansion is true.
11970 
11971         continue;
11972       }
11973 
11974       EllipsisLoc = C->getEllipsisLoc();
11975     }
11976 
11977     // Transform the captured variable.
11978     VarDecl *CapturedVar
11979       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11980                                                          C->getCapturedVar()));
11981     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11982       Invalid = true;
11983       continue;
11984     }
11985 
11986     // Capture the transformed variable.
11987     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11988                                  EllipsisLoc);
11989   }
11990   getSema().finishLambdaExplicitCaptures(LSI);
11991 
11992   // FIXME: Sema's lambda-building mechanism expects us to push an expression
11993   // evaluation context even if we're not transforming the function body.
11994   getSema().PushExpressionEvaluationContext(
11995       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11996 
11997   // Instantiate the body of the lambda expression.
11998   StmtResult Body =
11999       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
12000 
12001   // ActOnLambda* will pop the function scope for us.
12002   FuncScopeCleanup.disable();
12003 
12004   if (Body.isInvalid()) {
12005     SavedContext.pop();
12006     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
12007                                /*IsInstantiation=*/true);
12008     return ExprError();
12009   }
12010 
12011   // Copy the LSI before ActOnFinishFunctionBody removes it.
12012   // FIXME: This is dumb. Store the lambda information somewhere that outlives
12013   // the call operator.
12014   auto LSICopy = *LSI;
12015   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
12016                                     /*IsInstantiation*/ true);
12017   SavedContext.pop();
12018 
12019   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
12020                                    &LSICopy);
12021 }
12022 
12023 template<typename Derived>
12024 StmtResult
12025 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
12026   return TransformStmt(S);
12027 }
12028 
12029 template<typename Derived>
12030 StmtResult
12031 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
12032   // Transform captures.
12033   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12034                                  CEnd = E->capture_end();
12035        C != CEnd; ++C) {
12036     // When we hit the first implicit capture, tell Sema that we've finished
12037     // the list of explicit captures.
12038     if (!C->isImplicit())
12039       continue;
12040 
12041     // Capturing 'this' is trivial.
12042     if (C->capturesThis()) {
12043       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
12044                                     /*BuildAndDiagnose*/ true, nullptr,
12045                                     C->getCaptureKind() == LCK_StarThis);
12046       continue;
12047     }
12048     // Captured expression will be recaptured during captured variables
12049     // rebuilding.
12050     if (C->capturesVLAType())
12051       continue;
12052 
12053     assert(C->capturesVariable() && "unexpected kind of lambda capture");
12054     assert(!E->isInitCapture(C) && "implicit init-capture?");
12055 
12056     // Transform the captured variable.
12057     VarDecl *CapturedVar = cast_or_null<VarDecl>(
12058         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
12059     if (!CapturedVar || CapturedVar->isInvalidDecl())
12060       return StmtError();
12061 
12062     // Capture the transformed variable.
12063     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
12064   }
12065 
12066   return S;
12067 }
12068 
12069 template<typename Derived>
12070 ExprResult
12071 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
12072                                                   CXXUnresolvedConstructExpr *E) {
12073   TypeSourceInfo *T =
12074       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12075   if (!T)
12076     return ExprError();
12077 
12078   bool ArgumentChanged = false;
12079   SmallVector<Expr*, 8> Args;
12080   Args.reserve(E->arg_size());
12081   {
12082     EnterExpressionEvaluationContext Context(
12083         getSema(), EnterExpressionEvaluationContext::InitList,
12084         E->isListInitialization());
12085     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
12086                                     &ArgumentChanged))
12087       return ExprError();
12088   }
12089 
12090   if (!getDerived().AlwaysRebuild() &&
12091       T == E->getTypeSourceInfo() &&
12092       !ArgumentChanged)
12093     return E;
12094 
12095   // FIXME: we're faking the locations of the commas
12096   return getDerived().RebuildCXXUnresolvedConstructExpr(
12097       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
12098 }
12099 
12100 template<typename Derived>
12101 ExprResult
12102 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
12103                                              CXXDependentScopeMemberExpr *E) {
12104   // Transform the base of the expression.
12105   ExprResult Base((Expr*) nullptr);
12106   Expr *OldBase;
12107   QualType BaseType;
12108   QualType ObjectType;
12109   if (!E->isImplicitAccess()) {
12110     OldBase = E->getBase();
12111     Base = getDerived().TransformExpr(OldBase);
12112     if (Base.isInvalid())
12113       return ExprError();
12114 
12115     // Start the member reference and compute the object's type.
12116     ParsedType ObjectTy;
12117     bool MayBePseudoDestructor = false;
12118     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12119                                                 E->getOperatorLoc(),
12120                                       E->isArrow()? tok::arrow : tok::period,
12121                                                 ObjectTy,
12122                                                 MayBePseudoDestructor);
12123     if (Base.isInvalid())
12124       return ExprError();
12125 
12126     ObjectType = ObjectTy.get();
12127     BaseType = ((Expr*) Base.get())->getType();
12128   } else {
12129     OldBase = nullptr;
12130     BaseType = getDerived().TransformType(E->getBaseType());
12131     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
12132   }
12133 
12134   // Transform the first part of the nested-name-specifier that qualifies
12135   // the member name.
12136   NamedDecl *FirstQualifierInScope
12137     = getDerived().TransformFirstQualifierInScope(
12138                                             E->getFirstQualifierFoundInScope(),
12139                                             E->getQualifierLoc().getBeginLoc());
12140 
12141   NestedNameSpecifierLoc QualifierLoc;
12142   if (E->getQualifier()) {
12143     QualifierLoc
12144       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
12145                                                      ObjectType,
12146                                                      FirstQualifierInScope);
12147     if (!QualifierLoc)
12148       return ExprError();
12149   }
12150 
12151   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12152 
12153   // TODO: If this is a conversion-function-id, verify that the
12154   // destination type name (if present) resolves the same way after
12155   // instantiation as it did in the local scope.
12156 
12157   DeclarationNameInfo NameInfo
12158     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
12159   if (!NameInfo.getName())
12160     return ExprError();
12161 
12162   if (!E->hasExplicitTemplateArgs()) {
12163     // This is a reference to a member without an explicitly-specified
12164     // template argument list. Optimize for this common case.
12165     if (!getDerived().AlwaysRebuild() &&
12166         Base.get() == OldBase &&
12167         BaseType == E->getBaseType() &&
12168         QualifierLoc == E->getQualifierLoc() &&
12169         NameInfo.getName() == E->getMember() &&
12170         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
12171       return E;
12172 
12173     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
12174                                                        BaseType,
12175                                                        E->isArrow(),
12176                                                        E->getOperatorLoc(),
12177                                                        QualifierLoc,
12178                                                        TemplateKWLoc,
12179                                                        FirstQualifierInScope,
12180                                                        NameInfo,
12181                                                        /*TemplateArgs*/nullptr);
12182   }
12183 
12184   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12185   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
12186                                               E->getNumTemplateArgs(),
12187                                               TransArgs))
12188     return ExprError();
12189 
12190   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
12191                                                      BaseType,
12192                                                      E->isArrow(),
12193                                                      E->getOperatorLoc(),
12194                                                      QualifierLoc,
12195                                                      TemplateKWLoc,
12196                                                      FirstQualifierInScope,
12197                                                      NameInfo,
12198                                                      &TransArgs);
12199 }
12200 
12201 template<typename Derived>
12202 ExprResult
12203 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
12204   // Transform the base of the expression.
12205   ExprResult Base((Expr*) nullptr);
12206   QualType BaseType;
12207   if (!Old->isImplicitAccess()) {
12208     Base = getDerived().TransformExpr(Old->getBase());
12209     if (Base.isInvalid())
12210       return ExprError();
12211     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
12212                                                      Old->isArrow());
12213     if (Base.isInvalid())
12214       return ExprError();
12215     BaseType = Base.get()->getType();
12216   } else {
12217     BaseType = getDerived().TransformType(Old->getBaseType());
12218   }
12219 
12220   NestedNameSpecifierLoc QualifierLoc;
12221   if (Old->getQualifierLoc()) {
12222     QualifierLoc
12223     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12224     if (!QualifierLoc)
12225       return ExprError();
12226   }
12227 
12228   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12229 
12230   LookupResult R(SemaRef, Old->getMemberNameInfo(),
12231                  Sema::LookupOrdinaryName);
12232 
12233   // Transform the declaration set.
12234   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
12235     return ExprError();
12236 
12237   // Determine the naming class.
12238   if (Old->getNamingClass()) {
12239     CXXRecordDecl *NamingClass
12240       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12241                                                           Old->getMemberLoc(),
12242                                                         Old->getNamingClass()));
12243     if (!NamingClass)
12244       return ExprError();
12245 
12246     R.setNamingClass(NamingClass);
12247   }
12248 
12249   TemplateArgumentListInfo TransArgs;
12250   if (Old->hasExplicitTemplateArgs()) {
12251     TransArgs.setLAngleLoc(Old->getLAngleLoc());
12252     TransArgs.setRAngleLoc(Old->getRAngleLoc());
12253     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12254                                                 Old->getNumTemplateArgs(),
12255                                                 TransArgs))
12256       return ExprError();
12257   }
12258 
12259   // FIXME: to do this check properly, we will need to preserve the
12260   // first-qualifier-in-scope here, just in case we had a dependent
12261   // base (and therefore couldn't do the check) and a
12262   // nested-name-qualifier (and therefore could do the lookup).
12263   NamedDecl *FirstQualifierInScope = nullptr;
12264 
12265   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
12266                                                   BaseType,
12267                                                   Old->getOperatorLoc(),
12268                                                   Old->isArrow(),
12269                                                   QualifierLoc,
12270                                                   TemplateKWLoc,
12271                                                   FirstQualifierInScope,
12272                                                   R,
12273                                               (Old->hasExplicitTemplateArgs()
12274                                                   ? &TransArgs : nullptr));
12275 }
12276 
12277 template<typename Derived>
12278 ExprResult
12279 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
12280   EnterExpressionEvaluationContext Unevaluated(
12281       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12282   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
12283   if (SubExpr.isInvalid())
12284     return ExprError();
12285 
12286   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
12287     return E;
12288 
12289   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
12290 }
12291 
12292 template<typename Derived>
12293 ExprResult
12294 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
12295   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
12296   if (Pattern.isInvalid())
12297     return ExprError();
12298 
12299   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
12300     return E;
12301 
12302   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
12303                                            E->getNumExpansions());
12304 }
12305 
12306 template<typename Derived>
12307 ExprResult
12308 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
12309   // If E is not value-dependent, then nothing will change when we transform it.
12310   // Note: This is an instantiation-centric view.
12311   if (!E->isValueDependent())
12312     return E;
12313 
12314   EnterExpressionEvaluationContext Unevaluated(
12315       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
12316 
12317   ArrayRef<TemplateArgument> PackArgs;
12318   TemplateArgument ArgStorage;
12319 
12320   // Find the argument list to transform.
12321   if (E->isPartiallySubstituted()) {
12322     PackArgs = E->getPartialArguments();
12323   } else if (E->isValueDependent()) {
12324     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
12325     bool ShouldExpand = false;
12326     bool RetainExpansion = false;
12327     Optional<unsigned> NumExpansions;
12328     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
12329                                              Unexpanded,
12330                                              ShouldExpand, RetainExpansion,
12331                                              NumExpansions))
12332       return ExprError();
12333 
12334     // If we need to expand the pack, build a template argument from it and
12335     // expand that.
12336     if (ShouldExpand) {
12337       auto *Pack = E->getPack();
12338       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
12339         ArgStorage = getSema().Context.getPackExpansionType(
12340             getSema().Context.getTypeDeclType(TTPD), None);
12341       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
12342         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
12343       } else {
12344         auto *VD = cast<ValueDecl>(Pack);
12345         ExprResult DRE = getSema().BuildDeclRefExpr(
12346             VD, VD->getType().getNonLValueExprType(getSema().Context),
12347             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
12348             E->getPackLoc());
12349         if (DRE.isInvalid())
12350           return ExprError();
12351         ArgStorage = new (getSema().Context) PackExpansionExpr(
12352             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
12353       }
12354       PackArgs = ArgStorage;
12355     }
12356   }
12357 
12358   // If we're not expanding the pack, just transform the decl.
12359   if (!PackArgs.size()) {
12360     auto *Pack = cast_or_null<NamedDecl>(
12361         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
12362     if (!Pack)
12363       return ExprError();
12364     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
12365                                               E->getPackLoc(),
12366                                               E->getRParenLoc(), None, None);
12367   }
12368 
12369   // Try to compute the result without performing a partial substitution.
12370   Optional<unsigned> Result = 0;
12371   for (const TemplateArgument &Arg : PackArgs) {
12372     if (!Arg.isPackExpansion()) {
12373       Result = *Result + 1;
12374       continue;
12375     }
12376 
12377     TemplateArgumentLoc ArgLoc;
12378     InventTemplateArgumentLoc(Arg, ArgLoc);
12379 
12380     // Find the pattern of the pack expansion.
12381     SourceLocation Ellipsis;
12382     Optional<unsigned> OrigNumExpansions;
12383     TemplateArgumentLoc Pattern =
12384         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
12385                                                           OrigNumExpansions);
12386 
12387     // Substitute under the pack expansion. Do not expand the pack (yet).
12388     TemplateArgumentLoc OutPattern;
12389     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12390     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
12391                                                /*Uneval*/ true))
12392       return true;
12393 
12394     // See if we can determine the number of arguments from the result.
12395     Optional<unsigned> NumExpansions =
12396         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
12397     if (!NumExpansions) {
12398       // No: we must be in an alias template expansion, and we're going to need
12399       // to actually expand the packs.
12400       Result = None;
12401       break;
12402     }
12403 
12404     Result = *Result + *NumExpansions;
12405   }
12406 
12407   // Common case: we could determine the number of expansions without
12408   // substituting.
12409   if (Result)
12410     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12411                                               E->getPackLoc(),
12412                                               E->getRParenLoc(), *Result, None);
12413 
12414   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
12415                                                E->getPackLoc());
12416   {
12417     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
12418     typedef TemplateArgumentLocInventIterator<
12419         Derived, const TemplateArgument*> PackLocIterator;
12420     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
12421                                    PackLocIterator(*this, PackArgs.end()),
12422                                    TransformedPackArgs, /*Uneval*/true))
12423       return ExprError();
12424   }
12425 
12426   // Check whether we managed to fully-expand the pack.
12427   // FIXME: Is it possible for us to do so and not hit the early exit path?
12428   SmallVector<TemplateArgument, 8> Args;
12429   bool PartialSubstitution = false;
12430   for (auto &Loc : TransformedPackArgs.arguments()) {
12431     Args.push_back(Loc.getArgument());
12432     if (Loc.getArgument().isPackExpansion())
12433       PartialSubstitution = true;
12434   }
12435 
12436   if (PartialSubstitution)
12437     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12438                                               E->getPackLoc(),
12439                                               E->getRParenLoc(), None, Args);
12440 
12441   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12442                                             E->getPackLoc(), E->getRParenLoc(),
12443                                             Args.size(), None);
12444 }
12445 
12446 template<typename Derived>
12447 ExprResult
12448 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
12449                                           SubstNonTypeTemplateParmPackExpr *E) {
12450   // Default behavior is to do nothing with this transformation.
12451   return E;
12452 }
12453 
12454 template<typename Derived>
12455 ExprResult
12456 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
12457                                           SubstNonTypeTemplateParmExpr *E) {
12458   // Default behavior is to do nothing with this transformation.
12459   return E;
12460 }
12461 
12462 template<typename Derived>
12463 ExprResult
12464 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12465   // Default behavior is to do nothing with this transformation.
12466   return E;
12467 }
12468 
12469 template<typename Derived>
12470 ExprResult
12471 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12472                                                   MaterializeTemporaryExpr *E) {
12473   return getDerived().TransformExpr(E->getSubExpr());
12474 }
12475 
12476 template<typename Derived>
12477 ExprResult
12478 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12479   Expr *Pattern = E->getPattern();
12480 
12481   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12482   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12483   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12484 
12485   // Determine whether the set of unexpanded parameter packs can and should
12486   // be expanded.
12487   bool Expand = true;
12488   bool RetainExpansion = false;
12489   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12490                      NumExpansions = OrigNumExpansions;
12491   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12492                                            Pattern->getSourceRange(),
12493                                            Unexpanded,
12494                                            Expand, RetainExpansion,
12495                                            NumExpansions))
12496     return true;
12497 
12498   if (!Expand) {
12499     // Do not expand any packs here, just transform and rebuild a fold
12500     // expression.
12501     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12502 
12503     ExprResult LHS =
12504         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12505     if (LHS.isInvalid())
12506       return true;
12507 
12508     ExprResult RHS =
12509         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12510     if (RHS.isInvalid())
12511       return true;
12512 
12513     if (!getDerived().AlwaysRebuild() &&
12514         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12515       return E;
12516 
12517     return getDerived().RebuildCXXFoldExpr(
12518         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12519         RHS.get(), E->getEndLoc(), NumExpansions);
12520   }
12521 
12522   // The transform has determined that we should perform an elementwise
12523   // expansion of the pattern. Do so.
12524   ExprResult Result = getDerived().TransformExpr(E->getInit());
12525   if (Result.isInvalid())
12526     return true;
12527   bool LeftFold = E->isLeftFold();
12528 
12529   // If we're retaining an expansion for a right fold, it is the innermost
12530   // component and takes the init (if any).
12531   if (!LeftFold && RetainExpansion) {
12532     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12533 
12534     ExprResult Out = getDerived().TransformExpr(Pattern);
12535     if (Out.isInvalid())
12536       return true;
12537 
12538     Result = getDerived().RebuildCXXFoldExpr(
12539         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12540         Result.get(), E->getEndLoc(), OrigNumExpansions);
12541     if (Result.isInvalid())
12542       return true;
12543   }
12544 
12545   for (unsigned I = 0; I != *NumExpansions; ++I) {
12546     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12547         getSema(), LeftFold ? I : *NumExpansions - I - 1);
12548     ExprResult Out = getDerived().TransformExpr(Pattern);
12549     if (Out.isInvalid())
12550       return true;
12551 
12552     if (Out.get()->containsUnexpandedParameterPack()) {
12553       // We still have a pack; retain a pack expansion for this slice.
12554       Result = getDerived().RebuildCXXFoldExpr(
12555           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12556           E->getOperator(), E->getEllipsisLoc(),
12557           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12558           OrigNumExpansions);
12559     } else if (Result.isUsable()) {
12560       // We've got down to a single element; build a binary operator.
12561       Result = getDerived().RebuildBinaryOperator(
12562           E->getEllipsisLoc(), E->getOperator(),
12563           LeftFold ? Result.get() : Out.get(),
12564           LeftFold ? Out.get() : Result.get());
12565     } else
12566       Result = Out;
12567 
12568     if (Result.isInvalid())
12569       return true;
12570   }
12571 
12572   // If we're retaining an expansion for a left fold, it is the outermost
12573   // component and takes the complete expansion so far as its init (if any).
12574   if (LeftFold && RetainExpansion) {
12575     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12576 
12577     ExprResult Out = getDerived().TransformExpr(Pattern);
12578     if (Out.isInvalid())
12579       return true;
12580 
12581     Result = getDerived().RebuildCXXFoldExpr(
12582         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12583         Out.get(), E->getEndLoc(), OrigNumExpansions);
12584     if (Result.isInvalid())
12585       return true;
12586   }
12587 
12588   // If we had no init and an empty pack, and we're not retaining an expansion,
12589   // then produce a fallback value or error.
12590   if (Result.isUnset())
12591     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12592                                                 E->getOperator());
12593 
12594   return Result;
12595 }
12596 
12597 template<typename Derived>
12598 ExprResult
12599 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12600     CXXStdInitializerListExpr *E) {
12601   return getDerived().TransformExpr(E->getSubExpr());
12602 }
12603 
12604 template<typename Derived>
12605 ExprResult
12606 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12607   return SemaRef.MaybeBindToTemporary(E);
12608 }
12609 
12610 template<typename Derived>
12611 ExprResult
12612 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12613   return E;
12614 }
12615 
12616 template<typename Derived>
12617 ExprResult
12618 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12619   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12620   if (SubExpr.isInvalid())
12621     return ExprError();
12622 
12623   if (!getDerived().AlwaysRebuild() &&
12624       SubExpr.get() == E->getSubExpr())
12625     return E;
12626 
12627   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12628 }
12629 
12630 template<typename Derived>
12631 ExprResult
12632 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12633   // Transform each of the elements.
12634   SmallVector<Expr *, 8> Elements;
12635   bool ArgChanged = false;
12636   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12637                                   /*IsCall=*/false, Elements, &ArgChanged))
12638     return ExprError();
12639 
12640   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12641     return SemaRef.MaybeBindToTemporary(E);
12642 
12643   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12644                                               Elements.data(),
12645                                               Elements.size());
12646 }
12647 
12648 template<typename Derived>
12649 ExprResult
12650 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12651                                                     ObjCDictionaryLiteral *E) {
12652   // Transform each of the elements.
12653   SmallVector<ObjCDictionaryElement, 8> Elements;
12654   bool ArgChanged = false;
12655   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12656     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12657 
12658     if (OrigElement.isPackExpansion()) {
12659       // This key/value element is a pack expansion.
12660       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12661       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12662       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12663       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12664 
12665       // Determine whether the set of unexpanded parameter packs can
12666       // and should be expanded.
12667       bool Expand = true;
12668       bool RetainExpansion = false;
12669       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12670       Optional<unsigned> NumExpansions = OrigNumExpansions;
12671       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12672                                OrigElement.Value->getEndLoc());
12673       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12674                                                PatternRange, Unexpanded, Expand,
12675                                                RetainExpansion, NumExpansions))
12676         return ExprError();
12677 
12678       if (!Expand) {
12679         // The transform has determined that we should perform a simple
12680         // transformation on the pack expansion, producing another pack
12681         // expansion.
12682         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12683         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12684         if (Key.isInvalid())
12685           return ExprError();
12686 
12687         if (Key.get() != OrigElement.Key)
12688           ArgChanged = true;
12689 
12690         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12691         if (Value.isInvalid())
12692           return ExprError();
12693 
12694         if (Value.get() != OrigElement.Value)
12695           ArgChanged = true;
12696 
12697         ObjCDictionaryElement Expansion = {
12698           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12699         };
12700         Elements.push_back(Expansion);
12701         continue;
12702       }
12703 
12704       // Record right away that the argument was changed.  This needs
12705       // to happen even if the array expands to nothing.
12706       ArgChanged = true;
12707 
12708       // The transform has determined that we should perform an elementwise
12709       // expansion of the pattern. Do so.
12710       for (unsigned I = 0; I != *NumExpansions; ++I) {
12711         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12712         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12713         if (Key.isInvalid())
12714           return ExprError();
12715 
12716         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12717         if (Value.isInvalid())
12718           return ExprError();
12719 
12720         ObjCDictionaryElement Element = {
12721           Key.get(), Value.get(), SourceLocation(), NumExpansions
12722         };
12723 
12724         // If any unexpanded parameter packs remain, we still have a
12725         // pack expansion.
12726         // FIXME: Can this really happen?
12727         if (Key.get()->containsUnexpandedParameterPack() ||
12728             Value.get()->containsUnexpandedParameterPack())
12729           Element.EllipsisLoc = OrigElement.EllipsisLoc;
12730 
12731         Elements.push_back(Element);
12732       }
12733 
12734       // FIXME: Retain a pack expansion if RetainExpansion is true.
12735 
12736       // We've finished with this pack expansion.
12737       continue;
12738     }
12739 
12740     // Transform and check key.
12741     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12742     if (Key.isInvalid())
12743       return ExprError();
12744 
12745     if (Key.get() != OrigElement.Key)
12746       ArgChanged = true;
12747 
12748     // Transform and check value.
12749     ExprResult Value
12750       = getDerived().TransformExpr(OrigElement.Value);
12751     if (Value.isInvalid())
12752       return ExprError();
12753 
12754     if (Value.get() != OrigElement.Value)
12755       ArgChanged = true;
12756 
12757     ObjCDictionaryElement Element = {
12758       Key.get(), Value.get(), SourceLocation(), None
12759     };
12760     Elements.push_back(Element);
12761   }
12762 
12763   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12764     return SemaRef.MaybeBindToTemporary(E);
12765 
12766   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12767                                                    Elements);
12768 }
12769 
12770 template<typename Derived>
12771 ExprResult
12772 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12773   TypeSourceInfo *EncodedTypeInfo
12774     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12775   if (!EncodedTypeInfo)
12776     return ExprError();
12777 
12778   if (!getDerived().AlwaysRebuild() &&
12779       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12780     return E;
12781 
12782   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12783                                             EncodedTypeInfo,
12784                                             E->getRParenLoc());
12785 }
12786 
12787 template<typename Derived>
12788 ExprResult TreeTransform<Derived>::
12789 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12790   // This is a kind of implicit conversion, and it needs to get dropped
12791   // and recomputed for the same general reasons that ImplicitCastExprs
12792   // do, as well a more specific one: this expression is only valid when
12793   // it appears *immediately* as an argument expression.
12794   return getDerived().TransformExpr(E->getSubExpr());
12795 }
12796 
12797 template<typename Derived>
12798 ExprResult TreeTransform<Derived>::
12799 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12800   TypeSourceInfo *TSInfo
12801     = getDerived().TransformType(E->getTypeInfoAsWritten());
12802   if (!TSInfo)
12803     return ExprError();
12804 
12805   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12806   if (Result.isInvalid())
12807     return ExprError();
12808 
12809   if (!getDerived().AlwaysRebuild() &&
12810       TSInfo == E->getTypeInfoAsWritten() &&
12811       Result.get() == E->getSubExpr())
12812     return E;
12813 
12814   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12815                                       E->getBridgeKeywordLoc(), TSInfo,
12816                                       Result.get());
12817 }
12818 
12819 template <typename Derived>
12820 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12821     ObjCAvailabilityCheckExpr *E) {
12822   return E;
12823 }
12824 
12825 template<typename Derived>
12826 ExprResult
12827 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12828   // Transform arguments.
12829   bool ArgChanged = false;
12830   SmallVector<Expr*, 8> Args;
12831   Args.reserve(E->getNumArgs());
12832   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12833                                   &ArgChanged))
12834     return ExprError();
12835 
12836   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12837     // Class message: transform the receiver type.
12838     TypeSourceInfo *ReceiverTypeInfo
12839       = getDerived().TransformType(E->getClassReceiverTypeInfo());
12840     if (!ReceiverTypeInfo)
12841       return ExprError();
12842 
12843     // If nothing changed, just retain the existing message send.
12844     if (!getDerived().AlwaysRebuild() &&
12845         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12846       return SemaRef.MaybeBindToTemporary(E);
12847 
12848     // Build a new class message send.
12849     SmallVector<SourceLocation, 16> SelLocs;
12850     E->getSelectorLocs(SelLocs);
12851     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12852                                                E->getSelector(),
12853                                                SelLocs,
12854                                                E->getMethodDecl(),
12855                                                E->getLeftLoc(),
12856                                                Args,
12857                                                E->getRightLoc());
12858   }
12859   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12860            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12861     if (!E->getMethodDecl())
12862       return ExprError();
12863 
12864     // Build a new class message send to 'super'.
12865     SmallVector<SourceLocation, 16> SelLocs;
12866     E->getSelectorLocs(SelLocs);
12867     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12868                                                E->getSelector(),
12869                                                SelLocs,
12870                                                E->getReceiverType(),
12871                                                E->getMethodDecl(),
12872                                                E->getLeftLoc(),
12873                                                Args,
12874                                                E->getRightLoc());
12875   }
12876 
12877   // Instance message: transform the receiver
12878   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12879          "Only class and instance messages may be instantiated");
12880   ExprResult Receiver
12881     = getDerived().TransformExpr(E->getInstanceReceiver());
12882   if (Receiver.isInvalid())
12883     return ExprError();
12884 
12885   // If nothing changed, just retain the existing message send.
12886   if (!getDerived().AlwaysRebuild() &&
12887       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12888     return SemaRef.MaybeBindToTemporary(E);
12889 
12890   // Build a new instance message send.
12891   SmallVector<SourceLocation, 16> SelLocs;
12892   E->getSelectorLocs(SelLocs);
12893   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12894                                              E->getSelector(),
12895                                              SelLocs,
12896                                              E->getMethodDecl(),
12897                                              E->getLeftLoc(),
12898                                              Args,
12899                                              E->getRightLoc());
12900 }
12901 
12902 template<typename Derived>
12903 ExprResult
12904 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12905   return E;
12906 }
12907 
12908 template<typename Derived>
12909 ExprResult
12910 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12911   return E;
12912 }
12913 
12914 template<typename Derived>
12915 ExprResult
12916 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12917   // Transform the base expression.
12918   ExprResult Base = getDerived().TransformExpr(E->getBase());
12919   if (Base.isInvalid())
12920     return ExprError();
12921 
12922   // We don't need to transform the ivar; it will never change.
12923 
12924   // If nothing changed, just retain the existing expression.
12925   if (!getDerived().AlwaysRebuild() &&
12926       Base.get() == E->getBase())
12927     return E;
12928 
12929   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12930                                              E->getLocation(),
12931                                              E->isArrow(), E->isFreeIvar());
12932 }
12933 
12934 template<typename Derived>
12935 ExprResult
12936 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12937   // 'super' and types never change. Property never changes. Just
12938   // retain the existing expression.
12939   if (!E->isObjectReceiver())
12940     return E;
12941 
12942   // Transform the base expression.
12943   ExprResult Base = getDerived().TransformExpr(E->getBase());
12944   if (Base.isInvalid())
12945     return ExprError();
12946 
12947   // We don't need to transform the property; it will never change.
12948 
12949   // If nothing changed, just retain the existing expression.
12950   if (!getDerived().AlwaysRebuild() &&
12951       Base.get() == E->getBase())
12952     return E;
12953 
12954   if (E->isExplicitProperty())
12955     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12956                                                    E->getExplicitProperty(),
12957                                                    E->getLocation());
12958 
12959   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12960                                                  SemaRef.Context.PseudoObjectTy,
12961                                                  E->getImplicitPropertyGetter(),
12962                                                  E->getImplicitPropertySetter(),
12963                                                  E->getLocation());
12964 }
12965 
12966 template<typename Derived>
12967 ExprResult
12968 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12969   // Transform the base expression.
12970   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12971   if (Base.isInvalid())
12972     return ExprError();
12973 
12974   // Transform the key expression.
12975   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12976   if (Key.isInvalid())
12977     return ExprError();
12978 
12979   // If nothing changed, just retain the existing expression.
12980   if (!getDerived().AlwaysRebuild() &&
12981       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12982     return E;
12983 
12984   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12985                                                   Base.get(), Key.get(),
12986                                                   E->getAtIndexMethodDecl(),
12987                                                   E->setAtIndexMethodDecl());
12988 }
12989 
12990 template<typename Derived>
12991 ExprResult
12992 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12993   // Transform the base expression.
12994   ExprResult Base = getDerived().TransformExpr(E->getBase());
12995   if (Base.isInvalid())
12996     return ExprError();
12997 
12998   // If nothing changed, just retain the existing expression.
12999   if (!getDerived().AlwaysRebuild() &&
13000       Base.get() == E->getBase())
13001     return E;
13002 
13003   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
13004                                          E->getOpLoc(),
13005                                          E->isArrow());
13006 }
13007 
13008 template<typename Derived>
13009 ExprResult
13010 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
13011   bool ArgumentChanged = false;
13012   SmallVector<Expr*, 8> SubExprs;
13013   SubExprs.reserve(E->getNumSubExprs());
13014   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
13015                                   SubExprs, &ArgumentChanged))
13016     return ExprError();
13017 
13018   if (!getDerived().AlwaysRebuild() &&
13019       !ArgumentChanged)
13020     return E;
13021 
13022   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
13023                                                SubExprs,
13024                                                E->getRParenLoc());
13025 }
13026 
13027 template<typename Derived>
13028 ExprResult
13029 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
13030   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
13031   if (SrcExpr.isInvalid())
13032     return ExprError();
13033 
13034   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
13035   if (!Type)
13036     return ExprError();
13037 
13038   if (!getDerived().AlwaysRebuild() &&
13039       Type == E->getTypeSourceInfo() &&
13040       SrcExpr.get() == E->getSrcExpr())
13041     return E;
13042 
13043   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
13044                                                SrcExpr.get(), Type,
13045                                                E->getRParenLoc());
13046 }
13047 
13048 template<typename Derived>
13049 ExprResult
13050 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
13051   BlockDecl *oldBlock = E->getBlockDecl();
13052 
13053   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
13054   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
13055 
13056   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
13057   blockScope->TheDecl->setBlockMissingReturnType(
13058                          oldBlock->blockMissingReturnType());
13059 
13060   SmallVector<ParmVarDecl*, 4> params;
13061   SmallVector<QualType, 4> paramTypes;
13062 
13063   const FunctionProtoType *exprFunctionType = E->getFunctionType();
13064 
13065   // Parameter substitution.
13066   Sema::ExtParameterInfoBuilder extParamInfos;
13067   if (getDerived().TransformFunctionTypeParams(
13068           E->getCaretLocation(), oldBlock->parameters(), nullptr,
13069           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
13070           extParamInfos)) {
13071     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
13072     return ExprError();
13073   }
13074 
13075   QualType exprResultType =
13076       getDerived().TransformType(exprFunctionType->getReturnType());
13077 
13078   auto epi = exprFunctionType->getExtProtoInfo();
13079   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
13080 
13081   QualType functionType =
13082     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
13083   blockScope->FunctionType = functionType;
13084 
13085   // Set the parameters on the block decl.
13086   if (!params.empty())
13087     blockScope->TheDecl->setParams(params);
13088 
13089   if (!oldBlock->blockMissingReturnType()) {
13090     blockScope->HasImplicitReturnType = false;
13091     blockScope->ReturnType = exprResultType;
13092   }
13093 
13094   // Transform the body
13095   StmtResult body = getDerived().TransformStmt(E->getBody());
13096   if (body.isInvalid()) {
13097     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
13098     return ExprError();
13099   }
13100 
13101 #ifndef NDEBUG
13102   // In builds with assertions, make sure that we captured everything we
13103   // captured before.
13104   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
13105     for (const auto &I : oldBlock->captures()) {
13106       VarDecl *oldCapture = I.getVariable();
13107 
13108       // Ignore parameter packs.
13109       if (oldCapture->isParameterPack())
13110         continue;
13111 
13112       VarDecl *newCapture =
13113         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
13114                                                  oldCapture));
13115       assert(blockScope->CaptureMap.count(newCapture));
13116     }
13117     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
13118   }
13119 #endif
13120 
13121   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
13122                                     /*Scope=*/nullptr);
13123 }
13124 
13125 template<typename Derived>
13126 ExprResult
13127 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
13128   llvm_unreachable("Cannot transform asType expressions yet");
13129 }
13130 
13131 template<typename Derived>
13132 ExprResult
13133 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
13134   bool ArgumentChanged = false;
13135   SmallVector<Expr*, 8> SubExprs;
13136   SubExprs.reserve(E->getNumSubExprs());
13137   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
13138                                   SubExprs, &ArgumentChanged))
13139     return ExprError();
13140 
13141   if (!getDerived().AlwaysRebuild() &&
13142       !ArgumentChanged)
13143     return E;
13144 
13145   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
13146                                         E->getOp(), E->getRParenLoc());
13147 }
13148 
13149 //===----------------------------------------------------------------------===//
13150 // Type reconstruction
13151 //===----------------------------------------------------------------------===//
13152 
13153 template<typename Derived>
13154 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
13155                                                     SourceLocation Star) {
13156   return SemaRef.BuildPointerType(PointeeType, Star,
13157                                   getDerived().getBaseEntity());
13158 }
13159 
13160 template<typename Derived>
13161 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
13162                                                          SourceLocation Star) {
13163   return SemaRef.BuildBlockPointerType(PointeeType, Star,
13164                                        getDerived().getBaseEntity());
13165 }
13166 
13167 template<typename Derived>
13168 QualType
13169 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
13170                                              bool WrittenAsLValue,
13171                                              SourceLocation Sigil) {
13172   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
13173                                     Sigil, getDerived().getBaseEntity());
13174 }
13175 
13176 template<typename Derived>
13177 QualType
13178 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
13179                                                  QualType ClassType,
13180                                                  SourceLocation Sigil) {
13181   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
13182                                         getDerived().getBaseEntity());
13183 }
13184 
13185 template<typename Derived>
13186 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
13187            const ObjCTypeParamDecl *Decl,
13188            SourceLocation ProtocolLAngleLoc,
13189            ArrayRef<ObjCProtocolDecl *> Protocols,
13190            ArrayRef<SourceLocation> ProtocolLocs,
13191            SourceLocation ProtocolRAngleLoc) {
13192   return SemaRef.BuildObjCTypeParamType(Decl,
13193                                         ProtocolLAngleLoc, Protocols,
13194                                         ProtocolLocs, ProtocolRAngleLoc,
13195                                         /*FailOnError=*/true);
13196 }
13197 
13198 template<typename Derived>
13199 QualType TreeTransform<Derived>::RebuildObjCObjectType(
13200            QualType BaseType,
13201            SourceLocation Loc,
13202            SourceLocation TypeArgsLAngleLoc,
13203            ArrayRef<TypeSourceInfo *> TypeArgs,
13204            SourceLocation TypeArgsRAngleLoc,
13205            SourceLocation ProtocolLAngleLoc,
13206            ArrayRef<ObjCProtocolDecl *> Protocols,
13207            ArrayRef<SourceLocation> ProtocolLocs,
13208            SourceLocation ProtocolRAngleLoc) {
13209   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
13210                                      TypeArgs, TypeArgsRAngleLoc,
13211                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
13212                                      ProtocolRAngleLoc,
13213                                      /*FailOnError=*/true);
13214 }
13215 
13216 template<typename Derived>
13217 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
13218            QualType PointeeType,
13219            SourceLocation Star) {
13220   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
13221 }
13222 
13223 template<typename Derived>
13224 QualType
13225 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
13226                                          ArrayType::ArraySizeModifier SizeMod,
13227                                          const llvm::APInt *Size,
13228                                          Expr *SizeExpr,
13229                                          unsigned IndexTypeQuals,
13230                                          SourceRange BracketsRange) {
13231   if (SizeExpr || !Size)
13232     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
13233                                   IndexTypeQuals, BracketsRange,
13234                                   getDerived().getBaseEntity());
13235 
13236   QualType Types[] = {
13237     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
13238     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
13239     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
13240   };
13241   const unsigned NumTypes = llvm::array_lengthof(Types);
13242   QualType SizeType;
13243   for (unsigned I = 0; I != NumTypes; ++I)
13244     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
13245       SizeType = Types[I];
13246       break;
13247     }
13248 
13249   // Note that we can return a VariableArrayType here in the case where
13250   // the element type was a dependent VariableArrayType.
13251   IntegerLiteral *ArraySize
13252       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
13253                                /*FIXME*/BracketsRange.getBegin());
13254   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
13255                                 IndexTypeQuals, BracketsRange,
13256                                 getDerived().getBaseEntity());
13257 }
13258 
13259 template<typename Derived>
13260 QualType
13261 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
13262                                                  ArrayType::ArraySizeModifier SizeMod,
13263                                                  const llvm::APInt &Size,
13264                                                  Expr *SizeExpr,
13265                                                  unsigned IndexTypeQuals,
13266                                                  SourceRange BracketsRange) {
13267   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
13268                                         IndexTypeQuals, BracketsRange);
13269 }
13270 
13271 template<typename Derived>
13272 QualType
13273 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
13274                                           ArrayType::ArraySizeModifier SizeMod,
13275                                                  unsigned IndexTypeQuals,
13276                                                    SourceRange BracketsRange) {
13277   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
13278                                        IndexTypeQuals, BracketsRange);
13279 }
13280 
13281 template<typename Derived>
13282 QualType
13283 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
13284                                           ArrayType::ArraySizeModifier SizeMod,
13285                                                  Expr *SizeExpr,
13286                                                  unsigned IndexTypeQuals,
13287                                                  SourceRange BracketsRange) {
13288   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
13289                                        SizeExpr,
13290                                        IndexTypeQuals, BracketsRange);
13291 }
13292 
13293 template<typename Derived>
13294 QualType
13295 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
13296                                           ArrayType::ArraySizeModifier SizeMod,
13297                                                        Expr *SizeExpr,
13298                                                        unsigned IndexTypeQuals,
13299                                                    SourceRange BracketsRange) {
13300   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
13301                                        SizeExpr,
13302                                        IndexTypeQuals, BracketsRange);
13303 }
13304 
13305 template <typename Derived>
13306 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
13307     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
13308   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
13309                                           AttributeLoc);
13310 }
13311 
13312 template <typename Derived>
13313 QualType
13314 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
13315                                           unsigned NumElements,
13316                                           VectorType::VectorKind VecKind) {
13317   // FIXME: semantic checking!
13318   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
13319 }
13320 
13321 template <typename Derived>
13322 QualType TreeTransform<Derived>::RebuildDependentVectorType(
13323     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
13324     VectorType::VectorKind VecKind) {
13325   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
13326 }
13327 
13328 template<typename Derived>
13329 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
13330                                                       unsigned NumElements,
13331                                                  SourceLocation AttributeLoc) {
13332   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
13333                           NumElements, true);
13334   IntegerLiteral *VectorSize
13335     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
13336                              AttributeLoc);
13337   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
13338 }
13339 
13340 template<typename Derived>
13341 QualType
13342 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
13343                                                            Expr *SizeExpr,
13344                                                   SourceLocation AttributeLoc) {
13345   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
13346 }
13347 
13348 template<typename Derived>
13349 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
13350     QualType T,
13351     MutableArrayRef<QualType> ParamTypes,
13352     const FunctionProtoType::ExtProtoInfo &EPI) {
13353   return SemaRef.BuildFunctionType(T, ParamTypes,
13354                                    getDerived().getBaseLocation(),
13355                                    getDerived().getBaseEntity(),
13356                                    EPI);
13357 }
13358 
13359 template<typename Derived>
13360 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
13361   return SemaRef.Context.getFunctionNoProtoType(T);
13362 }
13363 
13364 template<typename Derived>
13365 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
13366                                                             Decl *D) {
13367   assert(D && "no decl found");
13368   if (D->isInvalidDecl()) return QualType();
13369 
13370   // FIXME: Doesn't account for ObjCInterfaceDecl!
13371   TypeDecl *Ty;
13372   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
13373     // A valid resolved using typename pack expansion decl can have multiple
13374     // UsingDecls, but they must each have exactly one type, and it must be
13375     // the same type in every case. But we must have at least one expansion!
13376     if (UPD->expansions().empty()) {
13377       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
13378           << UPD->isCXXClassMember() << UPD;
13379       return QualType();
13380     }
13381 
13382     // We might still have some unresolved types. Try to pick a resolved type
13383     // if we can. The final instantiation will check that the remaining
13384     // unresolved types instantiate to the type we pick.
13385     QualType FallbackT;
13386     QualType T;
13387     for (auto *E : UPD->expansions()) {
13388       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
13389       if (ThisT.isNull())
13390         continue;
13391       else if (ThisT->getAs<UnresolvedUsingType>())
13392         FallbackT = ThisT;
13393       else if (T.isNull())
13394         T = ThisT;
13395       else
13396         assert(getSema().Context.hasSameType(ThisT, T) &&
13397                "mismatched resolved types in using pack expansion");
13398     }
13399     return T.isNull() ? FallbackT : T;
13400   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
13401     assert(Using->hasTypename() &&
13402            "UnresolvedUsingTypenameDecl transformed to non-typename using");
13403 
13404     // A valid resolved using typename decl points to exactly one type decl.
13405     assert(++Using->shadow_begin() == Using->shadow_end());
13406     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
13407   } else {
13408     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
13409            "UnresolvedUsingTypenameDecl transformed to non-using decl");
13410     Ty = cast<UnresolvedUsingTypenameDecl>(D);
13411   }
13412 
13413   return SemaRef.Context.getTypeDeclType(Ty);
13414 }
13415 
13416 template<typename Derived>
13417 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
13418                                                        SourceLocation Loc) {
13419   return SemaRef.BuildTypeofExprType(E, Loc);
13420 }
13421 
13422 template<typename Derived>
13423 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
13424   return SemaRef.Context.getTypeOfType(Underlying);
13425 }
13426 
13427 template<typename Derived>
13428 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
13429                                                      SourceLocation Loc) {
13430   return SemaRef.BuildDecltypeType(E, Loc);
13431 }
13432 
13433 template<typename Derived>
13434 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
13435                                             UnaryTransformType::UTTKind UKind,
13436                                             SourceLocation Loc) {
13437   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
13438 }
13439 
13440 template<typename Derived>
13441 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
13442                                                       TemplateName Template,
13443                                              SourceLocation TemplateNameLoc,
13444                                      TemplateArgumentListInfo &TemplateArgs) {
13445   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
13446 }
13447 
13448 template<typename Derived>
13449 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
13450                                                    SourceLocation KWLoc) {
13451   return SemaRef.BuildAtomicType(ValueType, KWLoc);
13452 }
13453 
13454 template<typename Derived>
13455 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
13456                                                  SourceLocation KWLoc,
13457                                                  bool isReadPipe) {
13458   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
13459                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
13460 }
13461 
13462 template<typename Derived>
13463 TemplateName
13464 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13465                                             bool TemplateKW,
13466                                             TemplateDecl *Template) {
13467   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13468                                                   Template);
13469 }
13470 
13471 template<typename Derived>
13472 TemplateName
13473 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13474                                             SourceLocation TemplateKWLoc,
13475                                             const IdentifierInfo &Name,
13476                                             SourceLocation NameLoc,
13477                                             QualType ObjectType,
13478                                             NamedDecl *FirstQualifierInScope,
13479                                             bool AllowInjectedClassName) {
13480   UnqualifiedId TemplateName;
13481   TemplateName.setIdentifier(&Name, NameLoc);
13482   Sema::TemplateTy Template;
13483   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13484                                        SS, TemplateKWLoc, TemplateName,
13485                                        ParsedType::make(ObjectType),
13486                                        /*EnteringContext=*/false,
13487                                        Template, AllowInjectedClassName);
13488   return Template.get();
13489 }
13490 
13491 template<typename Derived>
13492 TemplateName
13493 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13494                                             SourceLocation TemplateKWLoc,
13495                                             OverloadedOperatorKind Operator,
13496                                             SourceLocation NameLoc,
13497                                             QualType ObjectType,
13498                                             bool AllowInjectedClassName) {
13499   UnqualifiedId Name;
13500   // FIXME: Bogus location information.
13501   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13502   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13503   Sema::TemplateTy Template;
13504   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13505                                        SS, TemplateKWLoc, Name,
13506                                        ParsedType::make(ObjectType),
13507                                        /*EnteringContext=*/false,
13508                                        Template, AllowInjectedClassName);
13509   return Template.get();
13510 }
13511 
13512 template<typename Derived>
13513 ExprResult
13514 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13515                                                    SourceLocation OpLoc,
13516                                                    Expr *OrigCallee,
13517                                                    Expr *First,
13518                                                    Expr *Second) {
13519   Expr *Callee = OrigCallee->IgnoreParenCasts();
13520   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13521 
13522   if (First->getObjectKind() == OK_ObjCProperty) {
13523     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13524     if (BinaryOperator::isAssignmentOp(Opc))
13525       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13526                                                  First, Second);
13527     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13528     if (Result.isInvalid())
13529       return ExprError();
13530     First = Result.get();
13531   }
13532 
13533   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13534     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13535     if (Result.isInvalid())
13536       return ExprError();
13537     Second = Result.get();
13538   }
13539 
13540   // Determine whether this should be a builtin operation.
13541   if (Op == OO_Subscript) {
13542     if (!First->getType()->isOverloadableType() &&
13543         !Second->getType()->isOverloadableType())
13544       return getSema().CreateBuiltinArraySubscriptExpr(
13545           First, Callee->getBeginLoc(), Second, OpLoc);
13546   } else if (Op == OO_Arrow) {
13547     // -> is never a builtin operation.
13548     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13549   } else if (Second == nullptr || isPostIncDec) {
13550     if (!First->getType()->isOverloadableType() ||
13551         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13552       // The argument is not of overloadable type, or this is an expression
13553       // of the form &Class::member, so try to create a built-in unary
13554       // operation.
13555       UnaryOperatorKind Opc
13556         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13557 
13558       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13559     }
13560   } else {
13561     if (!First->getType()->isOverloadableType() &&
13562         !Second->getType()->isOverloadableType()) {
13563       // Neither of the arguments is an overloadable type, so try to
13564       // create a built-in binary operation.
13565       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13566       ExprResult Result
13567         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13568       if (Result.isInvalid())
13569         return ExprError();
13570 
13571       return Result;
13572     }
13573   }
13574 
13575   // Compute the transformed set of functions (and function templates) to be
13576   // used during overload resolution.
13577   UnresolvedSet<16> Functions;
13578   bool RequiresADL;
13579 
13580   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13581     Functions.append(ULE->decls_begin(), ULE->decls_end());
13582     // If the overload could not be resolved in the template definition
13583     // (because we had a dependent argument), ADL is performed as part of
13584     // template instantiation.
13585     RequiresADL = ULE->requiresADL();
13586   } else {
13587     // If we've resolved this to a particular non-member function, just call
13588     // that function. If we resolved it to a member function,
13589     // CreateOverloaded* will find that function for us.
13590     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13591     if (!isa<CXXMethodDecl>(ND))
13592       Functions.addDecl(ND);
13593     RequiresADL = false;
13594   }
13595 
13596   // Add any functions found via argument-dependent lookup.
13597   Expr *Args[2] = { First, Second };
13598   unsigned NumArgs = 1 + (Second != nullptr);
13599 
13600   // Create the overloaded operator invocation for unary operators.
13601   if (NumArgs == 1 || isPostIncDec) {
13602     UnaryOperatorKind Opc
13603       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13604     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13605                                            RequiresADL);
13606   }
13607 
13608   if (Op == OO_Subscript) {
13609     SourceLocation LBrace;
13610     SourceLocation RBrace;
13611 
13612     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13613         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13614         LBrace = SourceLocation::getFromRawEncoding(
13615                     NameLoc.CXXOperatorName.BeginOpNameLoc);
13616         RBrace = SourceLocation::getFromRawEncoding(
13617                     NameLoc.CXXOperatorName.EndOpNameLoc);
13618     } else {
13619       LBrace = Callee->getBeginLoc();
13620       RBrace = OpLoc;
13621     }
13622 
13623     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13624                                                       First, Second);
13625   }
13626 
13627   // Create the overloaded operator invocation for binary operators.
13628   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13629   ExprResult Result = SemaRef.CreateOverloadedBinOp(
13630       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13631   if (Result.isInvalid())
13632     return ExprError();
13633 
13634   return Result;
13635 }
13636 
13637 template<typename Derived>
13638 ExprResult
13639 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13640                                                      SourceLocation OperatorLoc,
13641                                                        bool isArrow,
13642                                                        CXXScopeSpec &SS,
13643                                                      TypeSourceInfo *ScopeType,
13644                                                        SourceLocation CCLoc,
13645                                                        SourceLocation TildeLoc,
13646                                         PseudoDestructorTypeStorage Destroyed) {
13647   QualType BaseType = Base->getType();
13648   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13649       (!isArrow && !BaseType->getAs<RecordType>()) ||
13650       (isArrow && BaseType->getAs<PointerType>() &&
13651        !BaseType->castAs<PointerType>()->getPointeeType()
13652                                               ->template getAs<RecordType>())){
13653     // This pseudo-destructor expression is still a pseudo-destructor.
13654     return SemaRef.BuildPseudoDestructorExpr(
13655         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13656         CCLoc, TildeLoc, Destroyed);
13657   }
13658 
13659   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13660   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13661                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13662   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13663   NameInfo.setNamedTypeInfo(DestroyedType);
13664 
13665   // The scope type is now known to be a valid nested name specifier
13666   // component. Tack it on to the end of the nested name specifier.
13667   if (ScopeType) {
13668     if (!ScopeType->getType()->getAs<TagType>()) {
13669       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13670                      diag::err_expected_class_or_namespace)
13671           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13672       return ExprError();
13673     }
13674     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13675               CCLoc);
13676   }
13677 
13678   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13679   return getSema().BuildMemberReferenceExpr(Base, BaseType,
13680                                             OperatorLoc, isArrow,
13681                                             SS, TemplateKWLoc,
13682                                             /*FIXME: FirstQualifier*/ nullptr,
13683                                             NameInfo,
13684                                             /*TemplateArgs*/ nullptr,
13685                                             /*S*/nullptr);
13686 }
13687 
13688 template<typename Derived>
13689 StmtResult
13690 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13691   SourceLocation Loc = S->getBeginLoc();
13692   CapturedDecl *CD = S->getCapturedDecl();
13693   unsigned NumParams = CD->getNumParams();
13694   unsigned ContextParamPos = CD->getContextParamPosition();
13695   SmallVector<Sema::CapturedParamNameType, 4> Params;
13696   for (unsigned I = 0; I < NumParams; ++I) {
13697     if (I != ContextParamPos) {
13698       Params.push_back(
13699              std::make_pair(
13700                   CD->getParam(I)->getName(),
13701                   getDerived().TransformType(CD->getParam(I)->getType())));
13702     } else {
13703       Params.push_back(std::make_pair(StringRef(), QualType()));
13704     }
13705   }
13706   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13707                                      S->getCapturedRegionKind(), Params);
13708   StmtResult Body;
13709   {
13710     Sema::CompoundScopeRAII CompoundScope(getSema());
13711     Body = getDerived().TransformStmt(S->getCapturedStmt());
13712   }
13713 
13714   if (Body.isInvalid()) {
13715     getSema().ActOnCapturedRegionError();
13716     return StmtError();
13717   }
13718 
13719   return getSema().ActOnCapturedRegionEnd(Body.get());
13720 }
13721 
13722 } // end namespace clang
13723 
13724 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
13725