xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 3a9a9c0ca44ec535dcf73fe8462bee458e54814b)
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/Basic/DiagnosticParse.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Sema/Designator.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/Ownership.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaDiagnostic.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include <algorithm>
43 
44 using namespace llvm::omp;
45 
46 namespace clang {
47 using namespace sema;
48 
49 /// A semantic tree transformation that allows one to transform one
50 /// abstract syntax tree into another.
51 ///
52 /// A new tree transformation is defined by creating a new subclass \c X of
53 /// \c TreeTransform<X> and then overriding certain operations to provide
54 /// behavior specific to that transformation. For example, template
55 /// instantiation is implemented as a tree transformation where the
56 /// transformation of TemplateTypeParmType nodes involves substituting the
57 /// template arguments for their corresponding template parameters; a similar
58 /// transformation is performed for non-type template parameters and
59 /// template template parameters.
60 ///
61 /// This tree-transformation template uses static polymorphism to allow
62 /// subclasses to customize any of its operations. Thus, a subclass can
63 /// override any of the transformation or rebuild operators by providing an
64 /// operation with the same signature as the default implementation. The
65 /// overriding function should not be virtual.
66 ///
67 /// Semantic tree transformations are split into two stages, either of which
68 /// can be replaced by a subclass. The "transform" step transforms an AST node
69 /// or the parts of an AST node using the various transformation functions,
70 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
71 /// node of the appropriate kind from the pieces. The default transformation
72 /// routines recursively transform the operands to composite AST nodes (e.g.,
73 /// the pointee type of a PointerType node) and, if any of those operand nodes
74 /// were changed by the transformation, invokes the rebuild operation to create
75 /// a new AST node.
76 ///
77 /// Subclasses can customize the transformation at various levels. The
78 /// most coarse-grained transformations involve replacing TransformType(),
79 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
80 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
81 /// new implementations.
82 ///
83 /// For more fine-grained transformations, subclasses can replace any of the
84 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
85 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
86 /// replacing TransformTemplateTypeParmType() allows template instantiation
87 /// to substitute template arguments for their corresponding template
88 /// parameters. Additionally, subclasses can override the \c RebuildXXX
89 /// functions to control how AST nodes are rebuilt when their operands change.
90 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
91 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
92 /// be able to use more efficient rebuild steps.
93 ///
94 /// There are a handful of other functions that can be overridden, allowing one
95 /// to avoid traversing nodes that don't need any transformation
96 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
97 /// operands have not changed (\c AlwaysRebuild()), and customize the
98 /// default locations and entity names used for type-checking
99 /// (\c getBaseLocation(), \c getBaseEntity()).
100 template<typename Derived>
101 class TreeTransform {
102   /// Private RAII object that helps us forget and then re-remember
103   /// the template argument corresponding to a partially-substituted parameter
104   /// pack.
105   class ForgetPartiallySubstitutedPackRAII {
106     Derived &Self;
107     TemplateArgument Old;
108 
109   public:
110     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
111       Old = Self.ForgetPartiallySubstitutedPack();
112     }
113 
114     ~ForgetPartiallySubstitutedPackRAII() {
115       Self.RememberPartiallySubstitutedPack(Old);
116     }
117   };
118 
119 protected:
120   Sema &SemaRef;
121 
122   /// The set of local declarations that have been transformed, for
123   /// cases where we are forced to build new declarations within the transformer
124   /// rather than in the subclass (e.g., lambda closure types).
125   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
126 
127 public:
128   /// Initializes a new tree transformer.
129   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
130 
131   /// Retrieves a reference to the derived class.
132   Derived &getDerived() { return static_cast<Derived&>(*this); }
133 
134   /// Retrieves a reference to the derived class.
135   const Derived &getDerived() const {
136     return static_cast<const Derived&>(*this);
137   }
138 
139   static inline ExprResult Owned(Expr *E) { return E; }
140   static inline StmtResult Owned(Stmt *S) { return S; }
141 
142   /// Retrieves a reference to the semantic analysis object used for
143   /// this tree transform.
144   Sema &getSema() const { return SemaRef; }
145 
146   /// Whether the transformation should always rebuild AST nodes, even
147   /// if none of the children have changed.
148   ///
149   /// Subclasses may override this function to specify when the transformation
150   /// should rebuild all AST nodes.
151   ///
152   /// We must always rebuild all AST nodes when performing variadic template
153   /// pack expansion, in order to avoid violating the AST invariant that each
154   /// statement node appears at most once in its containing declaration.
155   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
156 
157   /// Whether the transformation is forming an expression or statement that
158   /// replaces the original. In this case, we'll reuse mangling numbers from
159   /// existing lambdas.
160   bool ReplacingOriginal() { return false; }
161 
162   /// Wether CXXConstructExpr can be skipped when they are implicit.
163   /// They will be reconstructed when used if needed.
164   /// This is useful when the user that cause rebuilding of the
165   /// CXXConstructExpr is outside of the expression at which the TreeTransform
166   /// started.
167   bool AllowSkippingCXXConstructExpr() { return true; }
168 
169   /// Returns the location of the entity being transformed, if that
170   /// information was not available elsewhere in the AST.
171   ///
172   /// By default, returns no source-location information. Subclasses can
173   /// provide an alternative implementation that provides better location
174   /// information.
175   SourceLocation getBaseLocation() { return SourceLocation(); }
176 
177   /// Returns the name of the entity being transformed, if that
178   /// information was not available elsewhere in the AST.
179   ///
180   /// By default, returns an empty name. Subclasses can provide an alternative
181   /// implementation with a more precise name.
182   DeclarationName getBaseEntity() { return DeclarationName(); }
183 
184   /// Sets the "base" location and entity when that
185   /// information is known based on another transformation.
186   ///
187   /// By default, the source location and entity are ignored. Subclasses can
188   /// override this function to provide a customized implementation.
189   void setBase(SourceLocation Loc, DeclarationName Entity) { }
190 
191   /// RAII object that temporarily sets the base location and entity
192   /// used for reporting diagnostics in types.
193   class TemporaryBase {
194     TreeTransform &Self;
195     SourceLocation OldLocation;
196     DeclarationName OldEntity;
197 
198   public:
199     TemporaryBase(TreeTransform &Self, SourceLocation Location,
200                   DeclarationName Entity) : Self(Self) {
201       OldLocation = Self.getDerived().getBaseLocation();
202       OldEntity = Self.getDerived().getBaseEntity();
203 
204       if (Location.isValid())
205         Self.getDerived().setBase(Location, Entity);
206     }
207 
208     ~TemporaryBase() {
209       Self.getDerived().setBase(OldLocation, OldEntity);
210     }
211   };
212 
213   /// Determine whether the given type \p T has already been
214   /// transformed.
215   ///
216   /// Subclasses can provide an alternative implementation of this routine
217   /// to short-circuit evaluation when it is known that a given type will
218   /// not change. For example, template instantiation need not traverse
219   /// non-dependent types.
220   bool AlreadyTransformed(QualType T) {
221     return T.isNull();
222   }
223 
224   /// Transform a template parameter depth level.
225   ///
226   /// During a transformation that transforms template parameters, this maps
227   /// an old template parameter depth to a new depth.
228   unsigned TransformTemplateDepth(unsigned Depth) {
229     return Depth;
230   }
231 
232   /// Determine whether the given call argument should be dropped, e.g.,
233   /// because it is a default argument.
234   ///
235   /// Subclasses can provide an alternative implementation of this routine to
236   /// determine which kinds of call arguments get dropped. By default,
237   /// CXXDefaultArgument nodes are dropped (prior to transformation).
238   bool DropCallArgument(Expr *E) {
239     return E->isDefaultArgument();
240   }
241 
242   /// Determine whether we should expand a pack expansion with the
243   /// given set of parameter packs into separate arguments by repeatedly
244   /// transforming the pattern.
245   ///
246   /// By default, the transformer never tries to expand pack expansions.
247   /// Subclasses can override this routine to provide different behavior.
248   ///
249   /// \param EllipsisLoc The location of the ellipsis that identifies the
250   /// pack expansion.
251   ///
252   /// \param PatternRange The source range that covers the entire pattern of
253   /// the pack expansion.
254   ///
255   /// \param Unexpanded The set of unexpanded parameter packs within the
256   /// pattern.
257   ///
258   /// \param ShouldExpand Will be set to \c true if the transformer should
259   /// expand the corresponding pack expansions into separate arguments. When
260   /// set, \c NumExpansions must also be set.
261   ///
262   /// \param RetainExpansion Whether the caller should add an unexpanded
263   /// pack expansion after all of the expanded arguments. This is used
264   /// when extending explicitly-specified template argument packs per
265   /// C++0x [temp.arg.explicit]p9.
266   ///
267   /// \param NumExpansions The number of separate arguments that will be in
268   /// the expanded form of the corresponding pack expansion. This is both an
269   /// input and an output parameter, which can be set by the caller if the
270   /// number of expansions is known a priori (e.g., due to a prior substitution)
271   /// and will be set by the callee when the number of expansions is known.
272   /// The callee must set this value when \c ShouldExpand is \c true; it may
273   /// set this value in other cases.
274   ///
275   /// \returns true if an error occurred (e.g., because the parameter packs
276   /// are to be instantiated with arguments of different lengths), false
277   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
278   /// must be set.
279   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
280                                SourceRange PatternRange,
281                                ArrayRef<UnexpandedParameterPack> Unexpanded,
282                                bool &ShouldExpand,
283                                bool &RetainExpansion,
284                                Optional<unsigned> &NumExpansions) {
285     ShouldExpand = false;
286     return false;
287   }
288 
289   /// "Forget" about the partially-substituted pack template argument,
290   /// when 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   TemplateArgument ForgetPartiallySubstitutedPack() {
295     return TemplateArgument();
296   }
297 
298   /// "Remember" the partially-substituted pack template argument
299   /// after performing an instantiation that must preserve the parameter pack
300   /// use.
301   ///
302   /// This routine is meant to be overridden by the template instantiator.
303   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304 
305   /// Note to the derived class when a function parameter pack is
306   /// being expanded.
307   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308 
309   /// Transforms the given type into another type.
310   ///
311   /// By default, this routine transforms a type by creating a
312   /// TypeSourceInfo for it and delegating to the appropriate
313   /// function.  This is expensive, but we don't mind, because
314   /// this method is deprecated anyway;  all users should be
315   /// switched to storing TypeSourceInfos.
316   ///
317   /// \returns the transformed type.
318   QualType TransformType(QualType T);
319 
320   /// Transforms the given type-with-location into a new
321   /// type-with-location.
322   ///
323   /// By default, this routine transforms a type by delegating to the
324   /// appropriate TransformXXXType to build a new type.  Subclasses
325   /// may override this function (to take over all type
326   /// transformations) or some set of the TransformXXXType functions
327   /// to alter the transformation.
328   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329 
330   /// Transform the given type-with-location into a new
331   /// type, collecting location information in the given builder
332   /// as necessary.
333   ///
334   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335 
336   /// Transform a type that is permitted to produce a
337   /// DeducedTemplateSpecializationType.
338   ///
339   /// This is used in the (relatively rare) contexts where it is acceptable
340   /// for transformation to produce a class template type with deduced
341   /// template arguments.
342   /// @{
343   QualType TransformTypeWithDeducedTST(QualType T);
344   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345   /// @}
346 
347   /// The reason why the value of a statement is not discarded, if any.
348   enum StmtDiscardKind {
349     SDK_Discarded,
350     SDK_NotDiscarded,
351     SDK_StmtExprResult,
352   };
353 
354   /// Transform the given statement.
355   ///
356   /// By default, this routine transforms a statement by delegating to the
357   /// appropriate TransformXXXStmt function to transform a specific kind of
358   /// statement or the TransformExpr() function to transform an expression.
359   /// Subclasses may override this function to transform statements using some
360   /// other mechanism.
361   ///
362   /// \returns the transformed statement.
363   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364 
365   /// Transform the given statement.
366   ///
367   /// By default, this routine transforms a statement by delegating to the
368   /// appropriate TransformOMPXXXClause function to transform a specific kind
369   /// of clause. Subclasses may override this function to transform statements
370   /// using some other mechanism.
371   ///
372   /// \returns the transformed OpenMP clause.
373   OMPClause *TransformOMPClause(OMPClause *S);
374 
375   /// Transform the given attribute.
376   ///
377   /// By default, this routine transforms a statement by delegating to the
378   /// appropriate TransformXXXAttr function to transform a specific kind
379   /// of attribute. Subclasses may override this function to transform
380   /// attributed statements using some other mechanism.
381   ///
382   /// \returns the transformed attribute
383   const Attr *TransformAttr(const Attr *S);
384 
385 /// Transform the specified attribute.
386 ///
387 /// Subclasses should override the transformation of attributes with a pragma
388 /// spelling to transform expressions stored within the attribute.
389 ///
390 /// \returns the transformed attribute.
391 #define ATTR(X)
392 #define PRAGMA_SPELLING_ATTR(X)                                                \
393   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
394 #include "clang/Basic/AttrList.inc"
395 
396   /// Transform the given expression.
397   ///
398   /// By default, this routine transforms an expression by delegating to the
399   /// appropriate TransformXXXExpr function to build a new expression.
400   /// Subclasses may override this function to transform expressions using some
401   /// other mechanism.
402   ///
403   /// \returns the transformed expression.
404   ExprResult TransformExpr(Expr *E);
405 
406   /// Transform the given initializer.
407   ///
408   /// By default, this routine transforms an initializer by stripping off the
409   /// semantic nodes added by initialization, then passing the result to
410   /// TransformExpr or TransformExprs.
411   ///
412   /// \returns the transformed initializer.
413   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
414 
415   /// Transform the given list of expressions.
416   ///
417   /// This routine transforms a list of expressions by invoking
418   /// \c TransformExpr() for each subexpression. However, it also provides
419   /// support for variadic templates by expanding any pack expansions (if the
420   /// derived class permits such expansion) along the way. When pack expansions
421   /// are present, the number of outputs may not equal the number of inputs.
422   ///
423   /// \param Inputs The set of expressions to be transformed.
424   ///
425   /// \param NumInputs The number of expressions in \c Inputs.
426   ///
427   /// \param IsCall If \c true, then this transform is being performed on
428   /// function-call arguments, and any arguments that should be dropped, will
429   /// be.
430   ///
431   /// \param Outputs The transformed input expressions will be added to this
432   /// vector.
433   ///
434   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
435   /// due to transformation.
436   ///
437   /// \returns true if an error occurred, false otherwise.
438   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
439                       SmallVectorImpl<Expr *> &Outputs,
440                       bool *ArgChanged = nullptr);
441 
442   /// Transform the given declaration, which is referenced from a type
443   /// or expression.
444   ///
445   /// By default, acts as the identity function on declarations, unless the
446   /// transformer has had to transform the declaration itself. Subclasses
447   /// may override this function to provide alternate behavior.
448   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
449     llvm::DenseMap<Decl *, Decl *>::iterator Known
450       = TransformedLocalDecls.find(D);
451     if (Known != TransformedLocalDecls.end())
452       return Known->second;
453 
454     return D;
455   }
456 
457   /// Transform the specified condition.
458   ///
459   /// By default, this transforms the variable and expression and rebuilds
460   /// the condition.
461   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
462                                            Expr *Expr,
463                                            Sema::ConditionKind Kind);
464 
465   /// Transform the attributes associated with the given declaration and
466   /// place them on the new declaration.
467   ///
468   /// By default, this operation does nothing. Subclasses may override this
469   /// behavior to transform attributes.
470   void transformAttrs(Decl *Old, Decl *New) { }
471 
472   /// Note that a local declaration has been transformed by this
473   /// transformer.
474   ///
475   /// Local declarations are typically transformed via a call to
476   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
477   /// the transformer itself has to transform the declarations. This routine
478   /// can be overridden by a subclass that keeps track of such mappings.
479   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
480     assert(New.size() == 1 &&
481            "must override transformedLocalDecl if performing pack expansion");
482     TransformedLocalDecls[Old] = New.front();
483   }
484 
485   /// Transform the definition of the given declaration.
486   ///
487   /// By default, invokes TransformDecl() to transform the declaration.
488   /// Subclasses may override this function to provide alternate behavior.
489   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
490     return getDerived().TransformDecl(Loc, D);
491   }
492 
493   /// Transform the given declaration, which was the first part of a
494   /// nested-name-specifier in a member access expression.
495   ///
496   /// This specific declaration transformation only applies to the first
497   /// identifier in a nested-name-specifier of a member access expression, e.g.,
498   /// the \c T in \c x->T::member
499   ///
500   /// By default, invokes TransformDecl() to transform the declaration.
501   /// Subclasses may override this function to provide alternate behavior.
502   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
503     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
504   }
505 
506   /// Transform the set of declarations in an OverloadExpr.
507   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
508                                   LookupResult &R);
509 
510   /// Transform the given nested-name-specifier with source-location
511   /// information.
512   ///
513   /// By default, transforms all of the types and declarations within the
514   /// nested-name-specifier. Subclasses may override this function to provide
515   /// alternate behavior.
516   NestedNameSpecifierLoc
517   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
518                                   QualType ObjectType = QualType(),
519                                   NamedDecl *FirstQualifierInScope = nullptr);
520 
521   /// Transform the given declaration name.
522   ///
523   /// By default, transforms the types of conversion function, constructor,
524   /// and destructor names and then (if needed) rebuilds the declaration name.
525   /// Identifiers and selectors are returned unmodified. Subclasses may
526   /// override this function to provide alternate behavior.
527   DeclarationNameInfo
528   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
529 
530   bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
531       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
532   concepts::TypeRequirement *
533   TransformTypeRequirement(concepts::TypeRequirement *Req);
534   concepts::ExprRequirement *
535   TransformExprRequirement(concepts::ExprRequirement *Req);
536   concepts::NestedRequirement *
537   TransformNestedRequirement(concepts::NestedRequirement *Req);
538 
539   /// Transform the given template name.
540   ///
541   /// \param SS The nested-name-specifier that qualifies the template
542   /// name. This nested-name-specifier must already have been transformed.
543   ///
544   /// \param Name The template name to transform.
545   ///
546   /// \param NameLoc The source location of the template name.
547   ///
548   /// \param ObjectType If we're translating a template name within a member
549   /// access expression, this is the type of the object whose member template
550   /// is being referenced.
551   ///
552   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
553   /// also refers to a name within the current (lexical) scope, this is the
554   /// declaration it refers to.
555   ///
556   /// By default, transforms the template name by transforming the declarations
557   /// and nested-name-specifiers that occur within the template name.
558   /// Subclasses may override this function to provide alternate behavior.
559   TemplateName
560   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
561                         SourceLocation NameLoc,
562                         QualType ObjectType = QualType(),
563                         NamedDecl *FirstQualifierInScope = nullptr,
564                         bool AllowInjectedClassName = false);
565 
566   /// Transform the given template argument.
567   ///
568   /// By default, this operation transforms the type, expression, or
569   /// declaration stored within the template argument and constructs a
570   /// new template argument from the transformed result. Subclasses may
571   /// override this function to provide alternate behavior.
572   ///
573   /// Returns true if there was an error.
574   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
575                                  TemplateArgumentLoc &Output,
576                                  bool Uneval = false);
577 
578   /// Transform the given set of template arguments.
579   ///
580   /// By default, this operation transforms all of the template arguments
581   /// in the input set using \c TransformTemplateArgument(), and appends
582   /// the transformed arguments to the output list.
583   ///
584   /// Note that this overload of \c TransformTemplateArguments() is merely
585   /// a convenience function. Subclasses that wish to override this behavior
586   /// should override the iterator-based member template version.
587   ///
588   /// \param Inputs The set of template arguments to be transformed.
589   ///
590   /// \param NumInputs The number of template arguments in \p Inputs.
591   ///
592   /// \param Outputs The set of transformed template arguments output by this
593   /// routine.
594   ///
595   /// Returns true if an error occurred.
596   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
597                                   unsigned NumInputs,
598                                   TemplateArgumentListInfo &Outputs,
599                                   bool Uneval = false) {
600     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
601                                       Uneval);
602   }
603 
604   /// Transform the given set of template arguments.
605   ///
606   /// By default, this operation transforms all of the template arguments
607   /// in the input set using \c TransformTemplateArgument(), and appends
608   /// the transformed arguments to the output list.
609   ///
610   /// \param First An iterator to the first template argument.
611   ///
612   /// \param Last An iterator one step past the last template argument.
613   ///
614   /// \param Outputs The set of transformed template arguments output by this
615   /// routine.
616   ///
617   /// Returns true if an error occurred.
618   template<typename InputIterator>
619   bool TransformTemplateArguments(InputIterator First,
620                                   InputIterator Last,
621                                   TemplateArgumentListInfo &Outputs,
622                                   bool Uneval = false);
623 
624   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
625   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
626                                  TemplateArgumentLoc &ArgLoc);
627 
628   /// Fakes up a TypeSourceInfo for a type.
629   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
630     return SemaRef.Context.getTrivialTypeSourceInfo(T,
631                        getDerived().getBaseLocation());
632   }
633 
634 #define ABSTRACT_TYPELOC(CLASS, PARENT)
635 #define TYPELOC(CLASS, PARENT)                                   \
636   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
637 #include "clang/AST/TypeLocNodes.def"
638 
639   template<typename Fn>
640   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
641                                       FunctionProtoTypeLoc TL,
642                                       CXXRecordDecl *ThisContext,
643                                       Qualifiers ThisTypeQuals,
644                                       Fn TransformExceptionSpec);
645 
646   bool TransformExceptionSpec(SourceLocation Loc,
647                               FunctionProtoType::ExceptionSpecInfo &ESI,
648                               SmallVectorImpl<QualType> &Exceptions,
649                               bool &Changed);
650 
651   StmtResult TransformSEHHandler(Stmt *Handler);
652 
653   QualType
654   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
655                                       TemplateSpecializationTypeLoc TL,
656                                       TemplateName Template);
657 
658   QualType
659   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
660                                       DependentTemplateSpecializationTypeLoc TL,
661                                                TemplateName Template,
662                                                CXXScopeSpec &SS);
663 
664   QualType TransformDependentTemplateSpecializationType(
665       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
666       NestedNameSpecifierLoc QualifierLoc);
667 
668   /// Transforms the parameters of a function type into the
669   /// given vectors.
670   ///
671   /// The result vectors should be kept in sync; null entries in the
672   /// variables vector are acceptable.
673   ///
674   /// Return true on error.
675   bool TransformFunctionTypeParams(
676       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
677       const QualType *ParamTypes,
678       const FunctionProtoType::ExtParameterInfo *ParamInfos,
679       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
680       Sema::ExtParameterInfoBuilder &PInfos);
681 
682   /// Transforms a single function-type parameter.  Return null
683   /// on error.
684   ///
685   /// \param indexAdjustment - A number to add to the parameter's
686   ///   scope index;  can be negative
687   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
688                                           int indexAdjustment,
689                                           Optional<unsigned> NumExpansions,
690                                           bool ExpectParameterPack);
691 
692   /// Transform the body of a lambda-expression.
693   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
694   /// Alternative implementation of TransformLambdaBody that skips transforming
695   /// the body.
696   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
697 
698   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
699 
700   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
701   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
702 
703   TemplateParameterList *TransformTemplateParameterList(
704         TemplateParameterList *TPL) {
705     return TPL;
706   }
707 
708   ExprResult TransformAddressOfOperand(Expr *E);
709 
710   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
711                                                 bool IsAddressOfOperand,
712                                                 TypeSourceInfo **RecoveryTSI);
713 
714   ExprResult TransformParenDependentScopeDeclRefExpr(
715       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
716       TypeSourceInfo **RecoveryTSI);
717 
718   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
719 
720 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
721 // amount of stack usage with clang.
722 #define STMT(Node, Parent)                        \
723   LLVM_ATTRIBUTE_NOINLINE \
724   StmtResult Transform##Node(Node *S);
725 #define VALUESTMT(Node, Parent)                   \
726   LLVM_ATTRIBUTE_NOINLINE \
727   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
728 #define EXPR(Node, Parent)                        \
729   LLVM_ATTRIBUTE_NOINLINE \
730   ExprResult Transform##Node(Node *E);
731 #define ABSTRACT_STMT(Stmt)
732 #include "clang/AST/StmtNodes.inc"
733 
734 #define GEN_CLANG_CLAUSE_CLASS
735 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
736   LLVM_ATTRIBUTE_NOINLINE                                                      \
737   OMPClause *Transform##Class(Class *S);
738 #include "llvm/Frontend/OpenMP/OMP.inc"
739 
740   /// Build a new qualified type given its unqualified type and type location.
741   ///
742   /// By default, this routine adds type qualifiers only to types that can
743   /// have qualifiers, and silently suppresses those qualifiers that are not
744   /// permitted. Subclasses may override this routine to provide different
745   /// behavior.
746   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
747 
748   /// Build a new pointer type given its pointee type.
749   ///
750   /// By default, performs semantic analysis when building the pointer type.
751   /// Subclasses may override this routine to provide different behavior.
752   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
753 
754   /// Build a new block pointer type given its pointee type.
755   ///
756   /// By default, performs semantic analysis when building the block pointer
757   /// type. Subclasses may override this routine to provide different behavior.
758   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
759 
760   /// Build a new reference type given the type it references.
761   ///
762   /// By default, performs semantic analysis when building the
763   /// reference type. Subclasses may override this routine to provide
764   /// different behavior.
765   ///
766   /// \param LValue whether the type was written with an lvalue sigil
767   /// or an rvalue sigil.
768   QualType RebuildReferenceType(QualType ReferentType,
769                                 bool LValue,
770                                 SourceLocation Sigil);
771 
772   /// Build a new member pointer type given the pointee type and the
773   /// class type it refers into.
774   ///
775   /// By default, performs semantic analysis when building the member pointer
776   /// type. Subclasses may override this routine to provide different behavior.
777   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
778                                     SourceLocation Sigil);
779 
780   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
781                                     SourceLocation ProtocolLAngleLoc,
782                                     ArrayRef<ObjCProtocolDecl *> Protocols,
783                                     ArrayRef<SourceLocation> ProtocolLocs,
784                                     SourceLocation ProtocolRAngleLoc);
785 
786   /// Build an Objective-C object type.
787   ///
788   /// By default, performs semantic analysis when building the object type.
789   /// Subclasses may override this routine to provide different behavior.
790   QualType RebuildObjCObjectType(QualType BaseType,
791                                  SourceLocation Loc,
792                                  SourceLocation TypeArgsLAngleLoc,
793                                  ArrayRef<TypeSourceInfo *> TypeArgs,
794                                  SourceLocation TypeArgsRAngleLoc,
795                                  SourceLocation ProtocolLAngleLoc,
796                                  ArrayRef<ObjCProtocolDecl *> Protocols,
797                                  ArrayRef<SourceLocation> ProtocolLocs,
798                                  SourceLocation ProtocolRAngleLoc);
799 
800   /// Build a new Objective-C object pointer type given the pointee type.
801   ///
802   /// By default, directly builds the pointer type, with no additional semantic
803   /// analysis.
804   QualType RebuildObjCObjectPointerType(QualType PointeeType,
805                                         SourceLocation Star);
806 
807   /// Build a new array type given the element type, size
808   /// modifier, size of the array (if known), size expression, and index type
809   /// qualifiers.
810   ///
811   /// By default, performs semantic analysis when building the array type.
812   /// Subclasses may override this routine to provide different behavior.
813   /// Also by default, all of the other Rebuild*Array
814   QualType RebuildArrayType(QualType ElementType,
815                             ArrayType::ArraySizeModifier SizeMod,
816                             const llvm::APInt *Size,
817                             Expr *SizeExpr,
818                             unsigned IndexTypeQuals,
819                             SourceRange BracketsRange);
820 
821   /// Build a new constant array type given the element type, size
822   /// modifier, (known) size of the array, and index type qualifiers.
823   ///
824   /// By default, performs semantic analysis when building the array type.
825   /// Subclasses may override this routine to provide different behavior.
826   QualType RebuildConstantArrayType(QualType ElementType,
827                                     ArrayType::ArraySizeModifier SizeMod,
828                                     const llvm::APInt &Size,
829                                     Expr *SizeExpr,
830                                     unsigned IndexTypeQuals,
831                                     SourceRange BracketsRange);
832 
833   /// Build a new incomplete array type given the element type, size
834   /// modifier, 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 RebuildIncompleteArrayType(QualType ElementType,
839                                       ArrayType::ArraySizeModifier SizeMod,
840                                       unsigned IndexTypeQuals,
841                                       SourceRange BracketsRange);
842 
843   /// Build a new variable-length array type given the element type,
844   /// size modifier, size expression, and index type qualifiers.
845   ///
846   /// By default, performs semantic analysis when building the array type.
847   /// Subclasses may override this routine to provide different behavior.
848   QualType RebuildVariableArrayType(QualType ElementType,
849                                     ArrayType::ArraySizeModifier SizeMod,
850                                     Expr *SizeExpr,
851                                     unsigned IndexTypeQuals,
852                                     SourceRange BracketsRange);
853 
854   /// Build a new dependent-sized array type given the element type,
855   /// size modifier, size expression, and index type qualifiers.
856   ///
857   /// By default, performs semantic analysis when building the array type.
858   /// Subclasses may override this routine to provide different behavior.
859   QualType RebuildDependentSizedArrayType(QualType ElementType,
860                                           ArrayType::ArraySizeModifier SizeMod,
861                                           Expr *SizeExpr,
862                                           unsigned IndexTypeQuals,
863                                           SourceRange BracketsRange);
864 
865   /// Build a new vector type given the element type and
866   /// number of elements.
867   ///
868   /// By default, performs semantic analysis when building the vector type.
869   /// Subclasses may override this routine to provide different behavior.
870   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
871                              VectorType::VectorKind VecKind);
872 
873   /// Build a new potentially dependently-sized extended vector type
874   /// given the element type and number of elements.
875   ///
876   /// By default, performs semantic analysis when building the vector type.
877   /// Subclasses may override this routine to provide different behavior.
878   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
879                                            SourceLocation AttributeLoc,
880                                            VectorType::VectorKind);
881 
882   /// Build a new extended vector type given the element type and
883   /// number of elements.
884   ///
885   /// By default, performs semantic analysis when building the vector type.
886   /// Subclasses may override this routine to provide different behavior.
887   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
888                                 SourceLocation AttributeLoc);
889 
890   /// Build a new potentially dependently-sized extended vector type
891   /// given the element type and number of elements.
892   ///
893   /// By default, performs semantic analysis when building the vector type.
894   /// Subclasses may override this routine to provide different behavior.
895   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
896                                               Expr *SizeExpr,
897                                               SourceLocation AttributeLoc);
898 
899   /// Build a new matrix type given the element type and dimensions.
900   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
901                                      unsigned NumColumns);
902 
903   /// Build a new matrix type given the type and dependently-defined
904   /// dimensions.
905   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
906                                            Expr *ColumnExpr,
907                                            SourceLocation AttributeLoc);
908 
909   /// Build a new DependentAddressSpaceType or return the pointee
910   /// type variable with the correct address space (retrieved from
911   /// AddrSpaceExpr) applied to it. The former will be returned in cases
912   /// where the address space remains dependent.
913   ///
914   /// By default, performs semantic analysis when building the type with address
915   /// space applied. Subclasses may override this routine to provide different
916   /// behavior.
917   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
918                                             Expr *AddrSpaceExpr,
919                                             SourceLocation AttributeLoc);
920 
921   /// Build a new function type.
922   ///
923   /// By default, performs semantic analysis when building the function type.
924   /// Subclasses may override this routine to provide different behavior.
925   QualType RebuildFunctionProtoType(QualType T,
926                                     MutableArrayRef<QualType> ParamTypes,
927                                     const FunctionProtoType::ExtProtoInfo &EPI);
928 
929   /// Build a new unprototyped function type.
930   QualType RebuildFunctionNoProtoType(QualType ResultType);
931 
932   /// Rebuild an unresolved typename type, given the decl that
933   /// the UnresolvedUsingTypenameDecl was transformed to.
934   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
935 
936   /// Build a new type found via an alias.
937   QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
938     return SemaRef.Context.getUsingType(Found, Underlying);
939   }
940 
941   /// Build a new typedef type.
942   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
943     return SemaRef.Context.getTypeDeclType(Typedef);
944   }
945 
946   /// Build a new MacroDefined type.
947   QualType RebuildMacroQualifiedType(QualType T,
948                                      const IdentifierInfo *MacroII) {
949     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
950   }
951 
952   /// Build a new class/struct/union type.
953   QualType RebuildRecordType(RecordDecl *Record) {
954     return SemaRef.Context.getTypeDeclType(Record);
955   }
956 
957   /// Build a new Enum type.
958   QualType RebuildEnumType(EnumDecl *Enum) {
959     return SemaRef.Context.getTypeDeclType(Enum);
960   }
961 
962   /// Build a new typeof(expr) type.
963   ///
964   /// By default, performs semantic analysis when building the typeof type.
965   /// Subclasses may override this routine to provide different behavior.
966   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
967 
968   /// Build a new typeof(type) type.
969   ///
970   /// By default, builds a new TypeOfType with the given underlying type.
971   QualType RebuildTypeOfType(QualType Underlying);
972 
973   /// Build a new unary transform type.
974   QualType RebuildUnaryTransformType(QualType BaseType,
975                                      UnaryTransformType::UTTKind UKind,
976                                      SourceLocation Loc);
977 
978   /// Build a new C++11 decltype type.
979   ///
980   /// By default, performs semantic analysis when building the decltype type.
981   /// Subclasses may override this routine to provide different behavior.
982   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
983 
984   /// Build a new C++11 auto type.
985   ///
986   /// By default, builds a new AutoType with the given deduced type.
987   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
988                            ConceptDecl *TypeConstraintConcept,
989                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
990     // Note, IsDependent is always false here: we implicitly convert an 'auto'
991     // which has been deduced to a dependent type into an undeduced 'auto', so
992     // that we'll retry deduction after the transformation.
993     return SemaRef.Context.getAutoType(Deduced, Keyword,
994                                        /*IsDependent*/ false, /*IsPack=*/false,
995                                        TypeConstraintConcept,
996                                        TypeConstraintArgs);
997   }
998 
999   /// By default, builds a new DeducedTemplateSpecializationType with the given
1000   /// deduced type.
1001   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1002       QualType Deduced) {
1003     return SemaRef.Context.getDeducedTemplateSpecializationType(
1004         Template, Deduced, /*IsDependent*/ false);
1005   }
1006 
1007   /// Build a new template specialization type.
1008   ///
1009   /// By default, performs semantic analysis when building the template
1010   /// specialization type. Subclasses may override this routine to provide
1011   /// different behavior.
1012   QualType RebuildTemplateSpecializationType(TemplateName Template,
1013                                              SourceLocation TemplateLoc,
1014                                              TemplateArgumentListInfo &Args);
1015 
1016   /// Build a new parenthesized type.
1017   ///
1018   /// By default, builds a new ParenType type from the inner type.
1019   /// Subclasses may override this routine to provide different behavior.
1020   QualType RebuildParenType(QualType InnerType) {
1021     return SemaRef.BuildParenType(InnerType);
1022   }
1023 
1024   /// Build a new qualified name type.
1025   ///
1026   /// By default, builds a new ElaboratedType type from the keyword,
1027   /// the nested-name-specifier and the named type.
1028   /// Subclasses may override this routine to provide different behavior.
1029   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1030                                  ElaboratedTypeKeyword Keyword,
1031                                  NestedNameSpecifierLoc QualifierLoc,
1032                                  QualType Named) {
1033     return SemaRef.Context.getElaboratedType(Keyword,
1034                                          QualifierLoc.getNestedNameSpecifier(),
1035                                              Named);
1036   }
1037 
1038   /// Build a new typename type that refers to a template-id.
1039   ///
1040   /// By default, builds a new DependentNameType type from the
1041   /// nested-name-specifier and the given type. Subclasses may override
1042   /// this routine to provide different behavior.
1043   QualType RebuildDependentTemplateSpecializationType(
1044                                           ElaboratedTypeKeyword Keyword,
1045                                           NestedNameSpecifierLoc QualifierLoc,
1046                                           SourceLocation TemplateKWLoc,
1047                                           const IdentifierInfo *Name,
1048                                           SourceLocation NameLoc,
1049                                           TemplateArgumentListInfo &Args,
1050                                           bool AllowInjectedClassName) {
1051     // Rebuild the template name.
1052     // TODO: avoid TemplateName abstraction
1053     CXXScopeSpec SS;
1054     SS.Adopt(QualifierLoc);
1055     TemplateName InstName = getDerived().RebuildTemplateName(
1056         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1057         AllowInjectedClassName);
1058 
1059     if (InstName.isNull())
1060       return QualType();
1061 
1062     // If it's still dependent, make a dependent specialization.
1063     if (InstName.getAsDependentTemplateName())
1064       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1065                                           QualifierLoc.getNestedNameSpecifier(),
1066                                                                     Name,
1067                                                                     Args);
1068 
1069     // Otherwise, make an elaborated type wrapping a non-dependent
1070     // specialization.
1071     QualType T =
1072     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1073     if (T.isNull()) return QualType();
1074 
1075     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1076       return T;
1077 
1078     return SemaRef.Context.getElaboratedType(Keyword,
1079                                        QualifierLoc.getNestedNameSpecifier(),
1080                                              T);
1081   }
1082 
1083   /// Build a new typename type that refers to an identifier.
1084   ///
1085   /// By default, performs semantic analysis when building the typename type
1086   /// (or elaborated type). Subclasses may override this routine to provide
1087   /// different behavior.
1088   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1089                                     SourceLocation KeywordLoc,
1090                                     NestedNameSpecifierLoc QualifierLoc,
1091                                     const IdentifierInfo *Id,
1092                                     SourceLocation IdLoc,
1093                                     bool DeducedTSTContext) {
1094     CXXScopeSpec SS;
1095     SS.Adopt(QualifierLoc);
1096 
1097     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1098       // If the name is still dependent, just build a new dependent name type.
1099       if (!SemaRef.computeDeclContext(SS))
1100         return SemaRef.Context.getDependentNameType(Keyword,
1101                                           QualifierLoc.getNestedNameSpecifier(),
1102                                                     Id);
1103     }
1104 
1105     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1106       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1107                                        *Id, IdLoc, DeducedTSTContext);
1108     }
1109 
1110     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1111 
1112     // We had a dependent elaborated-type-specifier that has been transformed
1113     // into a non-dependent elaborated-type-specifier. Find the tag we're
1114     // referring to.
1115     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1116     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1117     if (!DC)
1118       return QualType();
1119 
1120     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1121       return QualType();
1122 
1123     TagDecl *Tag = nullptr;
1124     SemaRef.LookupQualifiedName(Result, DC);
1125     switch (Result.getResultKind()) {
1126       case LookupResult::NotFound:
1127       case LookupResult::NotFoundInCurrentInstantiation:
1128         break;
1129 
1130       case LookupResult::Found:
1131         Tag = Result.getAsSingle<TagDecl>();
1132         break;
1133 
1134       case LookupResult::FoundOverloaded:
1135       case LookupResult::FoundUnresolvedValue:
1136         llvm_unreachable("Tag lookup cannot find non-tags");
1137 
1138       case LookupResult::Ambiguous:
1139         // Let the LookupResult structure handle ambiguities.
1140         return QualType();
1141     }
1142 
1143     if (!Tag) {
1144       // Check where the name exists but isn't a tag type and use that to emit
1145       // better diagnostics.
1146       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1147       SemaRef.LookupQualifiedName(Result, DC);
1148       switch (Result.getResultKind()) {
1149         case LookupResult::Found:
1150         case LookupResult::FoundOverloaded:
1151         case LookupResult::FoundUnresolvedValue: {
1152           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1153           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1154           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1155                                                                << NTK << Kind;
1156           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1157           break;
1158         }
1159         default:
1160           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1161               << Kind << Id << DC << QualifierLoc.getSourceRange();
1162           break;
1163       }
1164       return QualType();
1165     }
1166 
1167     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1168                                               IdLoc, Id)) {
1169       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1170       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1171       return QualType();
1172     }
1173 
1174     // Build the elaborated-type-specifier type.
1175     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1176     return SemaRef.Context.getElaboratedType(Keyword,
1177                                          QualifierLoc.getNestedNameSpecifier(),
1178                                              T);
1179   }
1180 
1181   /// Build a new pack expansion type.
1182   ///
1183   /// By default, builds a new PackExpansionType type from the given pattern.
1184   /// Subclasses may override this routine to provide different behavior.
1185   QualType RebuildPackExpansionType(QualType Pattern,
1186                                     SourceRange PatternRange,
1187                                     SourceLocation EllipsisLoc,
1188                                     Optional<unsigned> NumExpansions) {
1189     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1190                                         NumExpansions);
1191   }
1192 
1193   /// Build a new atomic type given its value type.
1194   ///
1195   /// By default, performs semantic analysis when building the atomic type.
1196   /// Subclasses may override this routine to provide different behavior.
1197   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1198 
1199   /// Build a new pipe type given its value type.
1200   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1201                            bool isReadPipe);
1202 
1203   /// Build a bit-precise int given its value type.
1204   QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1205                              SourceLocation Loc);
1206 
1207   /// Build a dependent bit-precise int given its value type.
1208   QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1209                                       SourceLocation Loc);
1210 
1211   /// Build a new template name given a nested name specifier, a flag
1212   /// indicating whether the "template" keyword was provided, and the template
1213   /// that the template name refers to.
1214   ///
1215   /// By default, builds the new template name directly. Subclasses may override
1216   /// this routine to provide different behavior.
1217   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1218                                    bool TemplateKW,
1219                                    TemplateDecl *Template);
1220 
1221   /// Build a new template name given a nested name specifier and the
1222   /// name that is referred to as a template.
1223   ///
1224   /// By default, performs semantic analysis to determine whether the name can
1225   /// be resolved to a specific template, then builds the appropriate kind of
1226   /// template name. Subclasses may override this routine to provide different
1227   /// behavior.
1228   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1229                                    SourceLocation TemplateKWLoc,
1230                                    const IdentifierInfo &Name,
1231                                    SourceLocation NameLoc, QualType ObjectType,
1232                                    NamedDecl *FirstQualifierInScope,
1233                                    bool AllowInjectedClassName);
1234 
1235   /// Build a new template name given a nested name specifier and the
1236   /// overloaded operator name that is referred to as a template.
1237   ///
1238   /// By default, performs semantic analysis to determine whether the name can
1239   /// be resolved to a specific template, then builds the appropriate kind of
1240   /// template name. Subclasses may override this routine to provide different
1241   /// behavior.
1242   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1243                                    SourceLocation TemplateKWLoc,
1244                                    OverloadedOperatorKind Operator,
1245                                    SourceLocation NameLoc, QualType ObjectType,
1246                                    bool AllowInjectedClassName);
1247 
1248   /// Build a new template name given a template template parameter pack
1249   /// and the
1250   ///
1251   /// By default, performs semantic analysis to determine whether the name can
1252   /// be resolved to a specific template, then builds the appropriate kind of
1253   /// template name. Subclasses may override this routine to provide different
1254   /// behavior.
1255   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1256                                    const TemplateArgument &ArgPack) {
1257     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1258   }
1259 
1260   /// Build a new compound statement.
1261   ///
1262   /// By default, performs semantic analysis to build the new statement.
1263   /// Subclasses may override this routine to provide different behavior.
1264   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1265                                        MultiStmtArg Statements,
1266                                        SourceLocation RBraceLoc,
1267                                        bool IsStmtExpr) {
1268     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1269                                        IsStmtExpr);
1270   }
1271 
1272   /// Build a new case 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 RebuildCaseStmt(SourceLocation CaseLoc,
1277                                    Expr *LHS,
1278                                    SourceLocation EllipsisLoc,
1279                                    Expr *RHS,
1280                                    SourceLocation ColonLoc) {
1281     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1282                                    ColonLoc);
1283   }
1284 
1285   /// Attach the body to a new case statement.
1286   ///
1287   /// By default, performs semantic analysis to build the new statement.
1288   /// Subclasses may override this routine to provide different behavior.
1289   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1290     getSema().ActOnCaseStmtBody(S, Body);
1291     return S;
1292   }
1293 
1294   /// Build a new default statement.
1295   ///
1296   /// By default, performs semantic analysis to build the new statement.
1297   /// Subclasses may override this routine to provide different behavior.
1298   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1299                                       SourceLocation ColonLoc,
1300                                       Stmt *SubStmt) {
1301     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1302                                       /*CurScope=*/nullptr);
1303   }
1304 
1305   /// Build a new label statement.
1306   ///
1307   /// By default, performs semantic analysis to build the new statement.
1308   /// Subclasses may override this routine to provide different behavior.
1309   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1310                               SourceLocation ColonLoc, Stmt *SubStmt) {
1311     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1312   }
1313 
1314   /// Build a new attributed statement.
1315   ///
1316   /// By default, performs semantic analysis to build the new statement.
1317   /// Subclasses may override this routine to provide different behavior.
1318   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1319                                    ArrayRef<const Attr *> Attrs,
1320                                    Stmt *SubStmt) {
1321     return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1322   }
1323 
1324   /// Build a new "if" statement.
1325   ///
1326   /// By default, performs semantic analysis to build the new statement.
1327   /// Subclasses may override this routine to provide different behavior.
1328   StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1329                            SourceLocation LParenLoc, Sema::ConditionResult Cond,
1330                            SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1331                            SourceLocation ElseLoc, Stmt *Else) {
1332     return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1333                                  Then, ElseLoc, Else);
1334   }
1335 
1336   /// Start building a new switch statement.
1337   ///
1338   /// By default, performs semantic analysis to build the new statement.
1339   /// Subclasses may override this routine to provide different behavior.
1340   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1341                                     SourceLocation LParenLoc, Stmt *Init,
1342                                     Sema::ConditionResult Cond,
1343                                     SourceLocation RParenLoc) {
1344     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1345                                             RParenLoc);
1346   }
1347 
1348   /// Attach the body to the switch statement.
1349   ///
1350   /// By default, performs semantic analysis to build the new statement.
1351   /// Subclasses may override this routine to provide different behavior.
1352   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1353                                    Stmt *Switch, Stmt *Body) {
1354     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1355   }
1356 
1357   /// Build a new while statement.
1358   ///
1359   /// By default, performs semantic analysis to build the new statement.
1360   /// Subclasses may override this routine to provide different behavior.
1361   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1362                               Sema::ConditionResult Cond,
1363                               SourceLocation RParenLoc, Stmt *Body) {
1364     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1365   }
1366 
1367   /// Build a new do-while statement.
1368   ///
1369   /// By default, performs semantic analysis to build the new statement.
1370   /// Subclasses may override this routine to provide different behavior.
1371   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1372                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1373                            Expr *Cond, SourceLocation RParenLoc) {
1374     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1375                                  Cond, RParenLoc);
1376   }
1377 
1378   /// Build a new for statement.
1379   ///
1380   /// By default, performs semantic analysis to build the new statement.
1381   /// Subclasses may override this routine to provide different behavior.
1382   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1383                             Stmt *Init, Sema::ConditionResult Cond,
1384                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1385                             Stmt *Body) {
1386     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1387                                   Inc, RParenLoc, Body);
1388   }
1389 
1390   /// Build a new goto statement.
1391   ///
1392   /// By default, performs semantic analysis to build the new statement.
1393   /// Subclasses may override this routine to provide different behavior.
1394   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1395                              LabelDecl *Label) {
1396     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1397   }
1398 
1399   /// Build a new indirect goto statement.
1400   ///
1401   /// By default, performs semantic analysis to build the new statement.
1402   /// Subclasses may override this routine to provide different behavior.
1403   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1404                                      SourceLocation StarLoc,
1405                                      Expr *Target) {
1406     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1407   }
1408 
1409   /// Build a new return statement.
1410   ///
1411   /// By default, performs semantic analysis to build the new statement.
1412   /// Subclasses may override this routine to provide different behavior.
1413   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1414     return getSema().BuildReturnStmt(ReturnLoc, Result);
1415   }
1416 
1417   /// Build a new declaration statement.
1418   ///
1419   /// By default, performs semantic analysis to build the new statement.
1420   /// Subclasses may override this routine to provide different behavior.
1421   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1422                              SourceLocation StartLoc, SourceLocation EndLoc) {
1423     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1424     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1425   }
1426 
1427   /// Build a new inline asm statement.
1428   ///
1429   /// By default, performs semantic analysis to build the new statement.
1430   /// Subclasses may override this routine to provide different behavior.
1431   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1432                                bool IsVolatile, unsigned NumOutputs,
1433                                unsigned NumInputs, IdentifierInfo **Names,
1434                                MultiExprArg Constraints, MultiExprArg Exprs,
1435                                Expr *AsmString, MultiExprArg Clobbers,
1436                                unsigned NumLabels,
1437                                SourceLocation RParenLoc) {
1438     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1439                                      NumInputs, Names, Constraints, Exprs,
1440                                      AsmString, Clobbers, NumLabels, RParenLoc);
1441   }
1442 
1443   /// Build a new MS style inline asm statement.
1444   ///
1445   /// By default, performs semantic analysis to build the new statement.
1446   /// Subclasses may override this routine to provide different behavior.
1447   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1448                               ArrayRef<Token> AsmToks,
1449                               StringRef AsmString,
1450                               unsigned NumOutputs, unsigned NumInputs,
1451                               ArrayRef<StringRef> Constraints,
1452                               ArrayRef<StringRef> Clobbers,
1453                               ArrayRef<Expr*> Exprs,
1454                               SourceLocation EndLoc) {
1455     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1456                                     NumOutputs, NumInputs,
1457                                     Constraints, Clobbers, Exprs, EndLoc);
1458   }
1459 
1460   /// Build a new co_return statement.
1461   ///
1462   /// By default, performs semantic analysis to build the new statement.
1463   /// Subclasses may override this routine to provide different behavior.
1464   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1465                                  bool IsImplicit) {
1466     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1467   }
1468 
1469   /// Build a new co_await expression.
1470   ///
1471   /// By default, performs semantic analysis to build the new expression.
1472   /// Subclasses may override this routine to provide different behavior.
1473   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1474                                 bool IsImplicit) {
1475     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1476   }
1477 
1478   /// Build a new co_await expression.
1479   ///
1480   /// By default, performs semantic analysis to build the new expression.
1481   /// Subclasses may override this routine to provide different behavior.
1482   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1483                                          Expr *Result,
1484                                          UnresolvedLookupExpr *Lookup) {
1485     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1486   }
1487 
1488   /// Build a new co_yield expression.
1489   ///
1490   /// By default, performs semantic analysis to build the new expression.
1491   /// Subclasses may override this routine to provide different behavior.
1492   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1493     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1494   }
1495 
1496   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1497     return getSema().BuildCoroutineBodyStmt(Args);
1498   }
1499 
1500   /// Build a new Objective-C \@try statement.
1501   ///
1502   /// By default, performs semantic analysis to build the new statement.
1503   /// Subclasses may override this routine to provide different behavior.
1504   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1505                                         Stmt *TryBody,
1506                                         MultiStmtArg CatchStmts,
1507                                         Stmt *Finally) {
1508     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1509                                         Finally);
1510   }
1511 
1512   /// Rebuild an Objective-C exception declaration.
1513   ///
1514   /// By default, performs semantic analysis to build the new declaration.
1515   /// Subclasses may override this routine to provide different behavior.
1516   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1517                                     TypeSourceInfo *TInfo, QualType T) {
1518     return getSema().BuildObjCExceptionDecl(TInfo, T,
1519                                             ExceptionDecl->getInnerLocStart(),
1520                                             ExceptionDecl->getLocation(),
1521                                             ExceptionDecl->getIdentifier());
1522   }
1523 
1524   /// Build a new Objective-C \@catch statement.
1525   ///
1526   /// By default, performs semantic analysis to build the new statement.
1527   /// Subclasses may override this routine to provide different behavior.
1528   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1529                                           SourceLocation RParenLoc,
1530                                           VarDecl *Var,
1531                                           Stmt *Body) {
1532     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1533                                           Var, Body);
1534   }
1535 
1536   /// Build a new Objective-C \@finally statement.
1537   ///
1538   /// By default, performs semantic analysis to build the new statement.
1539   /// Subclasses may override this routine to provide different behavior.
1540   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1541                                             Stmt *Body) {
1542     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1543   }
1544 
1545   /// Build a new Objective-C \@throw statement.
1546   ///
1547   /// By default, performs semantic analysis to build the new statement.
1548   /// Subclasses may override this routine to provide different behavior.
1549   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1550                                           Expr *Operand) {
1551     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1552   }
1553 
1554   /// Build a new OpenMP Canonical loop.
1555   ///
1556   /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1557   /// OMPCanonicalLoop.
1558   StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1559     return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1560   }
1561 
1562   /// Build a new OpenMP executable directive.
1563   ///
1564   /// By default, performs semantic analysis to build the new statement.
1565   /// Subclasses may override this routine to provide different behavior.
1566   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1567                                            DeclarationNameInfo DirName,
1568                                            OpenMPDirectiveKind CancelRegion,
1569                                            ArrayRef<OMPClause *> Clauses,
1570                                            Stmt *AStmt, SourceLocation StartLoc,
1571                                            SourceLocation EndLoc) {
1572     return getSema().ActOnOpenMPExecutableDirective(
1573         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1574   }
1575 
1576   /// Build a new OpenMP 'if' clause.
1577   ///
1578   /// By default, performs semantic analysis to build the new OpenMP clause.
1579   /// Subclasses may override this routine to provide different behavior.
1580   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1581                                 Expr *Condition, SourceLocation StartLoc,
1582                                 SourceLocation LParenLoc,
1583                                 SourceLocation NameModifierLoc,
1584                                 SourceLocation ColonLoc,
1585                                 SourceLocation EndLoc) {
1586     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1587                                          LParenLoc, NameModifierLoc, ColonLoc,
1588                                          EndLoc);
1589   }
1590 
1591   /// Build a new OpenMP 'final' clause.
1592   ///
1593   /// By default, performs semantic analysis to build the new OpenMP clause.
1594   /// Subclasses may override this routine to provide different behavior.
1595   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1596                                    SourceLocation LParenLoc,
1597                                    SourceLocation EndLoc) {
1598     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1599                                             EndLoc);
1600   }
1601 
1602   /// Build a new OpenMP 'num_threads' clause.
1603   ///
1604   /// By default, performs semantic analysis to build the new OpenMP clause.
1605   /// Subclasses may override this routine to provide different behavior.
1606   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1607                                         SourceLocation StartLoc,
1608                                         SourceLocation LParenLoc,
1609                                         SourceLocation EndLoc) {
1610     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1611                                                  LParenLoc, EndLoc);
1612   }
1613 
1614   /// Build a new OpenMP 'safelen' clause.
1615   ///
1616   /// By default, performs semantic analysis to build the new OpenMP clause.
1617   /// Subclasses may override this routine to provide different behavior.
1618   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1619                                      SourceLocation LParenLoc,
1620                                      SourceLocation EndLoc) {
1621     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1622   }
1623 
1624   /// Build a new OpenMP 'simdlen' clause.
1625   ///
1626   /// By default, performs semantic analysis to build the new OpenMP clause.
1627   /// Subclasses may override this routine to provide different behavior.
1628   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1629                                      SourceLocation LParenLoc,
1630                                      SourceLocation EndLoc) {
1631     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1632   }
1633 
1634   OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1635                                    SourceLocation StartLoc,
1636                                    SourceLocation LParenLoc,
1637                                    SourceLocation EndLoc) {
1638     return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1639   }
1640 
1641   /// Build a new OpenMP 'full' clause.
1642   OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1643                                   SourceLocation EndLoc) {
1644     return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1645   }
1646 
1647   /// Build a new OpenMP 'partial' clause.
1648   OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1649                                      SourceLocation LParenLoc,
1650                                      SourceLocation EndLoc) {
1651     return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1652                                               EndLoc);
1653   }
1654 
1655   /// Build a new OpenMP 'allocator' clause.
1656   ///
1657   /// By default, performs semantic analysis to build the new OpenMP clause.
1658   /// Subclasses may override this routine to provide different behavior.
1659   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1660                                        SourceLocation LParenLoc,
1661                                        SourceLocation EndLoc) {
1662     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1663   }
1664 
1665   /// Build a new OpenMP 'collapse' clause.
1666   ///
1667   /// By default, performs semantic analysis to build the new OpenMP clause.
1668   /// Subclasses may override this routine to provide different behavior.
1669   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1670                                       SourceLocation LParenLoc,
1671                                       SourceLocation EndLoc) {
1672     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1673                                                EndLoc);
1674   }
1675 
1676   /// Build a new OpenMP 'default' clause.
1677   ///
1678   /// By default, performs semantic analysis to build the new OpenMP clause.
1679   /// Subclasses may override this routine to provide different behavior.
1680   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1681                                      SourceLocation StartLoc,
1682                                      SourceLocation LParenLoc,
1683                                      SourceLocation EndLoc) {
1684     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1685                                               StartLoc, LParenLoc, EndLoc);
1686   }
1687 
1688   /// Build a new OpenMP 'proc_bind' clause.
1689   ///
1690   /// By default, performs semantic analysis to build the new OpenMP clause.
1691   /// Subclasses may override this routine to provide different behavior.
1692   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1693                                       SourceLocation KindKwLoc,
1694                                       SourceLocation StartLoc,
1695                                       SourceLocation LParenLoc,
1696                                       SourceLocation EndLoc) {
1697     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1698                                                StartLoc, LParenLoc, EndLoc);
1699   }
1700 
1701   /// Build a new OpenMP 'schedule' clause.
1702   ///
1703   /// By default, performs semantic analysis to build the new OpenMP clause.
1704   /// Subclasses may override this routine to provide different behavior.
1705   OMPClause *RebuildOMPScheduleClause(
1706       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1707       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1708       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1709       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1710     return getSema().ActOnOpenMPScheduleClause(
1711         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1712         CommaLoc, EndLoc);
1713   }
1714 
1715   /// Build a new OpenMP 'ordered' clause.
1716   ///
1717   /// By default, performs semantic analysis to build the new OpenMP clause.
1718   /// Subclasses may override this routine to provide different behavior.
1719   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1720                                      SourceLocation EndLoc,
1721                                      SourceLocation LParenLoc, Expr *Num) {
1722     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1723   }
1724 
1725   /// Build a new OpenMP 'private' clause.
1726   ///
1727   /// By default, performs semantic analysis to build the new OpenMP clause.
1728   /// Subclasses may override this routine to provide different behavior.
1729   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1730                                      SourceLocation StartLoc,
1731                                      SourceLocation LParenLoc,
1732                                      SourceLocation EndLoc) {
1733     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1734                                               EndLoc);
1735   }
1736 
1737   /// Build a new OpenMP 'firstprivate' clause.
1738   ///
1739   /// By default, performs semantic analysis to build the new OpenMP clause.
1740   /// Subclasses may override this routine to provide different behavior.
1741   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1742                                           SourceLocation StartLoc,
1743                                           SourceLocation LParenLoc,
1744                                           SourceLocation EndLoc) {
1745     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1746                                                    EndLoc);
1747   }
1748 
1749   /// Build a new OpenMP 'lastprivate' clause.
1750   ///
1751   /// By default, performs semantic analysis to build the new OpenMP clause.
1752   /// Subclasses may override this routine to provide different behavior.
1753   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1754                                          OpenMPLastprivateModifier LPKind,
1755                                          SourceLocation LPKindLoc,
1756                                          SourceLocation ColonLoc,
1757                                          SourceLocation StartLoc,
1758                                          SourceLocation LParenLoc,
1759                                          SourceLocation EndLoc) {
1760     return getSema().ActOnOpenMPLastprivateClause(
1761         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1762   }
1763 
1764   /// Build a new OpenMP 'shared' clause.
1765   ///
1766   /// By default, performs semantic analysis to build the new OpenMP clause.
1767   /// Subclasses may override this routine to provide different behavior.
1768   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1769                                     SourceLocation StartLoc,
1770                                     SourceLocation LParenLoc,
1771                                     SourceLocation EndLoc) {
1772     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1773                                              EndLoc);
1774   }
1775 
1776   /// Build a new OpenMP 'reduction' clause.
1777   ///
1778   /// By default, performs semantic analysis to build the new statement.
1779   /// Subclasses may override this routine to provide different behavior.
1780   OMPClause *RebuildOMPReductionClause(
1781       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1782       SourceLocation StartLoc, SourceLocation LParenLoc,
1783       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1784       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1785       const DeclarationNameInfo &ReductionId,
1786       ArrayRef<Expr *> UnresolvedReductions) {
1787     return getSema().ActOnOpenMPReductionClause(
1788         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1789         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1790   }
1791 
1792   /// Build a new OpenMP 'task_reduction' clause.
1793   ///
1794   /// By default, performs semantic analysis to build the new statement.
1795   /// Subclasses may override this routine to provide different behavior.
1796   OMPClause *RebuildOMPTaskReductionClause(
1797       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1798       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1799       CXXScopeSpec &ReductionIdScopeSpec,
1800       const DeclarationNameInfo &ReductionId,
1801       ArrayRef<Expr *> UnresolvedReductions) {
1802     return getSema().ActOnOpenMPTaskReductionClause(
1803         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1804         ReductionId, UnresolvedReductions);
1805   }
1806 
1807   /// Build a new OpenMP 'in_reduction' clause.
1808   ///
1809   /// By default, performs semantic analysis to build the new statement.
1810   /// Subclasses may override this routine to provide different behavior.
1811   OMPClause *
1812   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1813                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1814                               SourceLocation EndLoc,
1815                               CXXScopeSpec &ReductionIdScopeSpec,
1816                               const DeclarationNameInfo &ReductionId,
1817                               ArrayRef<Expr *> UnresolvedReductions) {
1818     return getSema().ActOnOpenMPInReductionClause(
1819         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1820         ReductionId, UnresolvedReductions);
1821   }
1822 
1823   /// Build a new OpenMP 'linear' 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 *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1828                                     SourceLocation StartLoc,
1829                                     SourceLocation LParenLoc,
1830                                     OpenMPLinearClauseKind Modifier,
1831                                     SourceLocation ModifierLoc,
1832                                     SourceLocation ColonLoc,
1833                                     SourceLocation EndLoc) {
1834     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1835                                              Modifier, ModifierLoc, ColonLoc,
1836                                              EndLoc);
1837   }
1838 
1839   /// Build a new OpenMP 'aligned' clause.
1840   ///
1841   /// By default, performs semantic analysis to build the new OpenMP clause.
1842   /// Subclasses may override this routine to provide different behavior.
1843   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1844                                      SourceLocation StartLoc,
1845                                      SourceLocation LParenLoc,
1846                                      SourceLocation ColonLoc,
1847                                      SourceLocation EndLoc) {
1848     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1849                                               LParenLoc, ColonLoc, EndLoc);
1850   }
1851 
1852   /// Build a new OpenMP 'copyin' clause.
1853   ///
1854   /// By default, performs semantic analysis to build the new OpenMP clause.
1855   /// Subclasses may override this routine to provide different behavior.
1856   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1857                                     SourceLocation StartLoc,
1858                                     SourceLocation LParenLoc,
1859                                     SourceLocation EndLoc) {
1860     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1861                                              EndLoc);
1862   }
1863 
1864   /// Build a new OpenMP 'copyprivate' 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 *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1869                                          SourceLocation StartLoc,
1870                                          SourceLocation LParenLoc,
1871                                          SourceLocation EndLoc) {
1872     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1873                                                   EndLoc);
1874   }
1875 
1876   /// Build a new OpenMP 'flush' pseudo clause.
1877   ///
1878   /// By default, performs semantic analysis to build the new OpenMP clause.
1879   /// Subclasses may override this routine to provide different behavior.
1880   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1881                                    SourceLocation StartLoc,
1882                                    SourceLocation LParenLoc,
1883                                    SourceLocation EndLoc) {
1884     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1885                                             EndLoc);
1886   }
1887 
1888   /// Build a new OpenMP 'depobj' pseudo clause.
1889   ///
1890   /// By default, performs semantic analysis to build the new OpenMP clause.
1891   /// Subclasses may override this routine to provide different behavior.
1892   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1893                                     SourceLocation LParenLoc,
1894                                     SourceLocation EndLoc) {
1895     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1896                                              EndLoc);
1897   }
1898 
1899   /// Build a new OpenMP 'depend' pseudo clause.
1900   ///
1901   /// By default, performs semantic analysis to build the new OpenMP clause.
1902   /// Subclasses may override this routine to provide different behavior.
1903   OMPClause *
1904   RebuildOMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
1905                          SourceLocation DepLoc, SourceLocation ColonLoc,
1906                          ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1907                          SourceLocation LParenLoc, SourceLocation EndLoc) {
1908     return getSema().ActOnOpenMPDependClause(DepModifier, DepKind, DepLoc,
1909                                              ColonLoc, VarList, StartLoc,
1910                                              LParenLoc, EndLoc);
1911   }
1912 
1913   /// Build a new OpenMP 'device' clause.
1914   ///
1915   /// By default, performs semantic analysis to build the new statement.
1916   /// Subclasses may override this routine to provide different behavior.
1917   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1918                                     Expr *Device, SourceLocation StartLoc,
1919                                     SourceLocation LParenLoc,
1920                                     SourceLocation ModifierLoc,
1921                                     SourceLocation EndLoc) {
1922     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1923                                              LParenLoc, ModifierLoc, EndLoc);
1924   }
1925 
1926   /// Build a new OpenMP 'map' clause.
1927   ///
1928   /// By default, performs semantic analysis to build the new OpenMP clause.
1929   /// Subclasses may override this routine to provide different behavior.
1930   OMPClause *RebuildOMPMapClause(
1931       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1932       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1933       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1934       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1935       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1936       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1937     return getSema().ActOnOpenMPMapClause(
1938         MapTypeModifiers, MapTypeModifiersLoc, MapperIdScopeSpec, MapperId,
1939         MapType, IsMapTypeImplicit, MapLoc, ColonLoc, VarList, Locs,
1940         /*NoDiagnose=*/false, UnresolvedMappers);
1941   }
1942 
1943   /// Build a new OpenMP 'allocate' 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 *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1948                                       SourceLocation StartLoc,
1949                                       SourceLocation LParenLoc,
1950                                       SourceLocation ColonLoc,
1951                                       SourceLocation EndLoc) {
1952     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1953                                                LParenLoc, ColonLoc, EndLoc);
1954   }
1955 
1956   /// Build a new OpenMP 'num_teams' 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 *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1961                                       SourceLocation LParenLoc,
1962                                       SourceLocation EndLoc) {
1963     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1964                                                EndLoc);
1965   }
1966 
1967   /// Build a new OpenMP 'thread_limit' clause.
1968   ///
1969   /// By default, performs semantic analysis to build the new statement.
1970   /// Subclasses may override this routine to provide different behavior.
1971   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1972                                          SourceLocation StartLoc,
1973                                          SourceLocation LParenLoc,
1974                                          SourceLocation EndLoc) {
1975     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1976                                                   LParenLoc, EndLoc);
1977   }
1978 
1979   /// Build a new OpenMP 'priority' clause.
1980   ///
1981   /// By default, performs semantic analysis to build the new statement.
1982   /// Subclasses may override this routine to provide different behavior.
1983   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1984                                       SourceLocation LParenLoc,
1985                                       SourceLocation EndLoc) {
1986     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1987                                                EndLoc);
1988   }
1989 
1990   /// Build a new OpenMP 'grainsize' clause.
1991   ///
1992   /// By default, performs semantic analysis to build the new statement.
1993   /// Subclasses may override this routine to provide different behavior.
1994   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1995                                        SourceLocation LParenLoc,
1996                                        SourceLocation EndLoc) {
1997     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1998                                                 EndLoc);
1999   }
2000 
2001   /// Build a new OpenMP 'num_tasks' clause.
2002   ///
2003   /// By default, performs semantic analysis to build the new statement.
2004   /// Subclasses may override this routine to provide different behavior.
2005   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
2006                                       SourceLocation LParenLoc,
2007                                       SourceLocation EndLoc) {
2008     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
2009                                                EndLoc);
2010   }
2011 
2012   /// Build a new OpenMP 'hint' clause.
2013   ///
2014   /// By default, performs semantic analysis to build the new statement.
2015   /// Subclasses may override this routine to provide different behavior.
2016   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2017                                   SourceLocation LParenLoc,
2018                                   SourceLocation EndLoc) {
2019     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2020   }
2021 
2022   /// Build a new OpenMP 'detach' clause.
2023   ///
2024   /// By default, performs semantic analysis to build the new statement.
2025   /// Subclasses may override this routine to provide different behavior.
2026   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2027                                     SourceLocation LParenLoc,
2028                                     SourceLocation EndLoc) {
2029     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2030   }
2031 
2032   /// Build a new OpenMP 'dist_schedule' clause.
2033   ///
2034   /// By default, performs semantic analysis to build the new OpenMP clause.
2035   /// Subclasses may override this routine to provide different behavior.
2036   OMPClause *
2037   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2038                                Expr *ChunkSize, SourceLocation StartLoc,
2039                                SourceLocation LParenLoc, SourceLocation KindLoc,
2040                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2041     return getSema().ActOnOpenMPDistScheduleClause(
2042         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2043   }
2044 
2045   /// Build a new OpenMP 'to' clause.
2046   ///
2047   /// By default, performs semantic analysis to build the new statement.
2048   /// Subclasses may override this routine to provide different behavior.
2049   OMPClause *
2050   RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2051                      ArrayRef<SourceLocation> MotionModifiersLoc,
2052                      CXXScopeSpec &MapperIdScopeSpec,
2053                      DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2054                      ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2055                      ArrayRef<Expr *> UnresolvedMappers) {
2056     return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2057                                          MapperIdScopeSpec, MapperId, ColonLoc,
2058                                          VarList, Locs, UnresolvedMappers);
2059   }
2060 
2061   /// Build a new OpenMP 'from' clause.
2062   ///
2063   /// By default, performs semantic analysis to build the new statement.
2064   /// Subclasses may override this routine to provide different behavior.
2065   OMPClause *
2066   RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2067                        ArrayRef<SourceLocation> MotionModifiersLoc,
2068                        CXXScopeSpec &MapperIdScopeSpec,
2069                        DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2070                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2071                        ArrayRef<Expr *> UnresolvedMappers) {
2072     return getSema().ActOnOpenMPFromClause(
2073         MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2074         ColonLoc, VarList, Locs, UnresolvedMappers);
2075   }
2076 
2077   /// Build a new OpenMP 'use_device_ptr' clause.
2078   ///
2079   /// By default, performs semantic analysis to build the new OpenMP clause.
2080   /// Subclasses may override this routine to provide different behavior.
2081   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2082                                           const OMPVarListLocTy &Locs) {
2083     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2084   }
2085 
2086   /// Build a new OpenMP 'use_device_addr' clause.
2087   ///
2088   /// By default, performs semantic analysis to build the new OpenMP clause.
2089   /// Subclasses may override this routine to provide different behavior.
2090   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2091                                            const OMPVarListLocTy &Locs) {
2092     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2093   }
2094 
2095   /// Build a new OpenMP 'is_device_ptr' clause.
2096   ///
2097   /// By default, performs semantic analysis to build the new OpenMP clause.
2098   /// Subclasses may override this routine to provide different behavior.
2099   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2100                                          const OMPVarListLocTy &Locs) {
2101     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2102   }
2103 
2104   /// Build a new OpenMP 'defaultmap' clause.
2105   ///
2106   /// By default, performs semantic analysis to build the new OpenMP clause.
2107   /// Subclasses may override this routine to provide different behavior.
2108   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2109                                         OpenMPDefaultmapClauseKind Kind,
2110                                         SourceLocation StartLoc,
2111                                         SourceLocation LParenLoc,
2112                                         SourceLocation MLoc,
2113                                         SourceLocation KindLoc,
2114                                         SourceLocation EndLoc) {
2115     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2116                                                  MLoc, KindLoc, EndLoc);
2117   }
2118 
2119   /// Build a new OpenMP 'nontemporal' clause.
2120   ///
2121   /// By default, performs semantic analysis to build the new OpenMP clause.
2122   /// Subclasses may override this routine to provide different behavior.
2123   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2124                                          SourceLocation StartLoc,
2125                                          SourceLocation LParenLoc,
2126                                          SourceLocation EndLoc) {
2127     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2128                                                   EndLoc);
2129   }
2130 
2131   /// Build a new OpenMP 'inclusive' clause.
2132   ///
2133   /// By default, performs semantic analysis to build the new OpenMP clause.
2134   /// Subclasses may override this routine to provide different behavior.
2135   OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2136                                        SourceLocation StartLoc,
2137                                        SourceLocation LParenLoc,
2138                                        SourceLocation EndLoc) {
2139     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2140                                                 EndLoc);
2141   }
2142 
2143   /// Build a new OpenMP 'exclusive' clause.
2144   ///
2145   /// By default, performs semantic analysis to build the new OpenMP clause.
2146   /// Subclasses may override this routine to provide different behavior.
2147   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2148                                        SourceLocation StartLoc,
2149                                        SourceLocation LParenLoc,
2150                                        SourceLocation EndLoc) {
2151     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2152                                                 EndLoc);
2153   }
2154 
2155   /// Build a new OpenMP 'uses_allocators' clause.
2156   ///
2157   /// By default, performs semantic analysis to build the new OpenMP clause.
2158   /// Subclasses may override this routine to provide different behavior.
2159   OMPClause *RebuildOMPUsesAllocatorsClause(
2160       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2161       SourceLocation LParenLoc, SourceLocation EndLoc) {
2162     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2163                                                     Data);
2164   }
2165 
2166   /// Build a new OpenMP 'affinity' clause.
2167   ///
2168   /// By default, performs semantic analysis to build the new OpenMP clause.
2169   /// Subclasses may override this routine to provide different behavior.
2170   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2171                                       SourceLocation LParenLoc,
2172                                       SourceLocation ColonLoc,
2173                                       SourceLocation EndLoc, Expr *Modifier,
2174                                       ArrayRef<Expr *> Locators) {
2175     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2176                                                EndLoc, Modifier, Locators);
2177   }
2178 
2179   /// Build a new OpenMP 'order' clause.
2180   ///
2181   /// By default, performs semantic analysis to build the new OpenMP clause.
2182   /// Subclasses may override this routine to provide different behavior.
2183   OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2184                                    SourceLocation KindKwLoc,
2185                                    SourceLocation StartLoc,
2186                                    SourceLocation LParenLoc,
2187                                    SourceLocation EndLoc) {
2188     return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2189                                             LParenLoc, EndLoc);
2190   }
2191 
2192   /// Build a new OpenMP 'init' clause.
2193   ///
2194   /// By default, performs semantic analysis to build the new OpenMP clause.
2195   /// Subclasses may override this routine to provide different behavior.
2196   OMPClause *RebuildOMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
2197                                   bool IsTarget, bool IsTargetSync,
2198                                   SourceLocation StartLoc,
2199                                   SourceLocation LParenLoc,
2200                                   SourceLocation VarLoc,
2201                                   SourceLocation EndLoc) {
2202     return getSema().ActOnOpenMPInitClause(InteropVar, PrefExprs, IsTarget,
2203                                            IsTargetSync, StartLoc, LParenLoc,
2204                                            VarLoc, EndLoc);
2205   }
2206 
2207   /// Build a new OpenMP 'use' clause.
2208   ///
2209   /// By default, performs semantic analysis to build the new OpenMP clause.
2210   /// Subclasses may override this routine to provide different behavior.
2211   OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2212                                  SourceLocation LParenLoc,
2213                                  SourceLocation VarLoc, SourceLocation EndLoc) {
2214     return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2215                                           VarLoc, EndLoc);
2216   }
2217 
2218   /// Build a new OpenMP 'destroy' clause.
2219   ///
2220   /// By default, performs semantic analysis to build the new OpenMP clause.
2221   /// Subclasses may override this routine to provide different behavior.
2222   OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2223                                      SourceLocation LParenLoc,
2224                                      SourceLocation VarLoc,
2225                                      SourceLocation EndLoc) {
2226     return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2227                                               VarLoc, EndLoc);
2228   }
2229 
2230   /// Build a new OpenMP 'novariants' clause.
2231   ///
2232   /// By default, performs semantic analysis to build the new OpenMP clause.
2233   /// Subclasses may override this routine to provide different behavior.
2234   OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2235                                         SourceLocation StartLoc,
2236                                         SourceLocation LParenLoc,
2237                                         SourceLocation EndLoc) {
2238     return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2239                                                  EndLoc);
2240   }
2241 
2242   /// Build a new OpenMP 'nocontext' clause.
2243   ///
2244   /// By default, performs semantic analysis to build the new OpenMP clause.
2245   /// Subclasses may override this routine to provide different behavior.
2246   OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2247                                        SourceLocation LParenLoc,
2248                                        SourceLocation EndLoc) {
2249     return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2250                                                 EndLoc);
2251   }
2252 
2253   /// Build a new OpenMP 'filter' clause.
2254   ///
2255   /// By default, performs semantic analysis to build the new OpenMP clause.
2256   /// Subclasses may override this routine to provide different behavior.
2257   OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2258                                     SourceLocation LParenLoc,
2259                                     SourceLocation EndLoc) {
2260     return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2261                                              EndLoc);
2262   }
2263 
2264   /// Build a new OpenMP 'bind' clause.
2265   ///
2266   /// By default, performs semantic analysis to build the new OpenMP clause.
2267   /// Subclasses may override this routine to provide different behavior.
2268   OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2269                                   SourceLocation KindLoc,
2270                                   SourceLocation StartLoc,
2271                                   SourceLocation LParenLoc,
2272                                   SourceLocation EndLoc) {
2273     return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2274                                            EndLoc);
2275   }
2276 
2277   /// Build a new OpenMP 'align' clause.
2278   ///
2279   /// By default, performs semantic analysis to build the new OpenMP clause.
2280   /// Subclasses may override this routine to provide different behavior.
2281   OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2282                                    SourceLocation LParenLoc,
2283                                    SourceLocation EndLoc) {
2284     return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2285   }
2286 
2287   /// Rebuild the operand to an Objective-C \@synchronized statement.
2288   ///
2289   /// By default, performs semantic analysis to build the new statement.
2290   /// Subclasses may override this routine to provide different behavior.
2291   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2292                                               Expr *object) {
2293     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2294   }
2295 
2296   /// Build a new Objective-C \@synchronized statement.
2297   ///
2298   /// By default, performs semantic analysis to build the new statement.
2299   /// Subclasses may override this routine to provide different behavior.
2300   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2301                                            Expr *Object, Stmt *Body) {
2302     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2303   }
2304 
2305   /// Build a new Objective-C \@autoreleasepool statement.
2306   ///
2307   /// By default, performs semantic analysis to build the new statement.
2308   /// Subclasses may override this routine to provide different behavior.
2309   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2310                                             Stmt *Body) {
2311     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2312   }
2313 
2314   /// Build a new Objective-C fast enumeration statement.
2315   ///
2316   /// By default, performs semantic analysis to build the new statement.
2317   /// Subclasses may override this routine to provide different behavior.
2318   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2319                                           Stmt *Element,
2320                                           Expr *Collection,
2321                                           SourceLocation RParenLoc,
2322                                           Stmt *Body) {
2323     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2324                                                 Element,
2325                                                 Collection,
2326                                                 RParenLoc);
2327     if (ForEachStmt.isInvalid())
2328       return StmtError();
2329 
2330     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2331   }
2332 
2333   /// Build a new C++ exception declaration.
2334   ///
2335   /// By default, performs semantic analysis to build the new decaration.
2336   /// Subclasses may override this routine to provide different behavior.
2337   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2338                                 TypeSourceInfo *Declarator,
2339                                 SourceLocation StartLoc,
2340                                 SourceLocation IdLoc,
2341                                 IdentifierInfo *Id) {
2342     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2343                                                        StartLoc, IdLoc, Id);
2344     if (Var)
2345       getSema().CurContext->addDecl(Var);
2346     return Var;
2347   }
2348 
2349   /// Build a new C++ catch statement.
2350   ///
2351   /// By default, performs semantic analysis to build the new statement.
2352   /// Subclasses may override this routine to provide different behavior.
2353   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2354                                  VarDecl *ExceptionDecl,
2355                                  Stmt *Handler) {
2356     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2357                                                       Handler));
2358   }
2359 
2360   /// Build a new C++ try statement.
2361   ///
2362   /// By default, performs semantic analysis to build the new statement.
2363   /// Subclasses may override this routine to provide different behavior.
2364   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2365                                ArrayRef<Stmt *> Handlers) {
2366     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2367   }
2368 
2369   /// Build a new C++0x range-based for statement.
2370   ///
2371   /// By default, performs semantic analysis to build the new statement.
2372   /// Subclasses may override this routine to provide different behavior.
2373   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2374                                     SourceLocation CoawaitLoc, Stmt *Init,
2375                                     SourceLocation ColonLoc, Stmt *Range,
2376                                     Stmt *Begin, Stmt *End, Expr *Cond,
2377                                     Expr *Inc, Stmt *LoopVar,
2378                                     SourceLocation RParenLoc) {
2379     // If we've just learned that the range is actually an Objective-C
2380     // collection, treat this as an Objective-C fast enumeration loop.
2381     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2382       if (RangeStmt->isSingleDecl()) {
2383         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2384           if (RangeVar->isInvalidDecl())
2385             return StmtError();
2386 
2387           Expr *RangeExpr = RangeVar->getInit();
2388           if (!RangeExpr->isTypeDependent() &&
2389               RangeExpr->getType()->isObjCObjectPointerType()) {
2390             // FIXME: Support init-statements in Objective-C++20 ranged for
2391             // statement.
2392             if (Init) {
2393               return SemaRef.Diag(Init->getBeginLoc(),
2394                                   diag::err_objc_for_range_init_stmt)
2395                          << Init->getSourceRange();
2396             }
2397             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2398                                                         RangeExpr, RParenLoc);
2399           }
2400         }
2401       }
2402     }
2403 
2404     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2405                                           Range, Begin, End, Cond, Inc, LoopVar,
2406                                           RParenLoc, Sema::BFRK_Rebuild);
2407   }
2408 
2409   /// Build a new C++0x range-based for statement.
2410   ///
2411   /// By default, performs semantic analysis to build the new statement.
2412   /// Subclasses may override this routine to provide different behavior.
2413   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2414                                           bool IsIfExists,
2415                                           NestedNameSpecifierLoc QualifierLoc,
2416                                           DeclarationNameInfo NameInfo,
2417                                           Stmt *Nested) {
2418     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2419                                                 QualifierLoc, NameInfo, Nested);
2420   }
2421 
2422   /// Attach body to a C++0x range-based for statement.
2423   ///
2424   /// By default, performs semantic analysis to finish the new statement.
2425   /// Subclasses may override this routine to provide different behavior.
2426   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2427     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2428   }
2429 
2430   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2431                                Stmt *TryBlock, Stmt *Handler) {
2432     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2433   }
2434 
2435   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2436                                   Stmt *Block) {
2437     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2438   }
2439 
2440   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2441     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2442   }
2443 
2444   ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2445                                              SourceLocation LParen,
2446                                              SourceLocation RParen,
2447                                              TypeSourceInfo *TSI) {
2448     return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2449   }
2450 
2451   /// Build a new predefined expression.
2452   ///
2453   /// By default, performs semantic analysis to build the new expression.
2454   /// Subclasses may override this routine to provide different behavior.
2455   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2456                                    PredefinedExpr::IdentKind IK) {
2457     return getSema().BuildPredefinedExpr(Loc, IK);
2458   }
2459 
2460   /// Build a new expression that references a declaration.
2461   ///
2462   /// By default, performs semantic analysis to build the new expression.
2463   /// Subclasses may override this routine to provide different behavior.
2464   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2465                                         LookupResult &R,
2466                                         bool RequiresADL) {
2467     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2468   }
2469 
2470 
2471   /// Build a new expression that references a declaration.
2472   ///
2473   /// By default, performs semantic analysis to build the new expression.
2474   /// Subclasses may override this routine to provide different behavior.
2475   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2476                                 ValueDecl *VD,
2477                                 const DeclarationNameInfo &NameInfo,
2478                                 NamedDecl *Found,
2479                                 TemplateArgumentListInfo *TemplateArgs) {
2480     CXXScopeSpec SS;
2481     SS.Adopt(QualifierLoc);
2482     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2483                                               TemplateArgs);
2484   }
2485 
2486   /// Build a new expression in parentheses.
2487   ///
2488   /// By default, performs semantic analysis to build the new expression.
2489   /// Subclasses may override this routine to provide different behavior.
2490   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2491                                     SourceLocation RParen) {
2492     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2493   }
2494 
2495   /// Build a new pseudo-destructor expression.
2496   ///
2497   /// By default, performs semantic analysis to build the new expression.
2498   /// Subclasses may override this routine to provide different behavior.
2499   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2500                                             SourceLocation OperatorLoc,
2501                                             bool isArrow,
2502                                             CXXScopeSpec &SS,
2503                                             TypeSourceInfo *ScopeType,
2504                                             SourceLocation CCLoc,
2505                                             SourceLocation TildeLoc,
2506                                         PseudoDestructorTypeStorage Destroyed);
2507 
2508   /// Build a new unary operator expression.
2509   ///
2510   /// By default, performs semantic analysis to build the new expression.
2511   /// Subclasses may override this routine to provide different behavior.
2512   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2513                                         UnaryOperatorKind Opc,
2514                                         Expr *SubExpr) {
2515     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2516   }
2517 
2518   /// Build a new builtin offsetof expression.
2519   ///
2520   /// By default, performs semantic analysis to build the new expression.
2521   /// Subclasses may override this routine to provide different behavior.
2522   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2523                                  TypeSourceInfo *Type,
2524                                  ArrayRef<Sema::OffsetOfComponent> Components,
2525                                  SourceLocation RParenLoc) {
2526     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2527                                           RParenLoc);
2528   }
2529 
2530   /// Build a new sizeof, alignof or vec_step expression with a
2531   /// type argument.
2532   ///
2533   /// By default, performs semantic analysis to build the new expression.
2534   /// Subclasses may override this routine to provide different behavior.
2535   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2536                                          SourceLocation OpLoc,
2537                                          UnaryExprOrTypeTrait ExprKind,
2538                                          SourceRange R) {
2539     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2540   }
2541 
2542   /// Build a new sizeof, alignof or vec step expression with an
2543   /// expression argument.
2544   ///
2545   /// By default, performs semantic analysis to build the new expression.
2546   /// Subclasses may override this routine to provide different behavior.
2547   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2548                                          UnaryExprOrTypeTrait ExprKind,
2549                                          SourceRange R) {
2550     ExprResult Result
2551       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2552     if (Result.isInvalid())
2553       return ExprError();
2554 
2555     return Result;
2556   }
2557 
2558   /// Build a new array subscript expression.
2559   ///
2560   /// By default, performs semantic analysis to build the new expression.
2561   /// Subclasses may override this routine to provide different behavior.
2562   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2563                                              SourceLocation LBracketLoc,
2564                                              Expr *RHS,
2565                                              SourceLocation RBracketLoc) {
2566     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2567                                              LBracketLoc, RHS,
2568                                              RBracketLoc);
2569   }
2570 
2571   /// Build a new matrix subscript expression.
2572   ///
2573   /// By default, performs semantic analysis to build the new expression.
2574   /// Subclasses may override this routine to provide different behavior.
2575   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2576                                         Expr *ColumnIdx,
2577                                         SourceLocation RBracketLoc) {
2578     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2579                                                       RBracketLoc);
2580   }
2581 
2582   /// Build a new array section expression.
2583   ///
2584   /// By default, performs semantic analysis to build the new expression.
2585   /// Subclasses may override this routine to provide different behavior.
2586   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2587                                         Expr *LowerBound,
2588                                         SourceLocation ColonLocFirst,
2589                                         SourceLocation ColonLocSecond,
2590                                         Expr *Length, Expr *Stride,
2591                                         SourceLocation RBracketLoc) {
2592     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2593                                               ColonLocFirst, ColonLocSecond,
2594                                               Length, Stride, RBracketLoc);
2595   }
2596 
2597   /// Build a new array shaping expression.
2598   ///
2599   /// By default, performs semantic analysis to build the new expression.
2600   /// Subclasses may override this routine to provide different behavior.
2601   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2602                                         SourceLocation RParenLoc,
2603                                         ArrayRef<Expr *> Dims,
2604                                         ArrayRef<SourceRange> BracketsRanges) {
2605     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2606                                               BracketsRanges);
2607   }
2608 
2609   /// Build a new iterator expression.
2610   ///
2611   /// By default, performs semantic analysis to build the new expression.
2612   /// Subclasses may override this routine to provide different behavior.
2613   ExprResult RebuildOMPIteratorExpr(
2614       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2615       ArrayRef<Sema::OMPIteratorData> Data) {
2616     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2617                                           LLoc, RLoc, Data);
2618   }
2619 
2620   /// Build a new call expression.
2621   ///
2622   /// By default, performs semantic analysis to build the new expression.
2623   /// Subclasses may override this routine to provide different behavior.
2624   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2625                                    MultiExprArg Args,
2626                                    SourceLocation RParenLoc,
2627                                    Expr *ExecConfig = nullptr) {
2628     return getSema().ActOnCallExpr(
2629         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2630   }
2631 
2632   /// Build a new member access expression.
2633   ///
2634   /// By default, performs semantic analysis to build the new expression.
2635   /// Subclasses may override this routine to provide different behavior.
2636   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2637                                bool isArrow,
2638                                NestedNameSpecifierLoc QualifierLoc,
2639                                SourceLocation TemplateKWLoc,
2640                                const DeclarationNameInfo &MemberNameInfo,
2641                                ValueDecl *Member,
2642                                NamedDecl *FoundDecl,
2643                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2644                                NamedDecl *FirstQualifierInScope) {
2645     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2646                                                                       isArrow);
2647     if (!Member->getDeclName()) {
2648       // We have a reference to an unnamed field.  This is always the
2649       // base of an anonymous struct/union member access, i.e. the
2650       // field is always of record type.
2651       assert(Member->getType()->isRecordType() &&
2652              "unnamed member not of record type?");
2653 
2654       BaseResult =
2655         getSema().PerformObjectMemberConversion(BaseResult.get(),
2656                                                 QualifierLoc.getNestedNameSpecifier(),
2657                                                 FoundDecl, Member);
2658       if (BaseResult.isInvalid())
2659         return ExprError();
2660       Base = BaseResult.get();
2661 
2662       CXXScopeSpec EmptySS;
2663       return getSema().BuildFieldReferenceExpr(
2664           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2665           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2666     }
2667 
2668     CXXScopeSpec SS;
2669     SS.Adopt(QualifierLoc);
2670 
2671     Base = BaseResult.get();
2672     QualType BaseType = Base->getType();
2673 
2674     if (isArrow && !BaseType->isPointerType())
2675       return ExprError();
2676 
2677     // FIXME: this involves duplicating earlier analysis in a lot of
2678     // cases; we should avoid this when possible.
2679     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2680     R.addDecl(FoundDecl);
2681     R.resolveKind();
2682 
2683     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2684                                               SS, TemplateKWLoc,
2685                                               FirstQualifierInScope,
2686                                               R, ExplicitTemplateArgs,
2687                                               /*S*/nullptr);
2688   }
2689 
2690   /// Build a new binary operator expression.
2691   ///
2692   /// By default, performs semantic analysis to build the new expression.
2693   /// Subclasses may override this routine to provide different behavior.
2694   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2695                                          BinaryOperatorKind Opc,
2696                                          Expr *LHS, Expr *RHS) {
2697     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2698   }
2699 
2700   /// Build a new rewritten operator expression.
2701   ///
2702   /// By default, performs semantic analysis to build the new expression.
2703   /// Subclasses may override this routine to provide different behavior.
2704   ExprResult RebuildCXXRewrittenBinaryOperator(
2705       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2706       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2707     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2708                                            RHS, /*RequiresADL*/false);
2709   }
2710 
2711   /// Build a new conditional operator expression.
2712   ///
2713   /// By default, performs semantic analysis to build the new expression.
2714   /// Subclasses may override this routine to provide different behavior.
2715   ExprResult RebuildConditionalOperator(Expr *Cond,
2716                                         SourceLocation QuestionLoc,
2717                                         Expr *LHS,
2718                                         SourceLocation ColonLoc,
2719                                         Expr *RHS) {
2720     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2721                                         LHS, RHS);
2722   }
2723 
2724   /// Build a new C-style cast expression.
2725   ///
2726   /// By default, performs semantic analysis to build the new expression.
2727   /// Subclasses may override this routine to provide different behavior.
2728   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2729                                          TypeSourceInfo *TInfo,
2730                                          SourceLocation RParenLoc,
2731                                          Expr *SubExpr) {
2732     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2733                                          SubExpr);
2734   }
2735 
2736   /// Build a new compound literal expression.
2737   ///
2738   /// By default, performs semantic analysis to build the new expression.
2739   /// Subclasses may override this routine to provide different behavior.
2740   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2741                                               TypeSourceInfo *TInfo,
2742                                               SourceLocation RParenLoc,
2743                                               Expr *Init) {
2744     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2745                                               Init);
2746   }
2747 
2748   /// Build a new extended vector element access expression.
2749   ///
2750   /// By default, performs semantic analysis to build the new expression.
2751   /// Subclasses may override this routine to provide different behavior.
2752   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2753                                                SourceLocation OpLoc,
2754                                                SourceLocation AccessorLoc,
2755                                                IdentifierInfo &Accessor) {
2756 
2757     CXXScopeSpec SS;
2758     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2759     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2760                                               OpLoc, /*IsArrow*/ false,
2761                                               SS, SourceLocation(),
2762                                               /*FirstQualifierInScope*/ nullptr,
2763                                               NameInfo,
2764                                               /* TemplateArgs */ nullptr,
2765                                               /*S*/ nullptr);
2766   }
2767 
2768   /// Build a new initializer list expression.
2769   ///
2770   /// By default, performs semantic analysis to build the new expression.
2771   /// Subclasses may override this routine to provide different behavior.
2772   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2773                              MultiExprArg Inits,
2774                              SourceLocation RBraceLoc) {
2775     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2776   }
2777 
2778   /// Build a new designated initializer expression.
2779   ///
2780   /// By default, performs semantic analysis to build the new expression.
2781   /// Subclasses may override this routine to provide different behavior.
2782   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2783                                              MultiExprArg ArrayExprs,
2784                                              SourceLocation EqualOrColonLoc,
2785                                              bool GNUSyntax,
2786                                              Expr *Init) {
2787     ExprResult Result
2788       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2789                                            Init);
2790     if (Result.isInvalid())
2791       return ExprError();
2792 
2793     return Result;
2794   }
2795 
2796   /// Build a new value-initialized expression.
2797   ///
2798   /// By default, builds the implicit value initialization without performing
2799   /// any semantic analysis. Subclasses may override this routine to provide
2800   /// different behavior.
2801   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2802     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2803   }
2804 
2805   /// Build a new \c va_arg expression.
2806   ///
2807   /// By default, performs semantic analysis to build the new expression.
2808   /// Subclasses may override this routine to provide different behavior.
2809   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2810                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2811                                     SourceLocation RParenLoc) {
2812     return getSema().BuildVAArgExpr(BuiltinLoc,
2813                                     SubExpr, TInfo,
2814                                     RParenLoc);
2815   }
2816 
2817   /// Build a new expression list in parentheses.
2818   ///
2819   /// By default, performs semantic analysis to build the new expression.
2820   /// Subclasses may override this routine to provide different behavior.
2821   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2822                                   MultiExprArg SubExprs,
2823                                   SourceLocation RParenLoc) {
2824     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2825   }
2826 
2827   /// Build a new address-of-label expression.
2828   ///
2829   /// By default, performs semantic analysis, using the name of the label
2830   /// rather than attempting to map the label statement itself.
2831   /// Subclasses may override this routine to provide different behavior.
2832   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2833                                   SourceLocation LabelLoc, LabelDecl *Label) {
2834     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2835   }
2836 
2837   /// Build a new GNU statement expression.
2838   ///
2839   /// By default, performs semantic analysis to build the new expression.
2840   /// Subclasses may override this routine to provide different behavior.
2841   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2842                              SourceLocation RParenLoc, unsigned TemplateDepth) {
2843     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2844                                    TemplateDepth);
2845   }
2846 
2847   /// Build a new __builtin_choose_expr expression.
2848   ///
2849   /// By default, performs semantic analysis to build the new expression.
2850   /// Subclasses may override this routine to provide different behavior.
2851   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2852                                      Expr *Cond, Expr *LHS, Expr *RHS,
2853                                      SourceLocation RParenLoc) {
2854     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2855                                    Cond, LHS, RHS,
2856                                    RParenLoc);
2857   }
2858 
2859   /// Build a new generic selection expression.
2860   ///
2861   /// By default, performs semantic analysis to build the new expression.
2862   /// Subclasses may override this routine to provide different behavior.
2863   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2864                                          SourceLocation DefaultLoc,
2865                                          SourceLocation RParenLoc,
2866                                          Expr *ControllingExpr,
2867                                          ArrayRef<TypeSourceInfo *> Types,
2868                                          ArrayRef<Expr *> Exprs) {
2869     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2870                                                 ControllingExpr, Types, Exprs);
2871   }
2872 
2873   /// Build a new overloaded operator call expression.
2874   ///
2875   /// By default, performs semantic analysis to build the new expression.
2876   /// The semantic analysis provides the behavior of template instantiation,
2877   /// copying with transformations that turn what looks like an overloaded
2878   /// operator call into a use of a builtin operator, performing
2879   /// argument-dependent lookup, etc. Subclasses may override this routine to
2880   /// provide different behavior.
2881   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2882                                               SourceLocation OpLoc,
2883                                               Expr *Callee,
2884                                               Expr *First,
2885                                               Expr *Second);
2886 
2887   /// Build a new C++ "named" cast expression, such as static_cast or
2888   /// reinterpret_cast.
2889   ///
2890   /// By default, this routine dispatches to one of the more-specific routines
2891   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2892   /// Subclasses may override this routine to provide different behavior.
2893   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2894                                            Stmt::StmtClass Class,
2895                                            SourceLocation LAngleLoc,
2896                                            TypeSourceInfo *TInfo,
2897                                            SourceLocation RAngleLoc,
2898                                            SourceLocation LParenLoc,
2899                                            Expr *SubExpr,
2900                                            SourceLocation RParenLoc) {
2901     switch (Class) {
2902     case Stmt::CXXStaticCastExprClass:
2903       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2904                                                    RAngleLoc, LParenLoc,
2905                                                    SubExpr, RParenLoc);
2906 
2907     case Stmt::CXXDynamicCastExprClass:
2908       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2909                                                     RAngleLoc, LParenLoc,
2910                                                     SubExpr, RParenLoc);
2911 
2912     case Stmt::CXXReinterpretCastExprClass:
2913       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2914                                                         RAngleLoc, LParenLoc,
2915                                                         SubExpr,
2916                                                         RParenLoc);
2917 
2918     case Stmt::CXXConstCastExprClass:
2919       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2920                                                    RAngleLoc, LParenLoc,
2921                                                    SubExpr, RParenLoc);
2922 
2923     case Stmt::CXXAddrspaceCastExprClass:
2924       return getDerived().RebuildCXXAddrspaceCastExpr(
2925           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
2926 
2927     default:
2928       llvm_unreachable("Invalid C++ named cast");
2929     }
2930   }
2931 
2932   /// Build a new C++ static_cast expression.
2933   ///
2934   /// By default, performs semantic analysis to build the new expression.
2935   /// Subclasses may override this routine to provide different behavior.
2936   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2937                                             SourceLocation LAngleLoc,
2938                                             TypeSourceInfo *TInfo,
2939                                             SourceLocation RAngleLoc,
2940                                             SourceLocation LParenLoc,
2941                                             Expr *SubExpr,
2942                                             SourceLocation RParenLoc) {
2943     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2944                                        TInfo, SubExpr,
2945                                        SourceRange(LAngleLoc, RAngleLoc),
2946                                        SourceRange(LParenLoc, RParenLoc));
2947   }
2948 
2949   /// Build a new C++ dynamic_cast expression.
2950   ///
2951   /// By default, performs semantic analysis to build the new expression.
2952   /// Subclasses may override this routine to provide different behavior.
2953   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2954                                              SourceLocation LAngleLoc,
2955                                              TypeSourceInfo *TInfo,
2956                                              SourceLocation RAngleLoc,
2957                                              SourceLocation LParenLoc,
2958                                              Expr *SubExpr,
2959                                              SourceLocation RParenLoc) {
2960     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2961                                        TInfo, SubExpr,
2962                                        SourceRange(LAngleLoc, RAngleLoc),
2963                                        SourceRange(LParenLoc, RParenLoc));
2964   }
2965 
2966   /// Build a new C++ reinterpret_cast 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 RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2971                                                  SourceLocation LAngleLoc,
2972                                                  TypeSourceInfo *TInfo,
2973                                                  SourceLocation RAngleLoc,
2974                                                  SourceLocation LParenLoc,
2975                                                  Expr *SubExpr,
2976                                                  SourceLocation RParenLoc) {
2977     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2978                                        TInfo, SubExpr,
2979                                        SourceRange(LAngleLoc, RAngleLoc),
2980                                        SourceRange(LParenLoc, RParenLoc));
2981   }
2982 
2983   /// Build a new C++ const_cast expression.
2984   ///
2985   /// By default, performs semantic analysis to build the new expression.
2986   /// Subclasses may override this routine to provide different behavior.
2987   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2988                                            SourceLocation LAngleLoc,
2989                                            TypeSourceInfo *TInfo,
2990                                            SourceLocation RAngleLoc,
2991                                            SourceLocation LParenLoc,
2992                                            Expr *SubExpr,
2993                                            SourceLocation RParenLoc) {
2994     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2995                                        TInfo, SubExpr,
2996                                        SourceRange(LAngleLoc, RAngleLoc),
2997                                        SourceRange(LParenLoc, RParenLoc));
2998   }
2999 
3000   ExprResult
3001   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3002                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3003                               SourceLocation LParenLoc, Expr *SubExpr,
3004                               SourceLocation RParenLoc) {
3005     return getSema().BuildCXXNamedCast(
3006         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3007         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3008   }
3009 
3010   /// Build a new C++ functional-style cast expression.
3011   ///
3012   /// By default, performs semantic analysis to build the new expression.
3013   /// Subclasses may override this routine to provide different behavior.
3014   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3015                                           SourceLocation LParenLoc,
3016                                           Expr *Sub,
3017                                           SourceLocation RParenLoc,
3018                                           bool ListInitialization) {
3019     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3020                                                MultiExprArg(&Sub, 1), RParenLoc,
3021                                                ListInitialization);
3022   }
3023 
3024   /// Build a new C++ __builtin_bit_cast expression.
3025   ///
3026   /// By default, performs semantic analysis to build the new expression.
3027   /// Subclasses may override this routine to provide different behavior.
3028   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3029                                        TypeSourceInfo *TSI, Expr *Sub,
3030                                        SourceLocation RParenLoc) {
3031     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3032   }
3033 
3034   /// Build a new C++ typeid(type) expression.
3035   ///
3036   /// By default, performs semantic analysis to build the new expression.
3037   /// Subclasses may override this routine to provide different behavior.
3038   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3039                                         SourceLocation TypeidLoc,
3040                                         TypeSourceInfo *Operand,
3041                                         SourceLocation RParenLoc) {
3042     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3043                                     RParenLoc);
3044   }
3045 
3046 
3047   /// Build a new C++ typeid(expr) expression.
3048   ///
3049   /// By default, performs semantic analysis to build the new expression.
3050   /// Subclasses may override this routine to provide different behavior.
3051   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3052                                         SourceLocation TypeidLoc,
3053                                         Expr *Operand,
3054                                         SourceLocation RParenLoc) {
3055     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3056                                     RParenLoc);
3057   }
3058 
3059   /// Build a new C++ __uuidof(type) expression.
3060   ///
3061   /// By default, performs semantic analysis to build the new expression.
3062   /// Subclasses may override this routine to provide different behavior.
3063   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3064                                   TypeSourceInfo *Operand,
3065                                   SourceLocation RParenLoc) {
3066     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3067   }
3068 
3069   /// Build a new C++ __uuidof(expr) 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 RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3074                                   Expr *Operand, SourceLocation RParenLoc) {
3075     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3076   }
3077 
3078   /// Build a new C++ "this" expression.
3079   ///
3080   /// By default, builds a new "this" expression without performing any
3081   /// semantic analysis. Subclasses may override this routine to provide
3082   /// different behavior.
3083   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3084                                 QualType ThisType,
3085                                 bool isImplicit) {
3086     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3087   }
3088 
3089   /// Build a new C++ throw expression.
3090   ///
3091   /// By default, performs semantic analysis to build the new expression.
3092   /// Subclasses may override this routine to provide different behavior.
3093   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3094                                  bool IsThrownVariableInScope) {
3095     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3096   }
3097 
3098   /// Build a new C++ default-argument expression.
3099   ///
3100   /// By default, builds a new default-argument expression, which does not
3101   /// require any semantic analysis. Subclasses may override this routine to
3102   /// provide different behavior.
3103   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
3104     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3105                                      getSema().CurContext);
3106   }
3107 
3108   /// Build a new C++11 default-initialization expression.
3109   ///
3110   /// By default, builds a new default field initialization expression, which
3111   /// does not require any semantic analysis. Subclasses may override this
3112   /// routine to provide different behavior.
3113   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3114                                        FieldDecl *Field) {
3115     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
3116                                       getSema().CurContext);
3117   }
3118 
3119   /// Build a new C++ zero-initialization expression.
3120   ///
3121   /// By default, performs semantic analysis to build the new expression.
3122   /// Subclasses may override this routine to provide different behavior.
3123   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3124                                            SourceLocation LParenLoc,
3125                                            SourceLocation RParenLoc) {
3126     return getSema().BuildCXXTypeConstructExpr(
3127         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
3128   }
3129 
3130   /// Build a new C++ "new" expression.
3131   ///
3132   /// By default, performs semantic analysis to build the new expression.
3133   /// Subclasses may override this routine to provide different behavior.
3134   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
3135                                bool UseGlobal,
3136                                SourceLocation PlacementLParen,
3137                                MultiExprArg PlacementArgs,
3138                                SourceLocation PlacementRParen,
3139                                SourceRange TypeIdParens,
3140                                QualType AllocatedType,
3141                                TypeSourceInfo *AllocatedTypeInfo,
3142                                Optional<Expr *> ArraySize,
3143                                SourceRange DirectInitRange,
3144                                Expr *Initializer) {
3145     return getSema().BuildCXXNew(StartLoc, UseGlobal,
3146                                  PlacementLParen,
3147                                  PlacementArgs,
3148                                  PlacementRParen,
3149                                  TypeIdParens,
3150                                  AllocatedType,
3151                                  AllocatedTypeInfo,
3152                                  ArraySize,
3153                                  DirectInitRange,
3154                                  Initializer);
3155   }
3156 
3157   /// Build a new C++ "delete" expression.
3158   ///
3159   /// By default, performs semantic analysis to build the new expression.
3160   /// Subclasses may override this routine to provide different behavior.
3161   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3162                                         bool IsGlobalDelete,
3163                                         bool IsArrayForm,
3164                                         Expr *Operand) {
3165     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3166                                     Operand);
3167   }
3168 
3169   /// Build a new type trait expression.
3170   ///
3171   /// By default, performs semantic analysis to build the new expression.
3172   /// Subclasses may override this routine to provide different behavior.
3173   ExprResult RebuildTypeTrait(TypeTrait Trait,
3174                               SourceLocation StartLoc,
3175                               ArrayRef<TypeSourceInfo *> Args,
3176                               SourceLocation RParenLoc) {
3177     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3178   }
3179 
3180   /// Build a new array type trait expression.
3181   ///
3182   /// By default, performs semantic analysis to build the new expression.
3183   /// Subclasses may override this routine to provide different behavior.
3184   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3185                                    SourceLocation StartLoc,
3186                                    TypeSourceInfo *TSInfo,
3187                                    Expr *DimExpr,
3188                                    SourceLocation RParenLoc) {
3189     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3190   }
3191 
3192   /// Build a new expression trait expression.
3193   ///
3194   /// By default, performs semantic analysis to build the new expression.
3195   /// Subclasses may override this routine to provide different behavior.
3196   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3197                                    SourceLocation StartLoc,
3198                                    Expr *Queried,
3199                                    SourceLocation RParenLoc) {
3200     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3201   }
3202 
3203   /// Build a new (previously unresolved) declaration reference
3204   /// expression.
3205   ///
3206   /// By default, performs semantic analysis to build the new expression.
3207   /// Subclasses may override this routine to provide different behavior.
3208   ExprResult RebuildDependentScopeDeclRefExpr(
3209                                           NestedNameSpecifierLoc QualifierLoc,
3210                                           SourceLocation TemplateKWLoc,
3211                                        const DeclarationNameInfo &NameInfo,
3212                               const TemplateArgumentListInfo *TemplateArgs,
3213                                           bool IsAddressOfOperand,
3214                                           TypeSourceInfo **RecoveryTSI) {
3215     CXXScopeSpec SS;
3216     SS.Adopt(QualifierLoc);
3217 
3218     if (TemplateArgs || TemplateKWLoc.isValid())
3219       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3220                                                     TemplateArgs);
3221 
3222     return getSema().BuildQualifiedDeclarationNameExpr(
3223         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3224   }
3225 
3226   /// Build a new template-id expression.
3227   ///
3228   /// By default, performs semantic analysis to build the new expression.
3229   /// Subclasses may override this routine to provide different behavior.
3230   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3231                                    SourceLocation TemplateKWLoc,
3232                                    LookupResult &R,
3233                                    bool RequiresADL,
3234                               const TemplateArgumentListInfo *TemplateArgs) {
3235     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3236                                          TemplateArgs);
3237   }
3238 
3239   /// Build a new object-construction expression.
3240   ///
3241   /// By default, performs semantic analysis to build the new expression.
3242   /// Subclasses may override this routine to provide different behavior.
3243   ExprResult RebuildCXXConstructExpr(QualType T,
3244                                      SourceLocation Loc,
3245                                      CXXConstructorDecl *Constructor,
3246                                      bool IsElidable,
3247                                      MultiExprArg Args,
3248                                      bool HadMultipleCandidates,
3249                                      bool ListInitialization,
3250                                      bool StdInitListInitialization,
3251                                      bool RequiresZeroInit,
3252                              CXXConstructExpr::ConstructionKind ConstructKind,
3253                                      SourceRange ParenRange) {
3254     // Reconstruct the constructor we originally found, which might be
3255     // different if this is a call to an inherited constructor.
3256     CXXConstructorDecl *FoundCtor = Constructor;
3257     if (Constructor->isInheritingConstructor())
3258       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3259 
3260     SmallVector<Expr *, 8> ConvertedArgs;
3261     if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3262                                           ConvertedArgs))
3263       return ExprError();
3264 
3265     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3266                                            IsElidable,
3267                                            ConvertedArgs,
3268                                            HadMultipleCandidates,
3269                                            ListInitialization,
3270                                            StdInitListInitialization,
3271                                            RequiresZeroInit, ConstructKind,
3272                                            ParenRange);
3273   }
3274 
3275   /// Build a new implicit construction via inherited constructor
3276   /// expression.
3277   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3278                                              CXXConstructorDecl *Constructor,
3279                                              bool ConstructsVBase,
3280                                              bool InheritedFromVBase) {
3281     return new (getSema().Context) CXXInheritedCtorInitExpr(
3282         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3283   }
3284 
3285   /// Build a new object-construction expression.
3286   ///
3287   /// By default, performs semantic analysis to build the new expression.
3288   /// Subclasses may override this routine to provide different behavior.
3289   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3290                                            SourceLocation LParenOrBraceLoc,
3291                                            MultiExprArg Args,
3292                                            SourceLocation RParenOrBraceLoc,
3293                                            bool ListInitialization) {
3294     return getSema().BuildCXXTypeConstructExpr(
3295         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3296   }
3297 
3298   /// Build a new object-construction expression.
3299   ///
3300   /// By default, performs semantic analysis to build the new expression.
3301   /// Subclasses may override this routine to provide different behavior.
3302   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3303                                                SourceLocation LParenLoc,
3304                                                MultiExprArg Args,
3305                                                SourceLocation RParenLoc,
3306                                                bool ListInitialization) {
3307     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3308                                                RParenLoc, ListInitialization);
3309   }
3310 
3311   /// Build a new member reference expression.
3312   ///
3313   /// By default, performs semantic analysis to build the new expression.
3314   /// Subclasses may override this routine to provide different behavior.
3315   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3316                                                 QualType BaseType,
3317                                                 bool IsArrow,
3318                                                 SourceLocation OperatorLoc,
3319                                           NestedNameSpecifierLoc QualifierLoc,
3320                                                 SourceLocation TemplateKWLoc,
3321                                             NamedDecl *FirstQualifierInScope,
3322                                    const DeclarationNameInfo &MemberNameInfo,
3323                               const TemplateArgumentListInfo *TemplateArgs) {
3324     CXXScopeSpec SS;
3325     SS.Adopt(QualifierLoc);
3326 
3327     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3328                                             OperatorLoc, IsArrow,
3329                                             SS, TemplateKWLoc,
3330                                             FirstQualifierInScope,
3331                                             MemberNameInfo,
3332                                             TemplateArgs, /*S*/nullptr);
3333   }
3334 
3335   /// Build a new member reference expression.
3336   ///
3337   /// By default, performs semantic analysis to build the new expression.
3338   /// Subclasses may override this routine to provide different behavior.
3339   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3340                                          SourceLocation OperatorLoc,
3341                                          bool IsArrow,
3342                                          NestedNameSpecifierLoc QualifierLoc,
3343                                          SourceLocation TemplateKWLoc,
3344                                          NamedDecl *FirstQualifierInScope,
3345                                          LookupResult &R,
3346                                 const TemplateArgumentListInfo *TemplateArgs) {
3347     CXXScopeSpec SS;
3348     SS.Adopt(QualifierLoc);
3349 
3350     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3351                                             OperatorLoc, IsArrow,
3352                                             SS, TemplateKWLoc,
3353                                             FirstQualifierInScope,
3354                                             R, TemplateArgs, /*S*/nullptr);
3355   }
3356 
3357   /// Build a new noexcept expression.
3358   ///
3359   /// By default, performs semantic analysis to build the new expression.
3360   /// Subclasses may override this routine to provide different behavior.
3361   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3362     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3363   }
3364 
3365   /// Build a new expression to compute the length of a parameter pack.
3366   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3367                                    NamedDecl *Pack,
3368                                    SourceLocation PackLoc,
3369                                    SourceLocation RParenLoc,
3370                                    Optional<unsigned> Length,
3371                                    ArrayRef<TemplateArgument> PartialArgs) {
3372     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3373                                   RParenLoc, Length, PartialArgs);
3374   }
3375 
3376   /// Build a new expression representing a call to a source location
3377   ///  builtin.
3378   ///
3379   /// By default, performs semantic analysis to build the new expression.
3380   /// Subclasses may override this routine to provide different behavior.
3381   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3382                                   SourceLocation BuiltinLoc,
3383                                   SourceLocation RPLoc,
3384                                   DeclContext *ParentContext) {
3385     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3386   }
3387 
3388   /// Build a new Objective-C boxed expression.
3389   ///
3390   /// By default, performs semantic analysis to build the new expression.
3391   /// Subclasses may override this routine to provide different behavior.
3392   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3393       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3394       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3395       TemplateArgumentListInfo *TALI) {
3396     CXXScopeSpec SS;
3397     SS.Adopt(NNS);
3398     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3399                                                          ConceptNameInfo,
3400                                                          FoundDecl,
3401                                                          NamedConcept, TALI);
3402     if (Result.isInvalid())
3403       return ExprError();
3404     return Result;
3405   }
3406 
3407   /// \brief Build a new requires expression.
3408   ///
3409   /// By default, performs semantic analysis to build the new expression.
3410   /// Subclasses may override this routine to provide different behavior.
3411   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3412                                  RequiresExprBodyDecl *Body,
3413                                  ArrayRef<ParmVarDecl *> LocalParameters,
3414                                  ArrayRef<concepts::Requirement *> Requirements,
3415                                  SourceLocation ClosingBraceLoc) {
3416     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3417                                 LocalParameters, Requirements, ClosingBraceLoc);
3418   }
3419 
3420   concepts::TypeRequirement *
3421   RebuildTypeRequirement(
3422       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3423     return SemaRef.BuildTypeRequirement(SubstDiag);
3424   }
3425 
3426   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3427     return SemaRef.BuildTypeRequirement(T);
3428   }
3429 
3430   concepts::ExprRequirement *
3431   RebuildExprRequirement(
3432       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3433       SourceLocation NoexceptLoc,
3434       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3435     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3436                                         std::move(Ret));
3437   }
3438 
3439   concepts::ExprRequirement *
3440   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3441                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3442     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3443                                         std::move(Ret));
3444   }
3445 
3446   concepts::NestedRequirement *
3447   RebuildNestedRequirement(
3448       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3449     return SemaRef.BuildNestedRequirement(SubstDiag);
3450   }
3451 
3452   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3453     return SemaRef.BuildNestedRequirement(Constraint);
3454   }
3455 
3456   /// \brief Build a new Objective-C boxed expression.
3457   ///
3458   /// By default, performs semantic analysis to build the new expression.
3459   /// Subclasses may override this routine to provide different behavior.
3460   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3461     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3462   }
3463 
3464   /// Build a new Objective-C array literal.
3465   ///
3466   /// By default, performs semantic analysis to build the new expression.
3467   /// Subclasses may override this routine to provide different behavior.
3468   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3469                                      Expr **Elements, unsigned NumElements) {
3470     return getSema().BuildObjCArrayLiteral(Range,
3471                                            MultiExprArg(Elements, NumElements));
3472   }
3473 
3474   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3475                                          Expr *Base, Expr *Key,
3476                                          ObjCMethodDecl *getterMethod,
3477                                          ObjCMethodDecl *setterMethod) {
3478     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3479                                                    getterMethod, setterMethod);
3480   }
3481 
3482   /// Build a new Objective-C dictionary literal.
3483   ///
3484   /// By default, performs semantic analysis to build the new expression.
3485   /// Subclasses may override this routine to provide different behavior.
3486   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3487                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3488     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3489   }
3490 
3491   /// Build a new Objective-C \@encode expression.
3492   ///
3493   /// By default, performs semantic analysis to build the new expression.
3494   /// Subclasses may override this routine to provide different behavior.
3495   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3496                                          TypeSourceInfo *EncodeTypeInfo,
3497                                          SourceLocation RParenLoc) {
3498     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3499   }
3500 
3501   /// Build a new Objective-C class message.
3502   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3503                                           Selector Sel,
3504                                           ArrayRef<SourceLocation> SelectorLocs,
3505                                           ObjCMethodDecl *Method,
3506                                           SourceLocation LBracLoc,
3507                                           MultiExprArg Args,
3508                                           SourceLocation RBracLoc) {
3509     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3510                                      ReceiverTypeInfo->getType(),
3511                                      /*SuperLoc=*/SourceLocation(),
3512                                      Sel, Method, LBracLoc, SelectorLocs,
3513                                      RBracLoc, Args);
3514   }
3515 
3516   /// Build a new Objective-C instance message.
3517   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3518                                           Selector Sel,
3519                                           ArrayRef<SourceLocation> SelectorLocs,
3520                                           ObjCMethodDecl *Method,
3521                                           SourceLocation LBracLoc,
3522                                           MultiExprArg Args,
3523                                           SourceLocation RBracLoc) {
3524     return SemaRef.BuildInstanceMessage(Receiver,
3525                                         Receiver->getType(),
3526                                         /*SuperLoc=*/SourceLocation(),
3527                                         Sel, Method, LBracLoc, SelectorLocs,
3528                                         RBracLoc, Args);
3529   }
3530 
3531   /// Build a new Objective-C instance/class message to 'super'.
3532   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3533                                     Selector Sel,
3534                                     ArrayRef<SourceLocation> SelectorLocs,
3535                                     QualType SuperType,
3536                                     ObjCMethodDecl *Method,
3537                                     SourceLocation LBracLoc,
3538                                     MultiExprArg Args,
3539                                     SourceLocation RBracLoc) {
3540     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3541                                           SuperType,
3542                                           SuperLoc,
3543                                           Sel, Method, LBracLoc, SelectorLocs,
3544                                           RBracLoc, Args)
3545                                       : SemaRef.BuildClassMessage(nullptr,
3546                                           SuperType,
3547                                           SuperLoc,
3548                                           Sel, Method, LBracLoc, SelectorLocs,
3549                                           RBracLoc, Args);
3550 
3551 
3552   }
3553 
3554   /// Build a new Objective-C ivar reference expression.
3555   ///
3556   /// By default, performs semantic analysis to build the new expression.
3557   /// Subclasses may override this routine to provide different behavior.
3558   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3559                                           SourceLocation IvarLoc,
3560                                           bool IsArrow, bool IsFreeIvar) {
3561     CXXScopeSpec SS;
3562     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3563     ExprResult Result = getSema().BuildMemberReferenceExpr(
3564         BaseArg, BaseArg->getType(),
3565         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3566         /*FirstQualifierInScope=*/nullptr, NameInfo,
3567         /*TemplateArgs=*/nullptr,
3568         /*S=*/nullptr);
3569     if (IsFreeIvar && Result.isUsable())
3570       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3571     return Result;
3572   }
3573 
3574   /// Build a new Objective-C property reference expression.
3575   ///
3576   /// By default, performs semantic analysis to build the new expression.
3577   /// Subclasses may override this routine to provide different behavior.
3578   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3579                                         ObjCPropertyDecl *Property,
3580                                         SourceLocation PropertyLoc) {
3581     CXXScopeSpec SS;
3582     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3583     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3584                                               /*FIXME:*/PropertyLoc,
3585                                               /*IsArrow=*/false,
3586                                               SS, SourceLocation(),
3587                                               /*FirstQualifierInScope=*/nullptr,
3588                                               NameInfo,
3589                                               /*TemplateArgs=*/nullptr,
3590                                               /*S=*/nullptr);
3591   }
3592 
3593   /// Build a new Objective-C property reference expression.
3594   ///
3595   /// By default, performs semantic analysis to build the new expression.
3596   /// Subclasses may override this routine to provide different behavior.
3597   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3598                                         ObjCMethodDecl *Getter,
3599                                         ObjCMethodDecl *Setter,
3600                                         SourceLocation PropertyLoc) {
3601     // Since these expressions can only be value-dependent, we do not
3602     // need to perform semantic analysis again.
3603     return Owned(
3604       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3605                                                   VK_LValue, OK_ObjCProperty,
3606                                                   PropertyLoc, Base));
3607   }
3608 
3609   /// Build a new Objective-C "isa" expression.
3610   ///
3611   /// By default, performs semantic analysis to build the new expression.
3612   /// Subclasses may override this routine to provide different behavior.
3613   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3614                                 SourceLocation OpLoc, bool IsArrow) {
3615     CXXScopeSpec SS;
3616     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3617     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3618                                               OpLoc, IsArrow,
3619                                               SS, SourceLocation(),
3620                                               /*FirstQualifierInScope=*/nullptr,
3621                                               NameInfo,
3622                                               /*TemplateArgs=*/nullptr,
3623                                               /*S=*/nullptr);
3624   }
3625 
3626   /// Build a new shuffle vector expression.
3627   ///
3628   /// By default, performs semantic analysis to build the new expression.
3629   /// Subclasses may override this routine to provide different behavior.
3630   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3631                                       MultiExprArg SubExprs,
3632                                       SourceLocation RParenLoc) {
3633     // Find the declaration for __builtin_shufflevector
3634     const IdentifierInfo &Name
3635       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3636     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3637     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3638     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3639 
3640     // Build a reference to the __builtin_shufflevector builtin
3641     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3642     Expr *Callee = new (SemaRef.Context)
3643         DeclRefExpr(SemaRef.Context, Builtin, false,
3644                     SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3645     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3646     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3647                                        CK_BuiltinFnToFnPtr).get();
3648 
3649     // Build the CallExpr
3650     ExprResult TheCall = CallExpr::Create(
3651         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3652         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3653         FPOptionsOverride());
3654 
3655     // Type-check the __builtin_shufflevector expression.
3656     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3657   }
3658 
3659   /// Build a new convert vector expression.
3660   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3661                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3662                                       SourceLocation RParenLoc) {
3663     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3664                                          BuiltinLoc, RParenLoc);
3665   }
3666 
3667   /// Build a new template argument pack expansion.
3668   ///
3669   /// By default, performs semantic analysis to build a new pack expansion
3670   /// for a template argument. Subclasses may override this routine to provide
3671   /// different behavior.
3672   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3673                                            SourceLocation EllipsisLoc,
3674                                            Optional<unsigned> NumExpansions) {
3675     switch (Pattern.getArgument().getKind()) {
3676     case TemplateArgument::Expression: {
3677       ExprResult Result
3678         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3679                                        EllipsisLoc, NumExpansions);
3680       if (Result.isInvalid())
3681         return TemplateArgumentLoc();
3682 
3683       return TemplateArgumentLoc(Result.get(), Result.get());
3684     }
3685 
3686     case TemplateArgument::Template:
3687       return TemplateArgumentLoc(
3688           SemaRef.Context,
3689           TemplateArgument(Pattern.getArgument().getAsTemplate(),
3690                            NumExpansions),
3691           Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3692           EllipsisLoc);
3693 
3694     case TemplateArgument::Null:
3695     case TemplateArgument::Integral:
3696     case TemplateArgument::Declaration:
3697     case TemplateArgument::Pack:
3698     case TemplateArgument::TemplateExpansion:
3699     case TemplateArgument::NullPtr:
3700       llvm_unreachable("Pack expansion pattern has no parameter packs");
3701 
3702     case TemplateArgument::Type:
3703       if (TypeSourceInfo *Expansion
3704             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3705                                            EllipsisLoc,
3706                                            NumExpansions))
3707         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3708                                    Expansion);
3709       break;
3710     }
3711 
3712     return TemplateArgumentLoc();
3713   }
3714 
3715   /// Build a new expression pack expansion.
3716   ///
3717   /// By default, performs semantic analysis to build a new pack expansion
3718   /// for an expression. Subclasses may override this routine to provide
3719   /// different behavior.
3720   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3721                                   Optional<unsigned> NumExpansions) {
3722     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3723   }
3724 
3725   /// Build a new C++1z fold-expression.
3726   ///
3727   /// By default, performs semantic analysis in order to build a new fold
3728   /// expression.
3729   ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3730                                 SourceLocation LParenLoc, Expr *LHS,
3731                                 BinaryOperatorKind Operator,
3732                                 SourceLocation EllipsisLoc, Expr *RHS,
3733                                 SourceLocation RParenLoc,
3734                                 Optional<unsigned> NumExpansions) {
3735     return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3736                                       EllipsisLoc, RHS, RParenLoc,
3737                                       NumExpansions);
3738   }
3739 
3740   /// Build an empty C++1z fold-expression with the given operator.
3741   ///
3742   /// By default, produces the fallback value for the fold-expression, or
3743   /// produce an error if there is no fallback value.
3744   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3745                                      BinaryOperatorKind Operator) {
3746     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3747   }
3748 
3749   /// Build a new atomic operation expression.
3750   ///
3751   /// By default, performs semantic analysis to build the new expression.
3752   /// Subclasses may override this routine to provide different behavior.
3753   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3754                                AtomicExpr::AtomicOp Op,
3755                                SourceLocation RParenLoc) {
3756     // Use this for all of the locations, since we don't know the difference
3757     // between the call and the expr at this point.
3758     SourceRange Range{BuiltinLoc, RParenLoc};
3759     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3760                                      Sema::AtomicArgumentOrder::AST);
3761   }
3762 
3763   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3764                                  ArrayRef<Expr *> SubExprs, QualType Type) {
3765     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3766   }
3767 
3768 private:
3769   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3770                                      QualType ObjectType,
3771                                      NamedDecl *FirstQualifierInScope,
3772                                      CXXScopeSpec &SS);
3773 
3774   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3775                                              QualType ObjectType,
3776                                              NamedDecl *FirstQualifierInScope,
3777                                              CXXScopeSpec &SS);
3778 
3779   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3780                                             NamedDecl *FirstQualifierInScope,
3781                                             CXXScopeSpec &SS);
3782 
3783   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3784                                       DependentNameTypeLoc TL,
3785                                       bool DeducibleTSTContext);
3786 };
3787 
3788 template <typename Derived>
3789 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3790   if (!S)
3791     return S;
3792 
3793   switch (S->getStmtClass()) {
3794   case Stmt::NoStmtClass: break;
3795 
3796   // Transform individual statement nodes
3797   // Pass SDK into statements that can produce a value
3798 #define STMT(Node, Parent)                                              \
3799   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3800 #define VALUESTMT(Node, Parent)                                         \
3801   case Stmt::Node##Class:                                               \
3802     return getDerived().Transform##Node(cast<Node>(S), SDK);
3803 #define ABSTRACT_STMT(Node)
3804 #define EXPR(Node, Parent)
3805 #include "clang/AST/StmtNodes.inc"
3806 
3807   // Transform expressions by calling TransformExpr.
3808 #define STMT(Node, Parent)
3809 #define ABSTRACT_STMT(Stmt)
3810 #define EXPR(Node, Parent) case Stmt::Node##Class:
3811 #include "clang/AST/StmtNodes.inc"
3812     {
3813       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3814 
3815       if (SDK == SDK_StmtExprResult)
3816         E = getSema().ActOnStmtExprResult(E);
3817       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3818     }
3819   }
3820 
3821   return S;
3822 }
3823 
3824 template<typename Derived>
3825 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3826   if (!S)
3827     return S;
3828 
3829   switch (S->getClauseKind()) {
3830   default: break;
3831   // Transform individual clause nodes
3832 #define GEN_CLANG_CLAUSE_CLASS
3833 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
3834   case Enum:                                                                   \
3835     return getDerived().Transform##Class(cast<Class>(S));
3836 #include "llvm/Frontend/OpenMP/OMP.inc"
3837   }
3838 
3839   return S;
3840 }
3841 
3842 
3843 template<typename Derived>
3844 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3845   if (!E)
3846     return E;
3847 
3848   switch (E->getStmtClass()) {
3849     case Stmt::NoStmtClass: break;
3850 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3851 #define ABSTRACT_STMT(Stmt)
3852 #define EXPR(Node, Parent)                                              \
3853     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3854 #include "clang/AST/StmtNodes.inc"
3855   }
3856 
3857   return E;
3858 }
3859 
3860 template<typename Derived>
3861 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3862                                                         bool NotCopyInit) {
3863   // Initializers are instantiated like expressions, except that various outer
3864   // layers are stripped.
3865   if (!Init)
3866     return Init;
3867 
3868   if (auto *FE = dyn_cast<FullExpr>(Init))
3869     Init = FE->getSubExpr();
3870 
3871   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
3872     OpaqueValueExpr *OVE = AIL->getCommonExpr();
3873     Init = OVE->getSourceExpr();
3874   }
3875 
3876   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3877     Init = MTE->getSubExpr();
3878 
3879   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3880     Init = Binder->getSubExpr();
3881 
3882   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3883     Init = ICE->getSubExprAsWritten();
3884 
3885   if (CXXStdInitializerListExpr *ILE =
3886           dyn_cast<CXXStdInitializerListExpr>(Init))
3887     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3888 
3889   // If this is copy-initialization, we only need to reconstruct
3890   // InitListExprs. Other forms of copy-initialization will be a no-op if
3891   // the initializer is already the right type.
3892   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3893   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3894     return getDerived().TransformExpr(Init);
3895 
3896   // Revert value-initialization back to empty parens.
3897   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3898     SourceRange Parens = VIE->getSourceRange();
3899     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3900                                              Parens.getEnd());
3901   }
3902 
3903   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3904   if (isa<ImplicitValueInitExpr>(Init))
3905     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3906                                              SourceLocation());
3907 
3908   // Revert initialization by constructor back to a parenthesized or braced list
3909   // of expressions. Any other form of initializer can just be reused directly.
3910   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3911     return getDerived().TransformExpr(Init);
3912 
3913   // If the initialization implicitly converted an initializer list to a
3914   // std::initializer_list object, unwrap the std::initializer_list too.
3915   if (Construct && Construct->isStdInitListInitialization())
3916     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3917 
3918   // Enter a list-init context if this was list initialization.
3919   EnterExpressionEvaluationContext Context(
3920       getSema(), EnterExpressionEvaluationContext::InitList,
3921       Construct->isListInitialization());
3922 
3923   SmallVector<Expr*, 8> NewArgs;
3924   bool ArgChanged = false;
3925   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3926                                   /*IsCall*/true, NewArgs, &ArgChanged))
3927     return ExprError();
3928 
3929   // If this was list initialization, revert to syntactic list form.
3930   if (Construct->isListInitialization())
3931     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3932                                         Construct->getEndLoc());
3933 
3934   // Build a ParenListExpr to represent anything else.
3935   SourceRange Parens = Construct->getParenOrBraceRange();
3936   if (Parens.isInvalid()) {
3937     // This was a variable declaration's initialization for which no initializer
3938     // was specified.
3939     assert(NewArgs.empty() &&
3940            "no parens or braces but have direct init with arguments?");
3941     return ExprEmpty();
3942   }
3943   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3944                                            Parens.getEnd());
3945 }
3946 
3947 template<typename Derived>
3948 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3949                                             unsigned NumInputs,
3950                                             bool IsCall,
3951                                       SmallVectorImpl<Expr *> &Outputs,
3952                                             bool *ArgChanged) {
3953   for (unsigned I = 0; I != NumInputs; ++I) {
3954     // If requested, drop call arguments that need to be dropped.
3955     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3956       if (ArgChanged)
3957         *ArgChanged = true;
3958 
3959       break;
3960     }
3961 
3962     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3963       Expr *Pattern = Expansion->getPattern();
3964 
3965       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3966       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3967       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3968 
3969       // Determine whether the set of unexpanded parameter packs can and should
3970       // be expanded.
3971       bool Expand = true;
3972       bool RetainExpansion = false;
3973       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3974       Optional<unsigned> NumExpansions = OrigNumExpansions;
3975       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3976                                                Pattern->getSourceRange(),
3977                                                Unexpanded,
3978                                                Expand, RetainExpansion,
3979                                                NumExpansions))
3980         return true;
3981 
3982       if (!Expand) {
3983         // The transform has determined that we should perform a simple
3984         // transformation on the pack expansion, producing another pack
3985         // expansion.
3986         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3987         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3988         if (OutPattern.isInvalid())
3989           return true;
3990 
3991         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3992                                                 Expansion->getEllipsisLoc(),
3993                                                            NumExpansions);
3994         if (Out.isInvalid())
3995           return true;
3996 
3997         if (ArgChanged)
3998           *ArgChanged = true;
3999         Outputs.push_back(Out.get());
4000         continue;
4001       }
4002 
4003       // Record right away that the argument was changed.  This needs
4004       // to happen even if the array expands to nothing.
4005       if (ArgChanged) *ArgChanged = true;
4006 
4007       // The transform has determined that we should perform an elementwise
4008       // expansion of the pattern. Do so.
4009       for (unsigned I = 0; I != *NumExpansions; ++I) {
4010         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4011         ExprResult Out = getDerived().TransformExpr(Pattern);
4012         if (Out.isInvalid())
4013           return true;
4014 
4015         if (Out.get()->containsUnexpandedParameterPack()) {
4016           Out = getDerived().RebuildPackExpansion(
4017               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4018           if (Out.isInvalid())
4019             return true;
4020         }
4021 
4022         Outputs.push_back(Out.get());
4023       }
4024 
4025       // If we're supposed to retain a pack expansion, do so by temporarily
4026       // forgetting the partially-substituted parameter pack.
4027       if (RetainExpansion) {
4028         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4029 
4030         ExprResult Out = getDerived().TransformExpr(Pattern);
4031         if (Out.isInvalid())
4032           return true;
4033 
4034         Out = getDerived().RebuildPackExpansion(
4035             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4036         if (Out.isInvalid())
4037           return true;
4038 
4039         Outputs.push_back(Out.get());
4040       }
4041 
4042       continue;
4043     }
4044 
4045     ExprResult Result =
4046       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4047              : getDerived().TransformExpr(Inputs[I]);
4048     if (Result.isInvalid())
4049       return true;
4050 
4051     if (Result.get() != Inputs[I] && ArgChanged)
4052       *ArgChanged = true;
4053 
4054     Outputs.push_back(Result.get());
4055   }
4056 
4057   return false;
4058 }
4059 
4060 template <typename Derived>
4061 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4062     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4063   if (Var) {
4064     VarDecl *ConditionVar = cast_or_null<VarDecl>(
4065         getDerived().TransformDefinition(Var->getLocation(), Var));
4066 
4067     if (!ConditionVar)
4068       return Sema::ConditionError();
4069 
4070     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4071   }
4072 
4073   if (Expr) {
4074     ExprResult CondExpr = getDerived().TransformExpr(Expr);
4075 
4076     if (CondExpr.isInvalid())
4077       return Sema::ConditionError();
4078 
4079     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4080                                     /*MissingOK=*/true);
4081   }
4082 
4083   return Sema::ConditionResult();
4084 }
4085 
4086 template <typename Derived>
4087 NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4088     NestedNameSpecifierLoc NNS, QualType ObjectType,
4089     NamedDecl *FirstQualifierInScope) {
4090   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4091   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4092        Qualifier = Qualifier.getPrefix())
4093     Qualifiers.push_back(Qualifier);
4094 
4095   CXXScopeSpec SS;
4096   while (!Qualifiers.empty()) {
4097     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4098     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4099 
4100     switch (QNNS->getKind()) {
4101     case NestedNameSpecifier::Identifier: {
4102       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4103                                       Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4104                                       ObjectType);
4105       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4106                                               SS, FirstQualifierInScope, false))
4107         return NestedNameSpecifierLoc();
4108       break;
4109     }
4110 
4111     case NestedNameSpecifier::Namespace: {
4112       NamespaceDecl *NS =
4113           cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4114               Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4115       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4116       break;
4117     }
4118 
4119     case NestedNameSpecifier::NamespaceAlias: {
4120       NamespaceAliasDecl *Alias =
4121           cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4122               Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4123       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4124                 Q.getLocalEndLoc());
4125       break;
4126     }
4127 
4128     case NestedNameSpecifier::Global:
4129       // There is no meaningful transformation that one could perform on the
4130       // global scope.
4131       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4132       break;
4133 
4134     case NestedNameSpecifier::Super: {
4135       CXXRecordDecl *RD =
4136           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4137               SourceLocation(), QNNS->getAsRecordDecl()));
4138       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4139       break;
4140     }
4141 
4142     case NestedNameSpecifier::TypeSpecWithTemplate:
4143     case NestedNameSpecifier::TypeSpec: {
4144       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4145                                               FirstQualifierInScope, SS);
4146 
4147       if (!TL)
4148         return NestedNameSpecifierLoc();
4149 
4150       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
4151           (SemaRef.getLangOpts().CPlusPlus11 &&
4152            TL.getType()->isEnumeralType())) {
4153         assert(!TL.getType().hasLocalQualifiers() &&
4154                "Can't get cv-qualifiers here");
4155         if (TL.getType()->isEnumeralType())
4156           SemaRef.Diag(TL.getBeginLoc(),
4157                        diag::warn_cxx98_compat_enum_nested_name_spec);
4158         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4159                   Q.getLocalEndLoc());
4160         break;
4161       }
4162       // If the nested-name-specifier is an invalid type def, don't emit an
4163       // error because a previous error should have already been emitted.
4164       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
4165       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4166         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4167             << TL.getType() << SS.getRange();
4168       }
4169       return NestedNameSpecifierLoc();
4170     }
4171     }
4172 
4173     // The qualifier-in-scope and object type only apply to the leftmost entity.
4174     FirstQualifierInScope = nullptr;
4175     ObjectType = QualType();
4176   }
4177 
4178   // Don't rebuild the nested-name-specifier if we don't have to.
4179   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4180       !getDerived().AlwaysRebuild())
4181     return NNS;
4182 
4183   // If we can re-use the source-location data from the original
4184   // nested-name-specifier, do so.
4185   if (SS.location_size() == NNS.getDataLength() &&
4186       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4187     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4188 
4189   // Allocate new nested-name-specifier location information.
4190   return SS.getWithLocInContext(SemaRef.Context);
4191 }
4192 
4193 template<typename Derived>
4194 DeclarationNameInfo
4195 TreeTransform<Derived>
4196 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4197   DeclarationName Name = NameInfo.getName();
4198   if (!Name)
4199     return DeclarationNameInfo();
4200 
4201   switch (Name.getNameKind()) {
4202   case DeclarationName::Identifier:
4203   case DeclarationName::ObjCZeroArgSelector:
4204   case DeclarationName::ObjCOneArgSelector:
4205   case DeclarationName::ObjCMultiArgSelector:
4206   case DeclarationName::CXXOperatorName:
4207   case DeclarationName::CXXLiteralOperatorName:
4208   case DeclarationName::CXXUsingDirective:
4209     return NameInfo;
4210 
4211   case DeclarationName::CXXDeductionGuideName: {
4212     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4213     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4214         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4215     if (!NewTemplate)
4216       return DeclarationNameInfo();
4217 
4218     DeclarationNameInfo NewNameInfo(NameInfo);
4219     NewNameInfo.setName(
4220         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4221     return NewNameInfo;
4222   }
4223 
4224   case DeclarationName::CXXConstructorName:
4225   case DeclarationName::CXXDestructorName:
4226   case DeclarationName::CXXConversionFunctionName: {
4227     TypeSourceInfo *NewTInfo;
4228     CanQualType NewCanTy;
4229     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4230       NewTInfo = getDerived().TransformType(OldTInfo);
4231       if (!NewTInfo)
4232         return DeclarationNameInfo();
4233       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4234     }
4235     else {
4236       NewTInfo = nullptr;
4237       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4238       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4239       if (NewT.isNull())
4240         return DeclarationNameInfo();
4241       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4242     }
4243 
4244     DeclarationName NewName
4245       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4246                                                            NewCanTy);
4247     DeclarationNameInfo NewNameInfo(NameInfo);
4248     NewNameInfo.setName(NewName);
4249     NewNameInfo.setNamedTypeInfo(NewTInfo);
4250     return NewNameInfo;
4251   }
4252   }
4253 
4254   llvm_unreachable("Unknown name kind.");
4255 }
4256 
4257 template<typename Derived>
4258 TemplateName
4259 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4260                                               TemplateName Name,
4261                                               SourceLocation NameLoc,
4262                                               QualType ObjectType,
4263                                               NamedDecl *FirstQualifierInScope,
4264                                               bool AllowInjectedClassName) {
4265   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4266     TemplateDecl *Template = QTN->getTemplateDecl();
4267     assert(Template && "qualified template name must refer to a template");
4268 
4269     TemplateDecl *TransTemplate
4270       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4271                                                               Template));
4272     if (!TransTemplate)
4273       return TemplateName();
4274 
4275     if (!getDerived().AlwaysRebuild() &&
4276         SS.getScopeRep() == QTN->getQualifier() &&
4277         TransTemplate == Template)
4278       return Name;
4279 
4280     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4281                                             TransTemplate);
4282   }
4283 
4284   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4285     if (SS.getScopeRep()) {
4286       // These apply to the scope specifier, not the template.
4287       ObjectType = QualType();
4288       FirstQualifierInScope = nullptr;
4289     }
4290 
4291     if (!getDerived().AlwaysRebuild() &&
4292         SS.getScopeRep() == DTN->getQualifier() &&
4293         ObjectType.isNull())
4294       return Name;
4295 
4296     // FIXME: Preserve the location of the "template" keyword.
4297     SourceLocation TemplateKWLoc = NameLoc;
4298 
4299     if (DTN->isIdentifier()) {
4300       return getDerived().RebuildTemplateName(SS,
4301                                               TemplateKWLoc,
4302                                               *DTN->getIdentifier(),
4303                                               NameLoc,
4304                                               ObjectType,
4305                                               FirstQualifierInScope,
4306                                               AllowInjectedClassName);
4307     }
4308 
4309     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4310                                             DTN->getOperator(), NameLoc,
4311                                             ObjectType, AllowInjectedClassName);
4312   }
4313 
4314   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4315     TemplateDecl *TransTemplate
4316       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4317                                                               Template));
4318     if (!TransTemplate)
4319       return TemplateName();
4320 
4321     if (!getDerived().AlwaysRebuild() &&
4322         TransTemplate == Template)
4323       return Name;
4324 
4325     return TemplateName(TransTemplate);
4326   }
4327 
4328   if (SubstTemplateTemplateParmPackStorage *SubstPack
4329       = Name.getAsSubstTemplateTemplateParmPack()) {
4330     TemplateTemplateParmDecl *TransParam
4331     = cast_or_null<TemplateTemplateParmDecl>(
4332             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
4333     if (!TransParam)
4334       return TemplateName();
4335 
4336     if (!getDerived().AlwaysRebuild() &&
4337         TransParam == SubstPack->getParameterPack())
4338       return Name;
4339 
4340     return getDerived().RebuildTemplateName(TransParam,
4341                                             SubstPack->getArgumentPack());
4342   }
4343 
4344   // These should be getting filtered out before they reach the AST.
4345   llvm_unreachable("overloaded function decl survived to here");
4346 }
4347 
4348 template<typename Derived>
4349 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4350                                          const TemplateArgument &Arg,
4351                                          TemplateArgumentLoc &Output) {
4352   Output = getSema().getTrivialTemplateArgumentLoc(
4353       Arg, QualType(), getDerived().getBaseLocation());
4354 }
4355 
4356 template <typename Derived>
4357 bool TreeTransform<Derived>::TransformTemplateArgument(
4358     const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4359     bool Uneval) {
4360   const TemplateArgument &Arg = Input.getArgument();
4361   switch (Arg.getKind()) {
4362   case TemplateArgument::Null:
4363   case TemplateArgument::Pack:
4364     llvm_unreachable("Unexpected TemplateArgument");
4365 
4366   case TemplateArgument::Integral:
4367   case TemplateArgument::NullPtr:
4368   case TemplateArgument::Declaration: {
4369     // Transform a resolved template argument straight to a resolved template
4370     // argument. We get here when substituting into an already-substituted
4371     // template type argument during concept satisfaction checking.
4372     QualType T = Arg.getNonTypeTemplateArgumentType();
4373     QualType NewT = getDerived().TransformType(T);
4374     if (NewT.isNull())
4375       return true;
4376 
4377     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4378                        ? Arg.getAsDecl()
4379                        : nullptr;
4380     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4381                               getDerived().getBaseLocation(), D))
4382                         : nullptr;
4383     if (D && !NewD)
4384       return true;
4385 
4386     if (NewT == T && D == NewD)
4387       Output = Input;
4388     else if (Arg.getKind() == TemplateArgument::Integral)
4389       Output = TemplateArgumentLoc(
4390           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4391           TemplateArgumentLocInfo());
4392     else if (Arg.getKind() == TemplateArgument::NullPtr)
4393       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4394                                    TemplateArgumentLocInfo());
4395     else
4396       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4397                                    TemplateArgumentLocInfo());
4398 
4399     return false;
4400   }
4401 
4402   case TemplateArgument::Type: {
4403     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4404     if (!DI)
4405       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4406 
4407     DI = getDerived().TransformType(DI);
4408     if (!DI)
4409       return true;
4410 
4411     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4412     return false;
4413   }
4414 
4415   case TemplateArgument::Template: {
4416     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4417     if (QualifierLoc) {
4418       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4419       if (!QualifierLoc)
4420         return true;
4421     }
4422 
4423     CXXScopeSpec SS;
4424     SS.Adopt(QualifierLoc);
4425     TemplateName Template = getDerived().TransformTemplateName(
4426         SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4427     if (Template.isNull())
4428       return true;
4429 
4430     Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4431                                  QualifierLoc, Input.getTemplateNameLoc());
4432     return false;
4433   }
4434 
4435   case TemplateArgument::TemplateExpansion:
4436     llvm_unreachable("Caller should expand pack expansions");
4437 
4438   case TemplateArgument::Expression: {
4439     // Template argument expressions are constant expressions.
4440     EnterExpressionEvaluationContext Unevaluated(
4441         getSema(),
4442         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4443                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4444         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4445         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4446 
4447     Expr *InputExpr = Input.getSourceExpression();
4448     if (!InputExpr)
4449       InputExpr = Input.getArgument().getAsExpr();
4450 
4451     ExprResult E = getDerived().TransformExpr(InputExpr);
4452     E = SemaRef.ActOnConstantExpression(E);
4453     if (E.isInvalid())
4454       return true;
4455     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4456     return false;
4457   }
4458   }
4459 
4460   // Work around bogus GCC warning
4461   return true;
4462 }
4463 
4464 /// Iterator adaptor that invents template argument location information
4465 /// for each of the template arguments in its underlying iterator.
4466 template<typename Derived, typename InputIterator>
4467 class TemplateArgumentLocInventIterator {
4468   TreeTransform<Derived> &Self;
4469   InputIterator Iter;
4470 
4471 public:
4472   typedef TemplateArgumentLoc value_type;
4473   typedef TemplateArgumentLoc reference;
4474   typedef typename std::iterator_traits<InputIterator>::difference_type
4475     difference_type;
4476   typedef std::input_iterator_tag iterator_category;
4477 
4478   class pointer {
4479     TemplateArgumentLoc Arg;
4480 
4481   public:
4482     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4483 
4484     const TemplateArgumentLoc *operator->() const { return &Arg; }
4485   };
4486 
4487   TemplateArgumentLocInventIterator() { }
4488 
4489   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4490                                              InputIterator Iter)
4491     : Self(Self), Iter(Iter) { }
4492 
4493   TemplateArgumentLocInventIterator &operator++() {
4494     ++Iter;
4495     return *this;
4496   }
4497 
4498   TemplateArgumentLocInventIterator operator++(int) {
4499     TemplateArgumentLocInventIterator Old(*this);
4500     ++(*this);
4501     return Old;
4502   }
4503 
4504   reference operator*() const {
4505     TemplateArgumentLoc Result;
4506     Self.InventTemplateArgumentLoc(*Iter, Result);
4507     return Result;
4508   }
4509 
4510   pointer operator->() const { return pointer(**this); }
4511 
4512   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4513                          const TemplateArgumentLocInventIterator &Y) {
4514     return X.Iter == Y.Iter;
4515   }
4516 
4517   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4518                          const TemplateArgumentLocInventIterator &Y) {
4519     return X.Iter != Y.Iter;
4520   }
4521 };
4522 
4523 template<typename Derived>
4524 template<typename InputIterator>
4525 bool TreeTransform<Derived>::TransformTemplateArguments(
4526     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4527     bool Uneval) {
4528   for (; First != Last; ++First) {
4529     TemplateArgumentLoc Out;
4530     TemplateArgumentLoc In = *First;
4531 
4532     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4533       // Unpack argument packs, which we translate them into separate
4534       // arguments.
4535       // FIXME: We could do much better if we could guarantee that the
4536       // TemplateArgumentLocInfo for the pack expansion would be usable for
4537       // all of the template arguments in the argument pack.
4538       typedef TemplateArgumentLocInventIterator<Derived,
4539                                                 TemplateArgument::pack_iterator>
4540         PackLocIterator;
4541       if (TransformTemplateArguments(PackLocIterator(*this,
4542                                                  In.getArgument().pack_begin()),
4543                                      PackLocIterator(*this,
4544                                                    In.getArgument().pack_end()),
4545                                      Outputs, Uneval))
4546         return true;
4547 
4548       continue;
4549     }
4550 
4551     if (In.getArgument().isPackExpansion()) {
4552       // We have a pack expansion, for which we will be substituting into
4553       // the pattern.
4554       SourceLocation Ellipsis;
4555       Optional<unsigned> OrigNumExpansions;
4556       TemplateArgumentLoc Pattern
4557         = getSema().getTemplateArgumentPackExpansionPattern(
4558               In, Ellipsis, OrigNumExpansions);
4559 
4560       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4561       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4562       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4563 
4564       // Determine whether the set of unexpanded parameter packs can and should
4565       // be expanded.
4566       bool Expand = true;
4567       bool RetainExpansion = false;
4568       Optional<unsigned> NumExpansions = OrigNumExpansions;
4569       if (getDerived().TryExpandParameterPacks(Ellipsis,
4570                                                Pattern.getSourceRange(),
4571                                                Unexpanded,
4572                                                Expand,
4573                                                RetainExpansion,
4574                                                NumExpansions))
4575         return true;
4576 
4577       if (!Expand) {
4578         // The transform has determined that we should perform a simple
4579         // transformation on the pack expansion, producing another pack
4580         // expansion.
4581         TemplateArgumentLoc OutPattern;
4582         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4583         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4584           return true;
4585 
4586         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4587                                                 NumExpansions);
4588         if (Out.getArgument().isNull())
4589           return true;
4590 
4591         Outputs.addArgument(Out);
4592         continue;
4593       }
4594 
4595       // The transform has determined that we should perform an elementwise
4596       // expansion of the pattern. Do so.
4597       for (unsigned I = 0; I != *NumExpansions; ++I) {
4598         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4599 
4600         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4601           return true;
4602 
4603         if (Out.getArgument().containsUnexpandedParameterPack()) {
4604           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4605                                                   OrigNumExpansions);
4606           if (Out.getArgument().isNull())
4607             return true;
4608         }
4609 
4610         Outputs.addArgument(Out);
4611       }
4612 
4613       // If we're supposed to retain a pack expansion, do so by temporarily
4614       // forgetting the partially-substituted parameter pack.
4615       if (RetainExpansion) {
4616         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4617 
4618         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4619           return true;
4620 
4621         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4622                                                 OrigNumExpansions);
4623         if (Out.getArgument().isNull())
4624           return true;
4625 
4626         Outputs.addArgument(Out);
4627       }
4628 
4629       continue;
4630     }
4631 
4632     // The simple case:
4633     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4634       return true;
4635 
4636     Outputs.addArgument(Out);
4637   }
4638 
4639   return false;
4640 
4641 }
4642 
4643 //===----------------------------------------------------------------------===//
4644 // Type transformation
4645 //===----------------------------------------------------------------------===//
4646 
4647 template<typename Derived>
4648 QualType TreeTransform<Derived>::TransformType(QualType T) {
4649   if (getDerived().AlreadyTransformed(T))
4650     return T;
4651 
4652   // Temporary workaround.  All of these transformations should
4653   // eventually turn into transformations on TypeLocs.
4654   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4655                                                 getDerived().getBaseLocation());
4656 
4657   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4658 
4659   if (!NewDI)
4660     return QualType();
4661 
4662   return NewDI->getType();
4663 }
4664 
4665 template<typename Derived>
4666 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4667   // Refine the base location to the type's location.
4668   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4669                        getDerived().getBaseEntity());
4670   if (getDerived().AlreadyTransformed(DI->getType()))
4671     return DI;
4672 
4673   TypeLocBuilder TLB;
4674 
4675   TypeLoc TL = DI->getTypeLoc();
4676   TLB.reserve(TL.getFullDataSize());
4677 
4678   QualType Result = getDerived().TransformType(TLB, TL);
4679   if (Result.isNull())
4680     return nullptr;
4681 
4682   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4683 }
4684 
4685 template<typename Derived>
4686 QualType
4687 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4688   switch (T.getTypeLocClass()) {
4689 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4690 #define TYPELOC(CLASS, PARENT)                                                 \
4691   case TypeLoc::CLASS:                                                         \
4692     return getDerived().Transform##CLASS##Type(TLB,                            \
4693                                                T.castAs<CLASS##TypeLoc>());
4694 #include "clang/AST/TypeLocNodes.def"
4695   }
4696 
4697   llvm_unreachable("unhandled type loc!");
4698 }
4699 
4700 template<typename Derived>
4701 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4702   if (!isa<DependentNameType>(T))
4703     return TransformType(T);
4704 
4705   if (getDerived().AlreadyTransformed(T))
4706     return T;
4707   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4708                                                 getDerived().getBaseLocation());
4709   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4710   return NewDI ? NewDI->getType() : QualType();
4711 }
4712 
4713 template<typename Derived>
4714 TypeSourceInfo *
4715 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4716   if (!isa<DependentNameType>(DI->getType()))
4717     return TransformType(DI);
4718 
4719   // Refine the base location to the type's location.
4720   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4721                        getDerived().getBaseEntity());
4722   if (getDerived().AlreadyTransformed(DI->getType()))
4723     return DI;
4724 
4725   TypeLocBuilder TLB;
4726 
4727   TypeLoc TL = DI->getTypeLoc();
4728   TLB.reserve(TL.getFullDataSize());
4729 
4730   auto QTL = TL.getAs<QualifiedTypeLoc>();
4731   if (QTL)
4732     TL = QTL.getUnqualifiedLoc();
4733 
4734   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4735 
4736   QualType Result = getDerived().TransformDependentNameType(
4737       TLB, DNTL, /*DeducedTSTContext*/true);
4738   if (Result.isNull())
4739     return nullptr;
4740 
4741   if (QTL) {
4742     Result = getDerived().RebuildQualifiedType(Result, QTL);
4743     if (Result.isNull())
4744       return nullptr;
4745     TLB.TypeWasModifiedSafely(Result);
4746   }
4747 
4748   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4749 }
4750 
4751 template<typename Derived>
4752 QualType
4753 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4754                                                QualifiedTypeLoc T) {
4755   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4756   if (Result.isNull())
4757     return QualType();
4758 
4759   Result = getDerived().RebuildQualifiedType(Result, T);
4760 
4761   if (Result.isNull())
4762     return QualType();
4763 
4764   // RebuildQualifiedType might have updated the type, but not in a way
4765   // that invalidates the TypeLoc. (There's no location information for
4766   // qualifiers.)
4767   TLB.TypeWasModifiedSafely(Result);
4768 
4769   return Result;
4770 }
4771 
4772 template <typename Derived>
4773 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4774                                                       QualifiedTypeLoc TL) {
4775 
4776   SourceLocation Loc = TL.getBeginLoc();
4777   Qualifiers Quals = TL.getType().getLocalQualifiers();
4778 
4779   if ((T.getAddressSpace() != LangAS::Default &&
4780        Quals.getAddressSpace() != LangAS::Default) &&
4781       T.getAddressSpace() != Quals.getAddressSpace()) {
4782     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4783         << TL.getType() << T;
4784     return QualType();
4785   }
4786 
4787   // C++ [dcl.fct]p7:
4788   //   [When] adding cv-qualifications on top of the function type [...] the
4789   //   cv-qualifiers are ignored.
4790   if (T->isFunctionType()) {
4791     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4792                                                      Quals.getAddressSpace());
4793     return T;
4794   }
4795 
4796   // C++ [dcl.ref]p1:
4797   //   when the cv-qualifiers are introduced through the use of a typedef-name
4798   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4799   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4800   // applied to a reference type.
4801   if (T->isReferenceType()) {
4802     // The only qualifier that applies to a reference type is restrict.
4803     if (!Quals.hasRestrict())
4804       return T;
4805     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4806   }
4807 
4808   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4809   // resulting type.
4810   if (Quals.hasObjCLifetime()) {
4811     if (!T->isObjCLifetimeType() && !T->isDependentType())
4812       Quals.removeObjCLifetime();
4813     else if (T.getObjCLifetime()) {
4814       // Objective-C ARC:
4815       //   A lifetime qualifier applied to a substituted template parameter
4816       //   overrides the lifetime qualifier from the template argument.
4817       const AutoType *AutoTy;
4818       if (const SubstTemplateTypeParmType *SubstTypeParam
4819                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4820         QualType Replacement = SubstTypeParam->getReplacementType();
4821         Qualifiers Qs = Replacement.getQualifiers();
4822         Qs.removeObjCLifetime();
4823         Replacement = SemaRef.Context.getQualifiedType(
4824             Replacement.getUnqualifiedType(), Qs);
4825         T = SemaRef.Context.getSubstTemplateTypeParmType(
4826             SubstTypeParam->getReplacedParameter(), Replacement);
4827       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4828         // 'auto' types behave the same way as template parameters.
4829         QualType Deduced = AutoTy->getDeducedType();
4830         Qualifiers Qs = Deduced.getQualifiers();
4831         Qs.removeObjCLifetime();
4832         Deduced =
4833             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4834         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4835                                         AutoTy->isDependentType(),
4836                                         /*isPack=*/false,
4837                                         AutoTy->getTypeConstraintConcept(),
4838                                         AutoTy->getTypeConstraintArguments());
4839       } else {
4840         // Otherwise, complain about the addition of a qualifier to an
4841         // already-qualified type.
4842         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4843         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4844         Quals.removeObjCLifetime();
4845       }
4846     }
4847   }
4848 
4849   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4850 }
4851 
4852 template<typename Derived>
4853 TypeLoc
4854 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4855                                                    QualType ObjectType,
4856                                                    NamedDecl *UnqualLookup,
4857                                                    CXXScopeSpec &SS) {
4858   if (getDerived().AlreadyTransformed(TL.getType()))
4859     return TL;
4860 
4861   TypeSourceInfo *TSI =
4862       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4863   if (TSI)
4864     return TSI->getTypeLoc();
4865   return TypeLoc();
4866 }
4867 
4868 template<typename Derived>
4869 TypeSourceInfo *
4870 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4871                                                    QualType ObjectType,
4872                                                    NamedDecl *UnqualLookup,
4873                                                    CXXScopeSpec &SS) {
4874   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4875     return TSInfo;
4876 
4877   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4878                                    UnqualLookup, SS);
4879 }
4880 
4881 template <typename Derived>
4882 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4883     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4884     CXXScopeSpec &SS) {
4885   QualType T = TL.getType();
4886   assert(!getDerived().AlreadyTransformed(T));
4887 
4888   TypeLocBuilder TLB;
4889   QualType Result;
4890 
4891   if (isa<TemplateSpecializationType>(T)) {
4892     TemplateSpecializationTypeLoc SpecTL =
4893         TL.castAs<TemplateSpecializationTypeLoc>();
4894 
4895     TemplateName Template = getDerived().TransformTemplateName(
4896         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4897         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4898     if (Template.isNull())
4899       return nullptr;
4900 
4901     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4902                                                               Template);
4903   } else if (isa<DependentTemplateSpecializationType>(T)) {
4904     DependentTemplateSpecializationTypeLoc SpecTL =
4905         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4906 
4907     TemplateName Template
4908       = getDerived().RebuildTemplateName(SS,
4909                                          SpecTL.getTemplateKeywordLoc(),
4910                                          *SpecTL.getTypePtr()->getIdentifier(),
4911                                          SpecTL.getTemplateNameLoc(),
4912                                          ObjectType, UnqualLookup,
4913                                          /*AllowInjectedClassName*/true);
4914     if (Template.isNull())
4915       return nullptr;
4916 
4917     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4918                                                                        SpecTL,
4919                                                                        Template,
4920                                                                        SS);
4921   } else {
4922     // Nothing special needs to be done for these.
4923     Result = getDerived().TransformType(TLB, TL);
4924   }
4925 
4926   if (Result.isNull())
4927     return nullptr;
4928 
4929   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4930 }
4931 
4932 template <class TyLoc> static inline
4933 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4934   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4935   NewT.setNameLoc(T.getNameLoc());
4936   return T.getType();
4937 }
4938 
4939 template<typename Derived>
4940 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4941                                                       BuiltinTypeLoc T) {
4942   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4943   NewT.setBuiltinLoc(T.getBuiltinLoc());
4944   if (T.needsExtraLocalData())
4945     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4946   return T.getType();
4947 }
4948 
4949 template<typename Derived>
4950 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4951                                                       ComplexTypeLoc T) {
4952   // FIXME: recurse?
4953   return TransformTypeSpecType(TLB, T);
4954 }
4955 
4956 template <typename Derived>
4957 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4958                                                        AdjustedTypeLoc TL) {
4959   // Adjustments applied during transformation are handled elsewhere.
4960   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4961 }
4962 
4963 template<typename Derived>
4964 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4965                                                       DecayedTypeLoc TL) {
4966   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4967   if (OriginalType.isNull())
4968     return QualType();
4969 
4970   QualType Result = TL.getType();
4971   if (getDerived().AlwaysRebuild() ||
4972       OriginalType != TL.getOriginalLoc().getType())
4973     Result = SemaRef.Context.getDecayedType(OriginalType);
4974   TLB.push<DecayedTypeLoc>(Result);
4975   // Nothing to set for DecayedTypeLoc.
4976   return Result;
4977 }
4978 
4979 template<typename Derived>
4980 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4981                                                       PointerTypeLoc TL) {
4982   QualType PointeeType
4983     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4984   if (PointeeType.isNull())
4985     return QualType();
4986 
4987   QualType Result = TL.getType();
4988   if (PointeeType->getAs<ObjCObjectType>()) {
4989     // A dependent pointer type 'T *' has is being transformed such
4990     // that an Objective-C class type is being replaced for 'T'. The
4991     // resulting pointer type is an ObjCObjectPointerType, not a
4992     // PointerType.
4993     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4994 
4995     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4996     NewT.setStarLoc(TL.getStarLoc());
4997     return Result;
4998   }
4999 
5000   if (getDerived().AlwaysRebuild() ||
5001       PointeeType != TL.getPointeeLoc().getType()) {
5002     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5003     if (Result.isNull())
5004       return QualType();
5005   }
5006 
5007   // Objective-C ARC can add lifetime qualifiers to the type that we're
5008   // pointing to.
5009   TLB.TypeWasModifiedSafely(Result->getPointeeType());
5010 
5011   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5012   NewT.setSigilLoc(TL.getSigilLoc());
5013   return Result;
5014 }
5015 
5016 template<typename Derived>
5017 QualType
5018 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5019                                                   BlockPointerTypeLoc TL) {
5020   QualType PointeeType
5021     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5022   if (PointeeType.isNull())
5023     return QualType();
5024 
5025   QualType Result = TL.getType();
5026   if (getDerived().AlwaysRebuild() ||
5027       PointeeType != TL.getPointeeLoc().getType()) {
5028     Result = getDerived().RebuildBlockPointerType(PointeeType,
5029                                                   TL.getSigilLoc());
5030     if (Result.isNull())
5031       return QualType();
5032   }
5033 
5034   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5035   NewT.setSigilLoc(TL.getSigilLoc());
5036   return Result;
5037 }
5038 
5039 /// Transforms a reference type.  Note that somewhat paradoxically we
5040 /// don't care whether the type itself is an l-value type or an r-value
5041 /// type;  we only care if the type was *written* as an l-value type
5042 /// or an r-value type.
5043 template<typename Derived>
5044 QualType
5045 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5046                                                ReferenceTypeLoc TL) {
5047   const ReferenceType *T = TL.getTypePtr();
5048 
5049   // Note that this works with the pointee-as-written.
5050   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5051   if (PointeeType.isNull())
5052     return QualType();
5053 
5054   QualType Result = TL.getType();
5055   if (getDerived().AlwaysRebuild() ||
5056       PointeeType != T->getPointeeTypeAsWritten()) {
5057     Result = getDerived().RebuildReferenceType(PointeeType,
5058                                                T->isSpelledAsLValue(),
5059                                                TL.getSigilLoc());
5060     if (Result.isNull())
5061       return QualType();
5062   }
5063 
5064   // Objective-C ARC can add lifetime qualifiers to the type that we're
5065   // referring to.
5066   TLB.TypeWasModifiedSafely(
5067       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5068 
5069   // r-value references can be rebuilt as l-value references.
5070   ReferenceTypeLoc NewTL;
5071   if (isa<LValueReferenceType>(Result))
5072     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5073   else
5074     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5075   NewTL.setSigilLoc(TL.getSigilLoc());
5076 
5077   return Result;
5078 }
5079 
5080 template<typename Derived>
5081 QualType
5082 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5083                                                  LValueReferenceTypeLoc TL) {
5084   return TransformReferenceType(TLB, TL);
5085 }
5086 
5087 template<typename Derived>
5088 QualType
5089 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5090                                                  RValueReferenceTypeLoc TL) {
5091   return TransformReferenceType(TLB, TL);
5092 }
5093 
5094 template<typename Derived>
5095 QualType
5096 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5097                                                    MemberPointerTypeLoc TL) {
5098   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5099   if (PointeeType.isNull())
5100     return QualType();
5101 
5102   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5103   TypeSourceInfo *NewClsTInfo = nullptr;
5104   if (OldClsTInfo) {
5105     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5106     if (!NewClsTInfo)
5107       return QualType();
5108   }
5109 
5110   const MemberPointerType *T = TL.getTypePtr();
5111   QualType OldClsType = QualType(T->getClass(), 0);
5112   QualType NewClsType;
5113   if (NewClsTInfo)
5114     NewClsType = NewClsTInfo->getType();
5115   else {
5116     NewClsType = getDerived().TransformType(OldClsType);
5117     if (NewClsType.isNull())
5118       return QualType();
5119   }
5120 
5121   QualType Result = TL.getType();
5122   if (getDerived().AlwaysRebuild() ||
5123       PointeeType != T->getPointeeType() ||
5124       NewClsType != OldClsType) {
5125     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5126                                                    TL.getStarLoc());
5127     if (Result.isNull())
5128       return QualType();
5129   }
5130 
5131   // If we had to adjust the pointee type when building a member pointer, make
5132   // sure to push TypeLoc info for it.
5133   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5134   if (MPT && PointeeType != MPT->getPointeeType()) {
5135     assert(isa<AdjustedType>(MPT->getPointeeType()));
5136     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5137   }
5138 
5139   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5140   NewTL.setSigilLoc(TL.getSigilLoc());
5141   NewTL.setClassTInfo(NewClsTInfo);
5142 
5143   return Result;
5144 }
5145 
5146 template<typename Derived>
5147 QualType
5148 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5149                                                    ConstantArrayTypeLoc TL) {
5150   const ConstantArrayType *T = TL.getTypePtr();
5151   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5152   if (ElementType.isNull())
5153     return QualType();
5154 
5155   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5156   Expr *OldSize = TL.getSizeExpr();
5157   if (!OldSize)
5158     OldSize = const_cast<Expr*>(T->getSizeExpr());
5159   Expr *NewSize = nullptr;
5160   if (OldSize) {
5161     EnterExpressionEvaluationContext Unevaluated(
5162         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5163     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5164     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5165   }
5166 
5167   QualType Result = TL.getType();
5168   if (getDerived().AlwaysRebuild() ||
5169       ElementType != T->getElementType() ||
5170       (T->getSizeExpr() && NewSize != OldSize)) {
5171     Result = getDerived().RebuildConstantArrayType(ElementType,
5172                                                    T->getSizeModifier(),
5173                                                    T->getSize(), NewSize,
5174                                              T->getIndexTypeCVRQualifiers(),
5175                                                    TL.getBracketsRange());
5176     if (Result.isNull())
5177       return QualType();
5178   }
5179 
5180   // We might have either a ConstantArrayType or a VariableArrayType now:
5181   // a ConstantArrayType is allowed to have an element type which is a
5182   // VariableArrayType if the type is dependent.  Fortunately, all array
5183   // types have the same location layout.
5184   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5185   NewTL.setLBracketLoc(TL.getLBracketLoc());
5186   NewTL.setRBracketLoc(TL.getRBracketLoc());
5187   NewTL.setSizeExpr(NewSize);
5188 
5189   return Result;
5190 }
5191 
5192 template<typename Derived>
5193 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5194                                               TypeLocBuilder &TLB,
5195                                               IncompleteArrayTypeLoc TL) {
5196   const IncompleteArrayType *T = TL.getTypePtr();
5197   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5198   if (ElementType.isNull())
5199     return QualType();
5200 
5201   QualType Result = TL.getType();
5202   if (getDerived().AlwaysRebuild() ||
5203       ElementType != T->getElementType()) {
5204     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5205                                                      T->getSizeModifier(),
5206                                            T->getIndexTypeCVRQualifiers(),
5207                                                      TL.getBracketsRange());
5208     if (Result.isNull())
5209       return QualType();
5210   }
5211 
5212   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5213   NewTL.setLBracketLoc(TL.getLBracketLoc());
5214   NewTL.setRBracketLoc(TL.getRBracketLoc());
5215   NewTL.setSizeExpr(nullptr);
5216 
5217   return Result;
5218 }
5219 
5220 template<typename Derived>
5221 QualType
5222 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5223                                                    VariableArrayTypeLoc TL) {
5224   const VariableArrayType *T = TL.getTypePtr();
5225   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5226   if (ElementType.isNull())
5227     return QualType();
5228 
5229   ExprResult SizeResult;
5230   {
5231     EnterExpressionEvaluationContext Context(
5232         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5233     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5234   }
5235   if (SizeResult.isInvalid())
5236     return QualType();
5237   SizeResult =
5238       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5239   if (SizeResult.isInvalid())
5240     return QualType();
5241 
5242   Expr *Size = SizeResult.get();
5243 
5244   QualType Result = TL.getType();
5245   if (getDerived().AlwaysRebuild() ||
5246       ElementType != T->getElementType() ||
5247       Size != T->getSizeExpr()) {
5248     Result = getDerived().RebuildVariableArrayType(ElementType,
5249                                                    T->getSizeModifier(),
5250                                                    Size,
5251                                              T->getIndexTypeCVRQualifiers(),
5252                                                    TL.getBracketsRange());
5253     if (Result.isNull())
5254       return QualType();
5255   }
5256 
5257   // We might have constant size array now, but fortunately it has the same
5258   // location layout.
5259   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5260   NewTL.setLBracketLoc(TL.getLBracketLoc());
5261   NewTL.setRBracketLoc(TL.getRBracketLoc());
5262   NewTL.setSizeExpr(Size);
5263 
5264   return Result;
5265 }
5266 
5267 template<typename Derived>
5268 QualType
5269 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5270                                              DependentSizedArrayTypeLoc TL) {
5271   const DependentSizedArrayType *T = TL.getTypePtr();
5272   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5273   if (ElementType.isNull())
5274     return QualType();
5275 
5276   // Array bounds are constant expressions.
5277   EnterExpressionEvaluationContext Unevaluated(
5278       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5279 
5280   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5281   Expr *origSize = TL.getSizeExpr();
5282   if (!origSize) origSize = T->getSizeExpr();
5283 
5284   ExprResult sizeResult
5285     = getDerived().TransformExpr(origSize);
5286   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5287   if (sizeResult.isInvalid())
5288     return QualType();
5289 
5290   Expr *size = sizeResult.get();
5291 
5292   QualType Result = TL.getType();
5293   if (getDerived().AlwaysRebuild() ||
5294       ElementType != T->getElementType() ||
5295       size != origSize) {
5296     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5297                                                          T->getSizeModifier(),
5298                                                          size,
5299                                                 T->getIndexTypeCVRQualifiers(),
5300                                                         TL.getBracketsRange());
5301     if (Result.isNull())
5302       return QualType();
5303   }
5304 
5305   // We might have any sort of array type now, but fortunately they
5306   // all have the same location layout.
5307   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5308   NewTL.setLBracketLoc(TL.getLBracketLoc());
5309   NewTL.setRBracketLoc(TL.getRBracketLoc());
5310   NewTL.setSizeExpr(size);
5311 
5312   return Result;
5313 }
5314 
5315 template <typename Derived>
5316 QualType TreeTransform<Derived>::TransformDependentVectorType(
5317     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5318   const DependentVectorType *T = TL.getTypePtr();
5319   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5320   if (ElementType.isNull())
5321     return QualType();
5322 
5323   EnterExpressionEvaluationContext Unevaluated(
5324       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5325 
5326   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5327   Size = SemaRef.ActOnConstantExpression(Size);
5328   if (Size.isInvalid())
5329     return QualType();
5330 
5331   QualType Result = TL.getType();
5332   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5333       Size.get() != T->getSizeExpr()) {
5334     Result = getDerived().RebuildDependentVectorType(
5335         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5336     if (Result.isNull())
5337       return QualType();
5338   }
5339 
5340   // Result might be dependent or not.
5341   if (isa<DependentVectorType>(Result)) {
5342     DependentVectorTypeLoc NewTL =
5343         TLB.push<DependentVectorTypeLoc>(Result);
5344     NewTL.setNameLoc(TL.getNameLoc());
5345   } else {
5346     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5347     NewTL.setNameLoc(TL.getNameLoc());
5348   }
5349 
5350   return Result;
5351 }
5352 
5353 template<typename Derived>
5354 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5355                                       TypeLocBuilder &TLB,
5356                                       DependentSizedExtVectorTypeLoc TL) {
5357   const DependentSizedExtVectorType *T = TL.getTypePtr();
5358 
5359   // FIXME: ext vector locs should be nested
5360   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5361   if (ElementType.isNull())
5362     return QualType();
5363 
5364   // Vector sizes are constant expressions.
5365   EnterExpressionEvaluationContext Unevaluated(
5366       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5367 
5368   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5369   Size = SemaRef.ActOnConstantExpression(Size);
5370   if (Size.isInvalid())
5371     return QualType();
5372 
5373   QualType Result = TL.getType();
5374   if (getDerived().AlwaysRebuild() ||
5375       ElementType != T->getElementType() ||
5376       Size.get() != T->getSizeExpr()) {
5377     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5378                                                              Size.get(),
5379                                                          T->getAttributeLoc());
5380     if (Result.isNull())
5381       return QualType();
5382   }
5383 
5384   // Result might be dependent or not.
5385   if (isa<DependentSizedExtVectorType>(Result)) {
5386     DependentSizedExtVectorTypeLoc NewTL
5387       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5388     NewTL.setNameLoc(TL.getNameLoc());
5389   } else {
5390     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5391     NewTL.setNameLoc(TL.getNameLoc());
5392   }
5393 
5394   return Result;
5395 }
5396 
5397 template <typename Derived>
5398 QualType
5399 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5400                                                     ConstantMatrixTypeLoc TL) {
5401   const ConstantMatrixType *T = TL.getTypePtr();
5402   QualType ElementType = getDerived().TransformType(T->getElementType());
5403   if (ElementType.isNull())
5404     return QualType();
5405 
5406   QualType Result = TL.getType();
5407   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5408     Result = getDerived().RebuildConstantMatrixType(
5409         ElementType, T->getNumRows(), T->getNumColumns());
5410     if (Result.isNull())
5411       return QualType();
5412   }
5413 
5414   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5415   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5416   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5417   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5418   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5419 
5420   return Result;
5421 }
5422 
5423 template <typename Derived>
5424 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5425     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5426   const DependentSizedMatrixType *T = TL.getTypePtr();
5427 
5428   QualType ElementType = getDerived().TransformType(T->getElementType());
5429   if (ElementType.isNull()) {
5430     return QualType();
5431   }
5432 
5433   // Matrix dimensions are constant expressions.
5434   EnterExpressionEvaluationContext Unevaluated(
5435       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5436 
5437   Expr *origRows = TL.getAttrRowOperand();
5438   if (!origRows)
5439     origRows = T->getRowExpr();
5440   Expr *origColumns = TL.getAttrColumnOperand();
5441   if (!origColumns)
5442     origColumns = T->getColumnExpr();
5443 
5444   ExprResult rowResult = getDerived().TransformExpr(origRows);
5445   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5446   if (rowResult.isInvalid())
5447     return QualType();
5448 
5449   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5450   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5451   if (columnResult.isInvalid())
5452     return QualType();
5453 
5454   Expr *rows = rowResult.get();
5455   Expr *columns = columnResult.get();
5456 
5457   QualType Result = TL.getType();
5458   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5459       rows != origRows || columns != origColumns) {
5460     Result = getDerived().RebuildDependentSizedMatrixType(
5461         ElementType, rows, columns, T->getAttributeLoc());
5462 
5463     if (Result.isNull())
5464       return QualType();
5465   }
5466 
5467   // We might have any sort of matrix type now, but fortunately they
5468   // all have the same location layout.
5469   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5470   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5471   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5472   NewTL.setAttrRowOperand(rows);
5473   NewTL.setAttrColumnOperand(columns);
5474   return Result;
5475 }
5476 
5477 template <typename Derived>
5478 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5479     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5480   const DependentAddressSpaceType *T = TL.getTypePtr();
5481 
5482   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5483 
5484   if (pointeeType.isNull())
5485     return QualType();
5486 
5487   // Address spaces are constant expressions.
5488   EnterExpressionEvaluationContext Unevaluated(
5489       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5490 
5491   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5492   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5493   if (AddrSpace.isInvalid())
5494     return QualType();
5495 
5496   QualType Result = TL.getType();
5497   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5498       AddrSpace.get() != T->getAddrSpaceExpr()) {
5499     Result = getDerived().RebuildDependentAddressSpaceType(
5500         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5501     if (Result.isNull())
5502       return QualType();
5503   }
5504 
5505   // Result might be dependent or not.
5506   if (isa<DependentAddressSpaceType>(Result)) {
5507     DependentAddressSpaceTypeLoc NewTL =
5508         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5509 
5510     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5511     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5512     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5513 
5514   } else {
5515     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5516         Result, getDerived().getBaseLocation());
5517     TransformType(TLB, DI->getTypeLoc());
5518   }
5519 
5520   return Result;
5521 }
5522 
5523 template <typename Derived>
5524 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5525                                                      VectorTypeLoc TL) {
5526   const VectorType *T = TL.getTypePtr();
5527   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5528   if (ElementType.isNull())
5529     return QualType();
5530 
5531   QualType Result = TL.getType();
5532   if (getDerived().AlwaysRebuild() ||
5533       ElementType != T->getElementType()) {
5534     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5535                                             T->getVectorKind());
5536     if (Result.isNull())
5537       return QualType();
5538   }
5539 
5540   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5541   NewTL.setNameLoc(TL.getNameLoc());
5542 
5543   return Result;
5544 }
5545 
5546 template<typename Derived>
5547 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5548                                                         ExtVectorTypeLoc TL) {
5549   const VectorType *T = TL.getTypePtr();
5550   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5551   if (ElementType.isNull())
5552     return QualType();
5553 
5554   QualType Result = TL.getType();
5555   if (getDerived().AlwaysRebuild() ||
5556       ElementType != T->getElementType()) {
5557     Result = getDerived().RebuildExtVectorType(ElementType,
5558                                                T->getNumElements(),
5559                                                /*FIXME*/ SourceLocation());
5560     if (Result.isNull())
5561       return QualType();
5562   }
5563 
5564   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5565   NewTL.setNameLoc(TL.getNameLoc());
5566 
5567   return Result;
5568 }
5569 
5570 template <typename Derived>
5571 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5572     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5573     bool ExpectParameterPack) {
5574   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5575   TypeSourceInfo *NewDI = nullptr;
5576 
5577   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5578     // If we're substituting into a pack expansion type and we know the
5579     // length we want to expand to, just substitute for the pattern.
5580     TypeLoc OldTL = OldDI->getTypeLoc();
5581     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5582 
5583     TypeLocBuilder TLB;
5584     TypeLoc NewTL = OldDI->getTypeLoc();
5585     TLB.reserve(NewTL.getFullDataSize());
5586 
5587     QualType Result = getDerived().TransformType(TLB,
5588                                                OldExpansionTL.getPatternLoc());
5589     if (Result.isNull())
5590       return nullptr;
5591 
5592     Result = RebuildPackExpansionType(Result,
5593                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5594                                       OldExpansionTL.getEllipsisLoc(),
5595                                       NumExpansions);
5596     if (Result.isNull())
5597       return nullptr;
5598 
5599     PackExpansionTypeLoc NewExpansionTL
5600       = TLB.push<PackExpansionTypeLoc>(Result);
5601     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5602     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5603   } else
5604     NewDI = getDerived().TransformType(OldDI);
5605   if (!NewDI)
5606     return nullptr;
5607 
5608   if (NewDI == OldDI && indexAdjustment == 0)
5609     return OldParm;
5610 
5611   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5612                                              OldParm->getDeclContext(),
5613                                              OldParm->getInnerLocStart(),
5614                                              OldParm->getLocation(),
5615                                              OldParm->getIdentifier(),
5616                                              NewDI->getType(),
5617                                              NewDI,
5618                                              OldParm->getStorageClass(),
5619                                              /* DefArg */ nullptr);
5620   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5621                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5622   transformedLocalDecl(OldParm, {newParm});
5623   return newParm;
5624 }
5625 
5626 template <typename Derived>
5627 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5628     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5629     const QualType *ParamTypes,
5630     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5631     SmallVectorImpl<QualType> &OutParamTypes,
5632     SmallVectorImpl<ParmVarDecl *> *PVars,
5633     Sema::ExtParameterInfoBuilder &PInfos) {
5634   int indexAdjustment = 0;
5635 
5636   unsigned NumParams = Params.size();
5637   for (unsigned i = 0; i != NumParams; ++i) {
5638     if (ParmVarDecl *OldParm = Params[i]) {
5639       assert(OldParm->getFunctionScopeIndex() == i);
5640 
5641       Optional<unsigned> NumExpansions;
5642       ParmVarDecl *NewParm = nullptr;
5643       if (OldParm->isParameterPack()) {
5644         // We have a function parameter pack that may need to be expanded.
5645         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5646 
5647         // Find the parameter packs that could be expanded.
5648         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5649         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5650         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5651         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5652 
5653         // Determine whether we should expand the parameter packs.
5654         bool ShouldExpand = false;
5655         bool RetainExpansion = false;
5656         Optional<unsigned> OrigNumExpansions;
5657         if (Unexpanded.size() > 0) {
5658           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5659           NumExpansions = OrigNumExpansions;
5660           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5661                                                    Pattern.getSourceRange(),
5662                                                    Unexpanded,
5663                                                    ShouldExpand,
5664                                                    RetainExpansion,
5665                                                    NumExpansions)) {
5666             return true;
5667           }
5668         } else {
5669 #ifndef NDEBUG
5670           const AutoType *AT =
5671               Pattern.getType().getTypePtr()->getContainedAutoType();
5672           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5673                  "Could not find parameter packs or undeduced auto type!");
5674 #endif
5675         }
5676 
5677         if (ShouldExpand) {
5678           // Expand the function parameter pack into multiple, separate
5679           // parameters.
5680           getDerived().ExpandingFunctionParameterPack(OldParm);
5681           for (unsigned I = 0; I != *NumExpansions; ++I) {
5682             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5683             ParmVarDecl *NewParm
5684               = getDerived().TransformFunctionTypeParam(OldParm,
5685                                                         indexAdjustment++,
5686                                                         OrigNumExpansions,
5687                                                 /*ExpectParameterPack=*/false);
5688             if (!NewParm)
5689               return true;
5690 
5691             if (ParamInfos)
5692               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5693             OutParamTypes.push_back(NewParm->getType());
5694             if (PVars)
5695               PVars->push_back(NewParm);
5696           }
5697 
5698           // If we're supposed to retain a pack expansion, do so by temporarily
5699           // forgetting the partially-substituted parameter pack.
5700           if (RetainExpansion) {
5701             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5702             ParmVarDecl *NewParm
5703               = getDerived().TransformFunctionTypeParam(OldParm,
5704                                                         indexAdjustment++,
5705                                                         OrigNumExpansions,
5706                                                 /*ExpectParameterPack=*/false);
5707             if (!NewParm)
5708               return true;
5709 
5710             if (ParamInfos)
5711               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5712             OutParamTypes.push_back(NewParm->getType());
5713             if (PVars)
5714               PVars->push_back(NewParm);
5715           }
5716 
5717           // The next parameter should have the same adjustment as the
5718           // last thing we pushed, but we post-incremented indexAdjustment
5719           // on every push.  Also, if we push nothing, the adjustment should
5720           // go down by one.
5721           indexAdjustment--;
5722 
5723           // We're done with the pack expansion.
5724           continue;
5725         }
5726 
5727         // We'll substitute the parameter now without expanding the pack
5728         // expansion.
5729         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5730         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5731                                                           indexAdjustment,
5732                                                           NumExpansions,
5733                                                   /*ExpectParameterPack=*/true);
5734         assert(NewParm->isParameterPack() &&
5735                "Parameter pack no longer a parameter pack after "
5736                "transformation.");
5737       } else {
5738         NewParm = getDerived().TransformFunctionTypeParam(
5739             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5740       }
5741 
5742       if (!NewParm)
5743         return true;
5744 
5745       if (ParamInfos)
5746         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5747       OutParamTypes.push_back(NewParm->getType());
5748       if (PVars)
5749         PVars->push_back(NewParm);
5750       continue;
5751     }
5752 
5753     // Deal with the possibility that we don't have a parameter
5754     // declaration for this parameter.
5755     QualType OldType = ParamTypes[i];
5756     bool IsPackExpansion = false;
5757     Optional<unsigned> NumExpansions;
5758     QualType NewType;
5759     if (const PackExpansionType *Expansion
5760                                        = dyn_cast<PackExpansionType>(OldType)) {
5761       // We have a function parameter pack that may need to be expanded.
5762       QualType Pattern = Expansion->getPattern();
5763       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5764       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5765 
5766       // Determine whether we should expand the parameter packs.
5767       bool ShouldExpand = false;
5768       bool RetainExpansion = false;
5769       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5770                                                Unexpanded,
5771                                                ShouldExpand,
5772                                                RetainExpansion,
5773                                                NumExpansions)) {
5774         return true;
5775       }
5776 
5777       if (ShouldExpand) {
5778         // Expand the function parameter pack into multiple, separate
5779         // parameters.
5780         for (unsigned I = 0; I != *NumExpansions; ++I) {
5781           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5782           QualType NewType = getDerived().TransformType(Pattern);
5783           if (NewType.isNull())
5784             return true;
5785 
5786           if (NewType->containsUnexpandedParameterPack()) {
5787             NewType =
5788                 getSema().getASTContext().getPackExpansionType(NewType, None);
5789 
5790             if (NewType.isNull())
5791               return true;
5792           }
5793 
5794           if (ParamInfos)
5795             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5796           OutParamTypes.push_back(NewType);
5797           if (PVars)
5798             PVars->push_back(nullptr);
5799         }
5800 
5801         // We're done with the pack expansion.
5802         continue;
5803       }
5804 
5805       // If we're supposed to retain a pack expansion, do so by temporarily
5806       // forgetting the partially-substituted parameter pack.
5807       if (RetainExpansion) {
5808         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5809         QualType NewType = getDerived().TransformType(Pattern);
5810         if (NewType.isNull())
5811           return true;
5812 
5813         if (ParamInfos)
5814           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5815         OutParamTypes.push_back(NewType);
5816         if (PVars)
5817           PVars->push_back(nullptr);
5818       }
5819 
5820       // We'll substitute the parameter now without expanding the pack
5821       // expansion.
5822       OldType = Expansion->getPattern();
5823       IsPackExpansion = true;
5824       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5825       NewType = getDerived().TransformType(OldType);
5826     } else {
5827       NewType = getDerived().TransformType(OldType);
5828     }
5829 
5830     if (NewType.isNull())
5831       return true;
5832 
5833     if (IsPackExpansion)
5834       NewType = getSema().Context.getPackExpansionType(NewType,
5835                                                        NumExpansions);
5836 
5837     if (ParamInfos)
5838       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5839     OutParamTypes.push_back(NewType);
5840     if (PVars)
5841       PVars->push_back(nullptr);
5842   }
5843 
5844 #ifndef NDEBUG
5845   if (PVars) {
5846     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5847       if (ParmVarDecl *parm = (*PVars)[i])
5848         assert(parm->getFunctionScopeIndex() == i);
5849   }
5850 #endif
5851 
5852   return false;
5853 }
5854 
5855 template<typename Derived>
5856 QualType
5857 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5858                                                    FunctionProtoTypeLoc TL) {
5859   SmallVector<QualType, 4> ExceptionStorage;
5860   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5861   return getDerived().TransformFunctionProtoType(
5862       TLB, TL, nullptr, Qualifiers(),
5863       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5864         return This->getDerived().TransformExceptionSpec(
5865             TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
5866       });
5867 }
5868 
5869 template<typename Derived> template<typename Fn>
5870 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5871     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5872     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5873 
5874   // Transform the parameters and return type.
5875   //
5876   // We are required to instantiate the params and return type in source order.
5877   // When the function has a trailing return type, we instantiate the
5878   // parameters before the return type,  since the return type can then refer
5879   // to the parameters themselves (via decltype, sizeof, etc.).
5880   //
5881   SmallVector<QualType, 4> ParamTypes;
5882   SmallVector<ParmVarDecl*, 4> ParamDecls;
5883   Sema::ExtParameterInfoBuilder ExtParamInfos;
5884   const FunctionProtoType *T = TL.getTypePtr();
5885 
5886   QualType ResultType;
5887 
5888   if (T->hasTrailingReturn()) {
5889     if (getDerived().TransformFunctionTypeParams(
5890             TL.getBeginLoc(), TL.getParams(),
5891             TL.getTypePtr()->param_type_begin(),
5892             T->getExtParameterInfosOrNull(),
5893             ParamTypes, &ParamDecls, ExtParamInfos))
5894       return QualType();
5895 
5896     {
5897       // C++11 [expr.prim.general]p3:
5898       //   If a declaration declares a member function or member function
5899       //   template of a class X, the expression this is a prvalue of type
5900       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5901       //   and the end of the function-definition, member-declarator, or
5902       //   declarator.
5903       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5904 
5905       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5906       if (ResultType.isNull())
5907         return QualType();
5908     }
5909   }
5910   else {
5911     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5912     if (ResultType.isNull())
5913       return QualType();
5914 
5915     if (getDerived().TransformFunctionTypeParams(
5916             TL.getBeginLoc(), TL.getParams(),
5917             TL.getTypePtr()->param_type_begin(),
5918             T->getExtParameterInfosOrNull(),
5919             ParamTypes, &ParamDecls, ExtParamInfos))
5920       return QualType();
5921   }
5922 
5923   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5924 
5925   bool EPIChanged = false;
5926   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5927     return QualType();
5928 
5929   // Handle extended parameter information.
5930   if (auto NewExtParamInfos =
5931         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5932     if (!EPI.ExtParameterInfos ||
5933         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5934           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5935       EPIChanged = true;
5936     }
5937     EPI.ExtParameterInfos = NewExtParamInfos;
5938   } else if (EPI.ExtParameterInfos) {
5939     EPIChanged = true;
5940     EPI.ExtParameterInfos = nullptr;
5941   }
5942 
5943   QualType Result = TL.getType();
5944   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5945       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5946     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5947     if (Result.isNull())
5948       return QualType();
5949   }
5950 
5951   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5952   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5953   NewTL.setLParenLoc(TL.getLParenLoc());
5954   NewTL.setRParenLoc(TL.getRParenLoc());
5955   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5956   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5957   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5958     NewTL.setParam(i, ParamDecls[i]);
5959 
5960   return Result;
5961 }
5962 
5963 template<typename Derived>
5964 bool TreeTransform<Derived>::TransformExceptionSpec(
5965     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5966     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5967   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5968 
5969   // Instantiate a dynamic noexcept expression, if any.
5970   if (isComputedNoexcept(ESI.Type)) {
5971     EnterExpressionEvaluationContext Unevaluated(
5972         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5973     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5974     if (NoexceptExpr.isInvalid())
5975       return true;
5976 
5977     ExceptionSpecificationType EST = ESI.Type;
5978     NoexceptExpr =
5979         getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
5980     if (NoexceptExpr.isInvalid())
5981       return true;
5982 
5983     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5984       Changed = true;
5985     ESI.NoexceptExpr = NoexceptExpr.get();
5986     ESI.Type = EST;
5987   }
5988 
5989   if (ESI.Type != EST_Dynamic)
5990     return false;
5991 
5992   // Instantiate a dynamic exception specification's type.
5993   for (QualType T : ESI.Exceptions) {
5994     if (const PackExpansionType *PackExpansion =
5995             T->getAs<PackExpansionType>()) {
5996       Changed = true;
5997 
5998       // We have a pack expansion. Instantiate it.
5999       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6000       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6001                                               Unexpanded);
6002       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6003 
6004       // Determine whether the set of unexpanded parameter packs can and
6005       // should
6006       // be expanded.
6007       bool Expand = false;
6008       bool RetainExpansion = false;
6009       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6010       // FIXME: Track the location of the ellipsis (and track source location
6011       // information for the types in the exception specification in general).
6012       if (getDerived().TryExpandParameterPacks(
6013               Loc, SourceRange(), Unexpanded, Expand,
6014               RetainExpansion, NumExpansions))
6015         return true;
6016 
6017       if (!Expand) {
6018         // We can't expand this pack expansion into separate arguments yet;
6019         // just substitute into the pattern and create a new pack expansion
6020         // type.
6021         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6022         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6023         if (U.isNull())
6024           return true;
6025 
6026         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6027         Exceptions.push_back(U);
6028         continue;
6029       }
6030 
6031       // Substitute into the pack expansion pattern for each slice of the
6032       // pack.
6033       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6034         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6035 
6036         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6037         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6038           return true;
6039 
6040         Exceptions.push_back(U);
6041       }
6042     } else {
6043       QualType U = getDerived().TransformType(T);
6044       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6045         return true;
6046       if (T != U)
6047         Changed = true;
6048 
6049       Exceptions.push_back(U);
6050     }
6051   }
6052 
6053   ESI.Exceptions = Exceptions;
6054   if (ESI.Exceptions.empty())
6055     ESI.Type = EST_DynamicNone;
6056   return false;
6057 }
6058 
6059 template<typename Derived>
6060 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6061                                                  TypeLocBuilder &TLB,
6062                                                  FunctionNoProtoTypeLoc TL) {
6063   const FunctionNoProtoType *T = TL.getTypePtr();
6064   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6065   if (ResultType.isNull())
6066     return QualType();
6067 
6068   QualType Result = TL.getType();
6069   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6070     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6071 
6072   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6073   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6074   NewTL.setLParenLoc(TL.getLParenLoc());
6075   NewTL.setRParenLoc(TL.getRParenLoc());
6076   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6077 
6078   return Result;
6079 }
6080 
6081 template <typename Derived>
6082 QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6083     TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6084   const UnresolvedUsingType *T = TL.getTypePtr();
6085   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6086   if (!D)
6087     return QualType();
6088 
6089   QualType Result = TL.getType();
6090   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6091     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6092     if (Result.isNull())
6093       return QualType();
6094   }
6095 
6096   // We might get an arbitrary type spec type back.  We should at
6097   // least always get a type spec type, though.
6098   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6099   NewTL.setNameLoc(TL.getNameLoc());
6100 
6101   return Result;
6102 }
6103 
6104 template <typename Derived>
6105 QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6106                                                     UsingTypeLoc TL) {
6107   const UsingType *T = TL.getTypePtr();
6108 
6109   auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6110       TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6111   if (!Found)
6112     return QualType();
6113 
6114   QualType Underlying = getDerived().TransformType(T->desugar());
6115   if (Underlying.isNull())
6116     return QualType();
6117 
6118   QualType Result = TL.getType();
6119   if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6120       Underlying != T->getUnderlyingType()) {
6121     Result = getDerived().RebuildUsingType(Found, Underlying);
6122     if (Result.isNull())
6123       return QualType();
6124   }
6125 
6126   TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6127   return Result;
6128 }
6129 
6130 template<typename Derived>
6131 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6132                                                       TypedefTypeLoc TL) {
6133   const TypedefType *T = TL.getTypePtr();
6134   TypedefNameDecl *Typedef
6135     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6136                                                                T->getDecl()));
6137   if (!Typedef)
6138     return QualType();
6139 
6140   QualType Result = TL.getType();
6141   if (getDerived().AlwaysRebuild() ||
6142       Typedef != T->getDecl()) {
6143     Result = getDerived().RebuildTypedefType(Typedef);
6144     if (Result.isNull())
6145       return QualType();
6146   }
6147 
6148   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6149   NewTL.setNameLoc(TL.getNameLoc());
6150 
6151   return Result;
6152 }
6153 
6154 template<typename Derived>
6155 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6156                                                       TypeOfExprTypeLoc TL) {
6157   // typeof expressions are not potentially evaluated contexts
6158   EnterExpressionEvaluationContext Unevaluated(
6159       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6160       Sema::ReuseLambdaContextDecl);
6161 
6162   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6163   if (E.isInvalid())
6164     return QualType();
6165 
6166   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6167   if (E.isInvalid())
6168     return QualType();
6169 
6170   QualType Result = TL.getType();
6171   if (getDerived().AlwaysRebuild() ||
6172       E.get() != TL.getUnderlyingExpr()) {
6173     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
6174     if (Result.isNull())
6175       return QualType();
6176   }
6177   else E.get();
6178 
6179   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6180   NewTL.setTypeofLoc(TL.getTypeofLoc());
6181   NewTL.setLParenLoc(TL.getLParenLoc());
6182   NewTL.setRParenLoc(TL.getRParenLoc());
6183 
6184   return Result;
6185 }
6186 
6187 template<typename Derived>
6188 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6189                                                      TypeOfTypeLoc TL) {
6190   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
6191   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6192   if (!New_Under_TI)
6193     return QualType();
6194 
6195   QualType Result = TL.getType();
6196   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6197     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
6198     if (Result.isNull())
6199       return QualType();
6200   }
6201 
6202   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6203   NewTL.setTypeofLoc(TL.getTypeofLoc());
6204   NewTL.setLParenLoc(TL.getLParenLoc());
6205   NewTL.setRParenLoc(TL.getRParenLoc());
6206   NewTL.setUnderlyingTInfo(New_Under_TI);
6207 
6208   return Result;
6209 }
6210 
6211 template<typename Derived>
6212 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6213                                                        DecltypeTypeLoc TL) {
6214   const DecltypeType *T = TL.getTypePtr();
6215 
6216   // decltype expressions are not potentially evaluated contexts
6217   EnterExpressionEvaluationContext Unevaluated(
6218       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6219       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6220 
6221   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6222   if (E.isInvalid())
6223     return QualType();
6224 
6225   E = getSema().ActOnDecltypeExpression(E.get());
6226   if (E.isInvalid())
6227     return QualType();
6228 
6229   QualType Result = TL.getType();
6230   if (getDerived().AlwaysRebuild() ||
6231       E.get() != T->getUnderlyingExpr()) {
6232     Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6233     if (Result.isNull())
6234       return QualType();
6235   }
6236   else E.get();
6237 
6238   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6239   NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6240   NewTL.setRParenLoc(TL.getRParenLoc());
6241   return Result;
6242 }
6243 
6244 template<typename Derived>
6245 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6246                                                             TypeLocBuilder &TLB,
6247                                                      UnaryTransformTypeLoc TL) {
6248   QualType Result = TL.getType();
6249   if (Result->isDependentType()) {
6250     const UnaryTransformType *T = TL.getTypePtr();
6251     QualType NewBase =
6252       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6253     Result = getDerived().RebuildUnaryTransformType(NewBase,
6254                                                     T->getUTTKind(),
6255                                                     TL.getKWLoc());
6256     if (Result.isNull())
6257       return QualType();
6258   }
6259 
6260   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6261   NewTL.setKWLoc(TL.getKWLoc());
6262   NewTL.setParensRange(TL.getParensRange());
6263   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6264   return Result;
6265 }
6266 
6267 template<typename Derived>
6268 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6269     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6270   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6271 
6272   CXXScopeSpec SS;
6273   TemplateName TemplateName = getDerived().TransformTemplateName(
6274       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6275   if (TemplateName.isNull())
6276     return QualType();
6277 
6278   QualType OldDeduced = T->getDeducedType();
6279   QualType NewDeduced;
6280   if (!OldDeduced.isNull()) {
6281     NewDeduced = getDerived().TransformType(OldDeduced);
6282     if (NewDeduced.isNull())
6283       return QualType();
6284   }
6285 
6286   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6287       TemplateName, NewDeduced);
6288   if (Result.isNull())
6289     return QualType();
6290 
6291   DeducedTemplateSpecializationTypeLoc NewTL =
6292       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6293   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6294 
6295   return Result;
6296 }
6297 
6298 template<typename Derived>
6299 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6300                                                      RecordTypeLoc TL) {
6301   const RecordType *T = TL.getTypePtr();
6302   RecordDecl *Record
6303     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6304                                                           T->getDecl()));
6305   if (!Record)
6306     return QualType();
6307 
6308   QualType Result = TL.getType();
6309   if (getDerived().AlwaysRebuild() ||
6310       Record != T->getDecl()) {
6311     Result = getDerived().RebuildRecordType(Record);
6312     if (Result.isNull())
6313       return QualType();
6314   }
6315 
6316   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6317   NewTL.setNameLoc(TL.getNameLoc());
6318 
6319   return Result;
6320 }
6321 
6322 template<typename Derived>
6323 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6324                                                    EnumTypeLoc TL) {
6325   const EnumType *T = TL.getTypePtr();
6326   EnumDecl *Enum
6327     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6328                                                         T->getDecl()));
6329   if (!Enum)
6330     return QualType();
6331 
6332   QualType Result = TL.getType();
6333   if (getDerived().AlwaysRebuild() ||
6334       Enum != T->getDecl()) {
6335     Result = getDerived().RebuildEnumType(Enum);
6336     if (Result.isNull())
6337       return QualType();
6338   }
6339 
6340   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6341   NewTL.setNameLoc(TL.getNameLoc());
6342 
6343   return Result;
6344 }
6345 
6346 template<typename Derived>
6347 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6348                                          TypeLocBuilder &TLB,
6349                                          InjectedClassNameTypeLoc TL) {
6350   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6351                                        TL.getTypePtr()->getDecl());
6352   if (!D) return QualType();
6353 
6354   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6355   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6356   return T;
6357 }
6358 
6359 template<typename Derived>
6360 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6361                                                 TypeLocBuilder &TLB,
6362                                                 TemplateTypeParmTypeLoc TL) {
6363   return TransformTypeSpecType(TLB, TL);
6364 }
6365 
6366 template<typename Derived>
6367 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6368                                          TypeLocBuilder &TLB,
6369                                          SubstTemplateTypeParmTypeLoc TL) {
6370   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6371 
6372   // Substitute into the replacement type, which itself might involve something
6373   // that needs to be transformed. This only tends to occur with default
6374   // template arguments of template template parameters.
6375   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6376   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6377   if (Replacement.isNull())
6378     return QualType();
6379 
6380   // Always canonicalize the replacement type.
6381   Replacement = SemaRef.Context.getCanonicalType(Replacement);
6382   QualType Result
6383     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
6384                                                    Replacement);
6385 
6386   // Propagate type-source information.
6387   SubstTemplateTypeParmTypeLoc NewTL
6388     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6389   NewTL.setNameLoc(TL.getNameLoc());
6390   return Result;
6391 
6392 }
6393 
6394 template<typename Derived>
6395 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6396                                           TypeLocBuilder &TLB,
6397                                           SubstTemplateTypeParmPackTypeLoc TL) {
6398   return TransformTypeSpecType(TLB, TL);
6399 }
6400 
6401 template<typename Derived>
6402 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6403                                                         TypeLocBuilder &TLB,
6404                                            TemplateSpecializationTypeLoc TL) {
6405   const TemplateSpecializationType *T = TL.getTypePtr();
6406 
6407   // The nested-name-specifier never matters in a TemplateSpecializationType,
6408   // because we can't have a dependent nested-name-specifier anyway.
6409   CXXScopeSpec SS;
6410   TemplateName Template
6411     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6412                                          TL.getTemplateNameLoc());
6413   if (Template.isNull())
6414     return QualType();
6415 
6416   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6417 }
6418 
6419 template<typename Derived>
6420 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6421                                                      AtomicTypeLoc TL) {
6422   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6423   if (ValueType.isNull())
6424     return QualType();
6425 
6426   QualType Result = TL.getType();
6427   if (getDerived().AlwaysRebuild() ||
6428       ValueType != TL.getValueLoc().getType()) {
6429     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6430     if (Result.isNull())
6431       return QualType();
6432   }
6433 
6434   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6435   NewTL.setKWLoc(TL.getKWLoc());
6436   NewTL.setLParenLoc(TL.getLParenLoc());
6437   NewTL.setRParenLoc(TL.getRParenLoc());
6438 
6439   return Result;
6440 }
6441 
6442 template <typename Derived>
6443 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6444                                                    PipeTypeLoc TL) {
6445   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6446   if (ValueType.isNull())
6447     return QualType();
6448 
6449   QualType Result = TL.getType();
6450   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6451     const PipeType *PT = Result->castAs<PipeType>();
6452     bool isReadPipe = PT->isReadOnly();
6453     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6454     if (Result.isNull())
6455       return QualType();
6456   }
6457 
6458   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6459   NewTL.setKWLoc(TL.getKWLoc());
6460 
6461   return Result;
6462 }
6463 
6464 template <typename Derived>
6465 QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6466                                                      BitIntTypeLoc TL) {
6467   const BitIntType *EIT = TL.getTypePtr();
6468   QualType Result = TL.getType();
6469 
6470   if (getDerived().AlwaysRebuild()) {
6471     Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6472                                             EIT->getNumBits(), TL.getNameLoc());
6473     if (Result.isNull())
6474       return QualType();
6475   }
6476 
6477   BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6478   NewTL.setNameLoc(TL.getNameLoc());
6479   return Result;
6480 }
6481 
6482 template <typename Derived>
6483 QualType TreeTransform<Derived>::TransformDependentBitIntType(
6484     TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6485   const DependentBitIntType *EIT = TL.getTypePtr();
6486 
6487   EnterExpressionEvaluationContext Unevaluated(
6488       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6489   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6490   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6491 
6492   if (BitsExpr.isInvalid())
6493     return QualType();
6494 
6495   QualType Result = TL.getType();
6496 
6497   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6498     Result = getDerived().RebuildDependentBitIntType(
6499         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6500 
6501     if (Result.isNull())
6502       return QualType();
6503   }
6504 
6505   if (isa<DependentBitIntType>(Result)) {
6506     DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6507     NewTL.setNameLoc(TL.getNameLoc());
6508   } else {
6509     BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6510     NewTL.setNameLoc(TL.getNameLoc());
6511   }
6512   return Result;
6513 }
6514 
6515   /// Simple iterator that traverses the template arguments in a
6516   /// container that provides a \c getArgLoc() member function.
6517   ///
6518   /// This iterator is intended to be used with the iterator form of
6519   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6520   template<typename ArgLocContainer>
6521   class TemplateArgumentLocContainerIterator {
6522     ArgLocContainer *Container;
6523     unsigned Index;
6524 
6525   public:
6526     typedef TemplateArgumentLoc value_type;
6527     typedef TemplateArgumentLoc reference;
6528     typedef int difference_type;
6529     typedef std::input_iterator_tag iterator_category;
6530 
6531     class pointer {
6532       TemplateArgumentLoc Arg;
6533 
6534     public:
6535       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6536 
6537       const TemplateArgumentLoc *operator->() const {
6538         return &Arg;
6539       }
6540     };
6541 
6542 
6543     TemplateArgumentLocContainerIterator() {}
6544 
6545     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6546                                  unsigned Index)
6547       : Container(&Container), Index(Index) { }
6548 
6549     TemplateArgumentLocContainerIterator &operator++() {
6550       ++Index;
6551       return *this;
6552     }
6553 
6554     TemplateArgumentLocContainerIterator operator++(int) {
6555       TemplateArgumentLocContainerIterator Old(*this);
6556       ++(*this);
6557       return Old;
6558     }
6559 
6560     TemplateArgumentLoc operator*() const {
6561       return Container->getArgLoc(Index);
6562     }
6563 
6564     pointer operator->() const {
6565       return pointer(Container->getArgLoc(Index));
6566     }
6567 
6568     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6569                            const TemplateArgumentLocContainerIterator &Y) {
6570       return X.Container == Y.Container && X.Index == Y.Index;
6571     }
6572 
6573     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6574                            const TemplateArgumentLocContainerIterator &Y) {
6575       return !(X == Y);
6576     }
6577   };
6578 
6579 template<typename Derived>
6580 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6581                                                    AutoTypeLoc TL) {
6582   const AutoType *T = TL.getTypePtr();
6583   QualType OldDeduced = T->getDeducedType();
6584   QualType NewDeduced;
6585   if (!OldDeduced.isNull()) {
6586     NewDeduced = getDerived().TransformType(OldDeduced);
6587     if (NewDeduced.isNull())
6588       return QualType();
6589   }
6590 
6591   ConceptDecl *NewCD = nullptr;
6592   TemplateArgumentListInfo NewTemplateArgs;
6593   NestedNameSpecifierLoc NewNestedNameSpec;
6594   if (T->isConstrained()) {
6595     NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6596         TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6597 
6598     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6599     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6600     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6601     if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6602                                                 ArgIterator(TL,
6603                                                             TL.getNumArgs()),
6604                                                 NewTemplateArgs))
6605       return QualType();
6606 
6607     if (TL.getNestedNameSpecifierLoc()) {
6608       NewNestedNameSpec
6609         = getDerived().TransformNestedNameSpecifierLoc(
6610             TL.getNestedNameSpecifierLoc());
6611       if (!NewNestedNameSpec)
6612         return QualType();
6613     }
6614   }
6615 
6616   QualType Result = TL.getType();
6617   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6618       T->isDependentType() || T->isConstrained()) {
6619     // FIXME: Maybe don't rebuild if all template arguments are the same.
6620     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6621     NewArgList.reserve(NewTemplateArgs.size());
6622     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6623       NewArgList.push_back(ArgLoc.getArgument());
6624     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6625                                           NewArgList);
6626     if (Result.isNull())
6627       return QualType();
6628   }
6629 
6630   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6631   NewTL.setNameLoc(TL.getNameLoc());
6632   NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6633   NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6634   NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6635   NewTL.setFoundDecl(TL.getFoundDecl());
6636   NewTL.setLAngleLoc(TL.getLAngleLoc());
6637   NewTL.setRAngleLoc(TL.getRAngleLoc());
6638   NewTL.setRParenLoc(TL.getRParenLoc());
6639   for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6640     NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6641 
6642   return Result;
6643 }
6644 
6645 template <typename Derived>
6646 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6647                                                         TypeLocBuilder &TLB,
6648                                            TemplateSpecializationTypeLoc TL,
6649                                                       TemplateName Template) {
6650   TemplateArgumentListInfo NewTemplateArgs;
6651   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6652   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6653   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6654     ArgIterator;
6655   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6656                                               ArgIterator(TL, TL.getNumArgs()),
6657                                               NewTemplateArgs))
6658     return QualType();
6659 
6660   // FIXME: maybe don't rebuild if all the template arguments are the same.
6661 
6662   QualType Result =
6663     getDerived().RebuildTemplateSpecializationType(Template,
6664                                                    TL.getTemplateNameLoc(),
6665                                                    NewTemplateArgs);
6666 
6667   if (!Result.isNull()) {
6668     // Specializations of template template parameters are represented as
6669     // TemplateSpecializationTypes, and substitution of type alias templates
6670     // within a dependent context can transform them into
6671     // DependentTemplateSpecializationTypes.
6672     if (isa<DependentTemplateSpecializationType>(Result)) {
6673       DependentTemplateSpecializationTypeLoc NewTL
6674         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6675       NewTL.setElaboratedKeywordLoc(SourceLocation());
6676       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6677       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6678       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6679       NewTL.setLAngleLoc(TL.getLAngleLoc());
6680       NewTL.setRAngleLoc(TL.getRAngleLoc());
6681       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6682         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6683       return Result;
6684     }
6685 
6686     TemplateSpecializationTypeLoc NewTL
6687       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6688     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6689     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6690     NewTL.setLAngleLoc(TL.getLAngleLoc());
6691     NewTL.setRAngleLoc(TL.getRAngleLoc());
6692     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6693       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6694   }
6695 
6696   return Result;
6697 }
6698 
6699 template <typename Derived>
6700 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6701                                      TypeLocBuilder &TLB,
6702                                      DependentTemplateSpecializationTypeLoc TL,
6703                                      TemplateName Template,
6704                                      CXXScopeSpec &SS) {
6705   TemplateArgumentListInfo NewTemplateArgs;
6706   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6707   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6708   typedef TemplateArgumentLocContainerIterator<
6709             DependentTemplateSpecializationTypeLoc> ArgIterator;
6710   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6711                                               ArgIterator(TL, TL.getNumArgs()),
6712                                               NewTemplateArgs))
6713     return QualType();
6714 
6715   // FIXME: maybe don't rebuild if all the template arguments are the same.
6716 
6717   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6718     QualType Result
6719       = getSema().Context.getDependentTemplateSpecializationType(
6720                                                 TL.getTypePtr()->getKeyword(),
6721                                                          DTN->getQualifier(),
6722                                                          DTN->getIdentifier(),
6723                                                                NewTemplateArgs);
6724 
6725     DependentTemplateSpecializationTypeLoc NewTL
6726       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6727     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6728     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6729     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6730     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6731     NewTL.setLAngleLoc(TL.getLAngleLoc());
6732     NewTL.setRAngleLoc(TL.getRAngleLoc());
6733     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6734       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6735     return Result;
6736   }
6737 
6738   QualType Result
6739     = getDerived().RebuildTemplateSpecializationType(Template,
6740                                                      TL.getTemplateNameLoc(),
6741                                                      NewTemplateArgs);
6742 
6743   if (!Result.isNull()) {
6744     /// FIXME: Wrap this in an elaborated-type-specifier?
6745     TemplateSpecializationTypeLoc NewTL
6746       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6747     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6748     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6749     NewTL.setLAngleLoc(TL.getLAngleLoc());
6750     NewTL.setRAngleLoc(TL.getRAngleLoc());
6751     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6752       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6753   }
6754 
6755   return Result;
6756 }
6757 
6758 template<typename Derived>
6759 QualType
6760 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6761                                                 ElaboratedTypeLoc TL) {
6762   const ElaboratedType *T = TL.getTypePtr();
6763 
6764   NestedNameSpecifierLoc QualifierLoc;
6765   // NOTE: the qualifier in an ElaboratedType is optional.
6766   if (TL.getQualifierLoc()) {
6767     QualifierLoc
6768       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6769     if (!QualifierLoc)
6770       return QualType();
6771   }
6772 
6773   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6774   if (NamedT.isNull())
6775     return QualType();
6776 
6777   // C++0x [dcl.type.elab]p2:
6778   //   If the identifier resolves to a typedef-name or the simple-template-id
6779   //   resolves to an alias template specialization, the
6780   //   elaborated-type-specifier is ill-formed.
6781   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6782     if (const TemplateSpecializationType *TST =
6783           NamedT->getAs<TemplateSpecializationType>()) {
6784       TemplateName Template = TST->getTemplateName();
6785       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6786               Template.getAsTemplateDecl())) {
6787         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6788                      diag::err_tag_reference_non_tag)
6789             << TAT << Sema::NTK_TypeAliasTemplate
6790             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6791         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6792       }
6793     }
6794   }
6795 
6796   QualType Result = TL.getType();
6797   if (getDerived().AlwaysRebuild() ||
6798       QualifierLoc != TL.getQualifierLoc() ||
6799       NamedT != T->getNamedType()) {
6800     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6801                                                 T->getKeyword(),
6802                                                 QualifierLoc, NamedT);
6803     if (Result.isNull())
6804       return QualType();
6805   }
6806 
6807   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6808   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6809   NewTL.setQualifierLoc(QualifierLoc);
6810   return Result;
6811 }
6812 
6813 template<typename Derived>
6814 QualType TreeTransform<Derived>::TransformAttributedType(
6815                                                 TypeLocBuilder &TLB,
6816                                                 AttributedTypeLoc TL) {
6817   const AttributedType *oldType = TL.getTypePtr();
6818   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6819   if (modifiedType.isNull())
6820     return QualType();
6821 
6822   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6823   const Attr *oldAttr = TL.getAttr();
6824   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6825   if (oldAttr && !newAttr)
6826     return QualType();
6827 
6828   QualType result = TL.getType();
6829 
6830   // FIXME: dependent operand expressions?
6831   if (getDerived().AlwaysRebuild() ||
6832       modifiedType != oldType->getModifiedType()) {
6833     // TODO: this is really lame; we should really be rebuilding the
6834     // equivalent type from first principles.
6835     QualType equivalentType
6836       = getDerived().TransformType(oldType->getEquivalentType());
6837     if (equivalentType.isNull())
6838       return QualType();
6839 
6840     // Check whether we can add nullability; it is only represented as
6841     // type sugar, and therefore cannot be diagnosed in any other way.
6842     if (auto nullability = oldType->getImmediateNullability()) {
6843       if (!modifiedType->canHaveNullability()) {
6844         SemaRef.Diag(TL.getAttr()->getLocation(),
6845                      diag::err_nullability_nonpointer)
6846             << DiagNullabilityKind(*nullability, false) << modifiedType;
6847         return QualType();
6848       }
6849     }
6850 
6851     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6852                                                modifiedType,
6853                                                equivalentType);
6854   }
6855 
6856   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6857   newTL.setAttr(newAttr);
6858   return result;
6859 }
6860 
6861 template<typename Derived>
6862 QualType
6863 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6864                                            ParenTypeLoc TL) {
6865   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6866   if (Inner.isNull())
6867     return QualType();
6868 
6869   QualType Result = TL.getType();
6870   if (getDerived().AlwaysRebuild() ||
6871       Inner != TL.getInnerLoc().getType()) {
6872     Result = getDerived().RebuildParenType(Inner);
6873     if (Result.isNull())
6874       return QualType();
6875   }
6876 
6877   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6878   NewTL.setLParenLoc(TL.getLParenLoc());
6879   NewTL.setRParenLoc(TL.getRParenLoc());
6880   return Result;
6881 }
6882 
6883 template <typename Derived>
6884 QualType
6885 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6886                                                     MacroQualifiedTypeLoc TL) {
6887   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6888   if (Inner.isNull())
6889     return QualType();
6890 
6891   QualType Result = TL.getType();
6892   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6893     Result =
6894         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6895     if (Result.isNull())
6896       return QualType();
6897   }
6898 
6899   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6900   NewTL.setExpansionLoc(TL.getExpansionLoc());
6901   return Result;
6902 }
6903 
6904 template<typename Derived>
6905 QualType TreeTransform<Derived>::TransformDependentNameType(
6906     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6907   return TransformDependentNameType(TLB, TL, false);
6908 }
6909 
6910 template<typename Derived>
6911 QualType TreeTransform<Derived>::TransformDependentNameType(
6912     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6913   const DependentNameType *T = TL.getTypePtr();
6914 
6915   NestedNameSpecifierLoc QualifierLoc
6916     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6917   if (!QualifierLoc)
6918     return QualType();
6919 
6920   QualType Result
6921     = getDerived().RebuildDependentNameType(T->getKeyword(),
6922                                             TL.getElaboratedKeywordLoc(),
6923                                             QualifierLoc,
6924                                             T->getIdentifier(),
6925                                             TL.getNameLoc(),
6926                                             DeducedTSTContext);
6927   if (Result.isNull())
6928     return QualType();
6929 
6930   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6931     QualType NamedT = ElabT->getNamedType();
6932     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6933 
6934     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6935     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6936     NewTL.setQualifierLoc(QualifierLoc);
6937   } else {
6938     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6939     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6940     NewTL.setQualifierLoc(QualifierLoc);
6941     NewTL.setNameLoc(TL.getNameLoc());
6942   }
6943   return Result;
6944 }
6945 
6946 template<typename Derived>
6947 QualType TreeTransform<Derived>::
6948           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6949                                  DependentTemplateSpecializationTypeLoc TL) {
6950   NestedNameSpecifierLoc QualifierLoc;
6951   if (TL.getQualifierLoc()) {
6952     QualifierLoc
6953       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6954     if (!QualifierLoc)
6955       return QualType();
6956   }
6957 
6958   return getDerived()
6959            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6960 }
6961 
6962 template<typename Derived>
6963 QualType TreeTransform<Derived>::
6964 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6965                                    DependentTemplateSpecializationTypeLoc TL,
6966                                        NestedNameSpecifierLoc QualifierLoc) {
6967   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6968 
6969   TemplateArgumentListInfo NewTemplateArgs;
6970   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6971   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6972 
6973   typedef TemplateArgumentLocContainerIterator<
6974   DependentTemplateSpecializationTypeLoc> ArgIterator;
6975   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6976                                               ArgIterator(TL, TL.getNumArgs()),
6977                                               NewTemplateArgs))
6978     return QualType();
6979 
6980   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6981       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6982       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6983       /*AllowInjectedClassName*/ false);
6984   if (Result.isNull())
6985     return QualType();
6986 
6987   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6988     QualType NamedT = ElabT->getNamedType();
6989 
6990     // Copy information relevant to the template specialization.
6991     TemplateSpecializationTypeLoc NamedTL
6992       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6993     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6994     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6995     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6996     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6997     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6998       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6999 
7000     // Copy information relevant to the elaborated type.
7001     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7002     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7003     NewTL.setQualifierLoc(QualifierLoc);
7004   } else if (isa<DependentTemplateSpecializationType>(Result)) {
7005     DependentTemplateSpecializationTypeLoc SpecTL
7006       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7007     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7008     SpecTL.setQualifierLoc(QualifierLoc);
7009     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7010     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7011     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7012     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7013     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7014       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7015   } else {
7016     TemplateSpecializationTypeLoc SpecTL
7017       = TLB.push<TemplateSpecializationTypeLoc>(Result);
7018     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7019     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7020     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7021     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7022     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7023       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7024   }
7025   return Result;
7026 }
7027 
7028 template<typename Derived>
7029 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7030                                                       PackExpansionTypeLoc TL) {
7031   QualType Pattern
7032     = getDerived().TransformType(TLB, TL.getPatternLoc());
7033   if (Pattern.isNull())
7034     return QualType();
7035 
7036   QualType Result = TL.getType();
7037   if (getDerived().AlwaysRebuild() ||
7038       Pattern != TL.getPatternLoc().getType()) {
7039     Result = getDerived().RebuildPackExpansionType(Pattern,
7040                                            TL.getPatternLoc().getSourceRange(),
7041                                                    TL.getEllipsisLoc(),
7042                                            TL.getTypePtr()->getNumExpansions());
7043     if (Result.isNull())
7044       return QualType();
7045   }
7046 
7047   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7048   NewT.setEllipsisLoc(TL.getEllipsisLoc());
7049   return Result;
7050 }
7051 
7052 template<typename Derived>
7053 QualType
7054 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7055                                                    ObjCInterfaceTypeLoc TL) {
7056   // ObjCInterfaceType is never dependent.
7057   TLB.pushFullCopy(TL);
7058   return TL.getType();
7059 }
7060 
7061 template<typename Derived>
7062 QualType
7063 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7064                                                    ObjCTypeParamTypeLoc TL) {
7065   const ObjCTypeParamType *T = TL.getTypePtr();
7066   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7067       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7068   if (!OTP)
7069     return QualType();
7070 
7071   QualType Result = TL.getType();
7072   if (getDerived().AlwaysRebuild() ||
7073       OTP != T->getDecl()) {
7074     Result = getDerived().RebuildObjCTypeParamType(OTP,
7075                  TL.getProtocolLAngleLoc(),
7076                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
7077                                     TL.getNumProtocols()),
7078                  TL.getProtocolLocs(),
7079                  TL.getProtocolRAngleLoc());
7080     if (Result.isNull())
7081       return QualType();
7082   }
7083 
7084   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7085   if (TL.getNumProtocols()) {
7086     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7087     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7088       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7089     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7090   }
7091   return Result;
7092 }
7093 
7094 template<typename Derived>
7095 QualType
7096 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7097                                                 ObjCObjectTypeLoc TL) {
7098   // Transform base type.
7099   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7100   if (BaseType.isNull())
7101     return QualType();
7102 
7103   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7104 
7105   // Transform type arguments.
7106   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7107   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7108     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7109     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7110     QualType TypeArg = TypeArgInfo->getType();
7111     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7112       AnyChanged = true;
7113 
7114       // We have a pack expansion. Instantiate it.
7115       const auto *PackExpansion = PackExpansionLoc.getType()
7116                                     ->castAs<PackExpansionType>();
7117       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7118       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7119                                               Unexpanded);
7120       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
7121 
7122       // Determine whether the set of unexpanded parameter packs can
7123       // and should be expanded.
7124       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7125       bool Expand = false;
7126       bool RetainExpansion = false;
7127       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7128       if (getDerived().TryExpandParameterPacks(
7129             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7130             Unexpanded, Expand, RetainExpansion, NumExpansions))
7131         return QualType();
7132 
7133       if (!Expand) {
7134         // We can't expand this pack expansion into separate arguments yet;
7135         // just substitute into the pattern and create a new pack expansion
7136         // type.
7137         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7138 
7139         TypeLocBuilder TypeArgBuilder;
7140         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7141         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7142                                                              PatternLoc);
7143         if (NewPatternType.isNull())
7144           return QualType();
7145 
7146         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7147                                       NewPatternType, NumExpansions);
7148         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7149         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7150         NewTypeArgInfos.push_back(
7151           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7152         continue;
7153       }
7154 
7155       // Substitute into the pack expansion pattern for each slice of the
7156       // pack.
7157       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7158         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7159 
7160         TypeLocBuilder TypeArgBuilder;
7161         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7162 
7163         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7164                                                          PatternLoc);
7165         if (NewTypeArg.isNull())
7166           return QualType();
7167 
7168         NewTypeArgInfos.push_back(
7169           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7170       }
7171 
7172       continue;
7173     }
7174 
7175     TypeLocBuilder TypeArgBuilder;
7176     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7177     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7178     if (NewTypeArg.isNull())
7179       return QualType();
7180 
7181     // If nothing changed, just keep the old TypeSourceInfo.
7182     if (NewTypeArg == TypeArg) {
7183       NewTypeArgInfos.push_back(TypeArgInfo);
7184       continue;
7185     }
7186 
7187     NewTypeArgInfos.push_back(
7188       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7189     AnyChanged = true;
7190   }
7191 
7192   QualType Result = TL.getType();
7193   if (getDerived().AlwaysRebuild() || AnyChanged) {
7194     // Rebuild the type.
7195     Result = getDerived().RebuildObjCObjectType(
7196         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7197         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7198         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7199         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7200 
7201     if (Result.isNull())
7202       return QualType();
7203   }
7204 
7205   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7206   NewT.setHasBaseTypeAsWritten(true);
7207   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7208   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7209     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7210   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7211   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7212   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7213     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7214   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7215   return Result;
7216 }
7217 
7218 template<typename Derived>
7219 QualType
7220 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7221                                                ObjCObjectPointerTypeLoc TL) {
7222   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7223   if (PointeeType.isNull())
7224     return QualType();
7225 
7226   QualType Result = TL.getType();
7227   if (getDerived().AlwaysRebuild() ||
7228       PointeeType != TL.getPointeeLoc().getType()) {
7229     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7230                                                        TL.getStarLoc());
7231     if (Result.isNull())
7232       return QualType();
7233   }
7234 
7235   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7236   NewT.setStarLoc(TL.getStarLoc());
7237   return Result;
7238 }
7239 
7240 //===----------------------------------------------------------------------===//
7241 // Statement transformation
7242 //===----------------------------------------------------------------------===//
7243 template<typename Derived>
7244 StmtResult
7245 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7246   return S;
7247 }
7248 
7249 template<typename Derived>
7250 StmtResult
7251 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7252   return getDerived().TransformCompoundStmt(S, false);
7253 }
7254 
7255 template<typename Derived>
7256 StmtResult
7257 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7258                                               bool IsStmtExpr) {
7259   Sema::CompoundScopeRAII CompoundScope(getSema());
7260 
7261   const Stmt *ExprResult = S->getStmtExprResult();
7262   bool SubStmtInvalid = false;
7263   bool SubStmtChanged = false;
7264   SmallVector<Stmt*, 8> Statements;
7265   for (auto *B : S->body()) {
7266     StmtResult Result = getDerived().TransformStmt(
7267         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7268 
7269     if (Result.isInvalid()) {
7270       // Immediately fail if this was a DeclStmt, since it's very
7271       // likely that this will cause problems for future statements.
7272       if (isa<DeclStmt>(B))
7273         return StmtError();
7274 
7275       // Otherwise, just keep processing substatements and fail later.
7276       SubStmtInvalid = true;
7277       continue;
7278     }
7279 
7280     SubStmtChanged = SubStmtChanged || Result.get() != B;
7281     Statements.push_back(Result.getAs<Stmt>());
7282   }
7283 
7284   if (SubStmtInvalid)
7285     return StmtError();
7286 
7287   if (!getDerived().AlwaysRebuild() &&
7288       !SubStmtChanged)
7289     return S;
7290 
7291   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7292                                           Statements,
7293                                           S->getRBracLoc(),
7294                                           IsStmtExpr);
7295 }
7296 
7297 template<typename Derived>
7298 StmtResult
7299 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7300   ExprResult LHS, RHS;
7301   {
7302     EnterExpressionEvaluationContext Unevaluated(
7303         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7304 
7305     // Transform the left-hand case value.
7306     LHS = getDerived().TransformExpr(S->getLHS());
7307     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7308     if (LHS.isInvalid())
7309       return StmtError();
7310 
7311     // Transform the right-hand case value (for the GNU case-range extension).
7312     RHS = getDerived().TransformExpr(S->getRHS());
7313     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7314     if (RHS.isInvalid())
7315       return StmtError();
7316   }
7317 
7318   // Build the case statement.
7319   // Case statements are always rebuilt so that they will attached to their
7320   // transformed switch statement.
7321   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7322                                                        LHS.get(),
7323                                                        S->getEllipsisLoc(),
7324                                                        RHS.get(),
7325                                                        S->getColonLoc());
7326   if (Case.isInvalid())
7327     return StmtError();
7328 
7329   // Transform the statement following the case
7330   StmtResult SubStmt =
7331       getDerived().TransformStmt(S->getSubStmt());
7332   if (SubStmt.isInvalid())
7333     return StmtError();
7334 
7335   // Attach the body to the case statement
7336   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7337 }
7338 
7339 template <typename Derived>
7340 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7341   // Transform the statement following the default case
7342   StmtResult SubStmt =
7343       getDerived().TransformStmt(S->getSubStmt());
7344   if (SubStmt.isInvalid())
7345     return StmtError();
7346 
7347   // Default statements are always rebuilt
7348   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7349                                          SubStmt.get());
7350 }
7351 
7352 template<typename Derived>
7353 StmtResult
7354 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7355   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7356   if (SubStmt.isInvalid())
7357     return StmtError();
7358 
7359   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7360                                         S->getDecl());
7361   if (!LD)
7362     return StmtError();
7363 
7364   // If we're transforming "in-place" (we're not creating new local
7365   // declarations), assume we're replacing the old label statement
7366   // and clear out the reference to it.
7367   if (LD == S->getDecl())
7368     S->getDecl()->setStmt(nullptr);
7369 
7370   // FIXME: Pass the real colon location in.
7371   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7372                                        cast<LabelDecl>(LD), SourceLocation(),
7373                                        SubStmt.get());
7374 }
7375 
7376 template <typename Derived>
7377 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7378   if (!R)
7379     return R;
7380 
7381   switch (R->getKind()) {
7382 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
7383 #define ATTR(X)
7384 #define PRAGMA_SPELLING_ATTR(X)                                                \
7385   case attr::X:                                                                \
7386     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7387 #include "clang/Basic/AttrList.inc"
7388   default:
7389     return R;
7390   }
7391 }
7392 
7393 template <typename Derived>
7394 StmtResult
7395 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7396                                                 StmtDiscardKind SDK) {
7397   bool AttrsChanged = false;
7398   SmallVector<const Attr *, 1> Attrs;
7399 
7400   // Visit attributes and keep track if any are transformed.
7401   for (const auto *I : S->getAttrs()) {
7402     const Attr *R = getDerived().TransformAttr(I);
7403     AttrsChanged |= (I != R);
7404     if (R)
7405       Attrs.push_back(R);
7406   }
7407 
7408   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7409   if (SubStmt.isInvalid())
7410     return StmtError();
7411 
7412   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7413     return S;
7414 
7415   // If transforming the attributes failed for all of the attributes in the
7416   // statement, don't make an AttributedStmt without attributes.
7417   if (Attrs.empty())
7418     return SubStmt;
7419 
7420   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7421                                             SubStmt.get());
7422 }
7423 
7424 template<typename Derived>
7425 StmtResult
7426 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7427   // Transform the initialization statement
7428   StmtResult Init = getDerived().TransformStmt(S->getInit());
7429   if (Init.isInvalid())
7430     return StmtError();
7431 
7432   Sema::ConditionResult Cond;
7433   if (!S->isConsteval()) {
7434     // Transform the condition
7435     Cond = getDerived().TransformCondition(
7436         S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7437         S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7438                          : Sema::ConditionKind::Boolean);
7439     if (Cond.isInvalid())
7440       return StmtError();
7441   }
7442 
7443   // If this is a constexpr if, determine which arm we should instantiate.
7444   llvm::Optional<bool> ConstexprConditionValue;
7445   if (S->isConstexpr())
7446     ConstexprConditionValue = Cond.getKnownValue();
7447 
7448   // Transform the "then" branch.
7449   StmtResult Then;
7450   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7451     Then = getDerived().TransformStmt(S->getThen());
7452     if (Then.isInvalid())
7453       return StmtError();
7454   } else {
7455     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7456   }
7457 
7458   // Transform the "else" branch.
7459   StmtResult Else;
7460   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7461     Else = getDerived().TransformStmt(S->getElse());
7462     if (Else.isInvalid())
7463       return StmtError();
7464   }
7465 
7466   if (!getDerived().AlwaysRebuild() &&
7467       Init.get() == S->getInit() &&
7468       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7469       Then.get() == S->getThen() &&
7470       Else.get() == S->getElse())
7471     return S;
7472 
7473   return getDerived().RebuildIfStmt(
7474       S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7475       S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7476 }
7477 
7478 template<typename Derived>
7479 StmtResult
7480 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7481   // Transform the initialization statement
7482   StmtResult Init = getDerived().TransformStmt(S->getInit());
7483   if (Init.isInvalid())
7484     return StmtError();
7485 
7486   // Transform the condition.
7487   Sema::ConditionResult Cond = getDerived().TransformCondition(
7488       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7489       Sema::ConditionKind::Switch);
7490   if (Cond.isInvalid())
7491     return StmtError();
7492 
7493   // Rebuild the switch statement.
7494   StmtResult Switch =
7495       getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7496                                           Init.get(), Cond, S->getRParenLoc());
7497   if (Switch.isInvalid())
7498     return StmtError();
7499 
7500   // Transform the body of the switch statement.
7501   StmtResult Body = getDerived().TransformStmt(S->getBody());
7502   if (Body.isInvalid())
7503     return StmtError();
7504 
7505   // Complete the switch statement.
7506   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7507                                             Body.get());
7508 }
7509 
7510 template<typename Derived>
7511 StmtResult
7512 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7513   // Transform the condition
7514   Sema::ConditionResult Cond = getDerived().TransformCondition(
7515       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7516       Sema::ConditionKind::Boolean);
7517   if (Cond.isInvalid())
7518     return StmtError();
7519 
7520   // Transform the body
7521   StmtResult Body = getDerived().TransformStmt(S->getBody());
7522   if (Body.isInvalid())
7523     return StmtError();
7524 
7525   if (!getDerived().AlwaysRebuild() &&
7526       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7527       Body.get() == S->getBody())
7528     return Owned(S);
7529 
7530   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7531                                        Cond, S->getRParenLoc(), Body.get());
7532 }
7533 
7534 template<typename Derived>
7535 StmtResult
7536 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7537   // Transform the body
7538   StmtResult Body = getDerived().TransformStmt(S->getBody());
7539   if (Body.isInvalid())
7540     return StmtError();
7541 
7542   // Transform the condition
7543   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7544   if (Cond.isInvalid())
7545     return StmtError();
7546 
7547   if (!getDerived().AlwaysRebuild() &&
7548       Cond.get() == S->getCond() &&
7549       Body.get() == S->getBody())
7550     return S;
7551 
7552   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7553                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7554                                     S->getRParenLoc());
7555 }
7556 
7557 template<typename Derived>
7558 StmtResult
7559 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7560   if (getSema().getLangOpts().OpenMP)
7561     getSema().startOpenMPLoop();
7562 
7563   // Transform the initialization statement
7564   StmtResult Init = getDerived().TransformStmt(S->getInit());
7565   if (Init.isInvalid())
7566     return StmtError();
7567 
7568   // In OpenMP loop region loop control variable must be captured and be
7569   // private. Perform analysis of first part (if any).
7570   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7571     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7572 
7573   // Transform the condition
7574   Sema::ConditionResult Cond = getDerived().TransformCondition(
7575       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7576       Sema::ConditionKind::Boolean);
7577   if (Cond.isInvalid())
7578     return StmtError();
7579 
7580   // Transform the increment
7581   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7582   if (Inc.isInvalid())
7583     return StmtError();
7584 
7585   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7586   if (S->getInc() && !FullInc.get())
7587     return StmtError();
7588 
7589   // Transform the body
7590   StmtResult Body = getDerived().TransformStmt(S->getBody());
7591   if (Body.isInvalid())
7592     return StmtError();
7593 
7594   if (!getDerived().AlwaysRebuild() &&
7595       Init.get() == S->getInit() &&
7596       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7597       Inc.get() == S->getInc() &&
7598       Body.get() == S->getBody())
7599     return S;
7600 
7601   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7602                                      Init.get(), Cond, FullInc,
7603                                      S->getRParenLoc(), Body.get());
7604 }
7605 
7606 template<typename Derived>
7607 StmtResult
7608 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7609   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7610                                         S->getLabel());
7611   if (!LD)
7612     return StmtError();
7613 
7614   // Goto statements must always be rebuilt, to resolve the label.
7615   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7616                                       cast<LabelDecl>(LD));
7617 }
7618 
7619 template<typename Derived>
7620 StmtResult
7621 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7622   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7623   if (Target.isInvalid())
7624     return StmtError();
7625   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7626 
7627   if (!getDerived().AlwaysRebuild() &&
7628       Target.get() == S->getTarget())
7629     return S;
7630 
7631   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7632                                               Target.get());
7633 }
7634 
7635 template<typename Derived>
7636 StmtResult
7637 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7638   return S;
7639 }
7640 
7641 template<typename Derived>
7642 StmtResult
7643 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7644   return S;
7645 }
7646 
7647 template<typename Derived>
7648 StmtResult
7649 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7650   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7651                                                         /*NotCopyInit*/false);
7652   if (Result.isInvalid())
7653     return StmtError();
7654 
7655   // FIXME: We always rebuild the return statement because there is no way
7656   // to tell whether the return type of the function has changed.
7657   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7658 }
7659 
7660 template<typename Derived>
7661 StmtResult
7662 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7663   bool DeclChanged = false;
7664   SmallVector<Decl *, 4> Decls;
7665   for (auto *D : S->decls()) {
7666     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7667     if (!Transformed)
7668       return StmtError();
7669 
7670     if (Transformed != D)
7671       DeclChanged = true;
7672 
7673     Decls.push_back(Transformed);
7674   }
7675 
7676   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7677     return S;
7678 
7679   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7680 }
7681 
7682 template<typename Derived>
7683 StmtResult
7684 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7685 
7686   SmallVector<Expr*, 8> Constraints;
7687   SmallVector<Expr*, 8> Exprs;
7688   SmallVector<IdentifierInfo *, 4> Names;
7689 
7690   ExprResult AsmString;
7691   SmallVector<Expr*, 8> Clobbers;
7692 
7693   bool ExprsChanged = false;
7694 
7695   // Go through the outputs.
7696   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7697     Names.push_back(S->getOutputIdentifier(I));
7698 
7699     // No need to transform the constraint literal.
7700     Constraints.push_back(S->getOutputConstraintLiteral(I));
7701 
7702     // Transform the output expr.
7703     Expr *OutputExpr = S->getOutputExpr(I);
7704     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7705     if (Result.isInvalid())
7706       return StmtError();
7707 
7708     ExprsChanged |= Result.get() != OutputExpr;
7709 
7710     Exprs.push_back(Result.get());
7711   }
7712 
7713   // Go through the inputs.
7714   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7715     Names.push_back(S->getInputIdentifier(I));
7716 
7717     // No need to transform the constraint literal.
7718     Constraints.push_back(S->getInputConstraintLiteral(I));
7719 
7720     // Transform the input expr.
7721     Expr *InputExpr = S->getInputExpr(I);
7722     ExprResult Result = getDerived().TransformExpr(InputExpr);
7723     if (Result.isInvalid())
7724       return StmtError();
7725 
7726     ExprsChanged |= Result.get() != InputExpr;
7727 
7728     Exprs.push_back(Result.get());
7729   }
7730 
7731   // Go through the Labels.
7732   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7733     Names.push_back(S->getLabelIdentifier(I));
7734 
7735     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7736     if (Result.isInvalid())
7737       return StmtError();
7738     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7739     Exprs.push_back(Result.get());
7740   }
7741   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7742     return S;
7743 
7744   // Go through the clobbers.
7745   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7746     Clobbers.push_back(S->getClobberStringLiteral(I));
7747 
7748   // No need to transform the asm string literal.
7749   AsmString = S->getAsmString();
7750   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7751                                         S->isVolatile(), S->getNumOutputs(),
7752                                         S->getNumInputs(), Names.data(),
7753                                         Constraints, Exprs, AsmString.get(),
7754                                         Clobbers, S->getNumLabels(),
7755                                         S->getRParenLoc());
7756 }
7757 
7758 template<typename Derived>
7759 StmtResult
7760 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7761   ArrayRef<Token> AsmToks =
7762     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7763 
7764   bool HadError = false, HadChange = false;
7765 
7766   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7767   SmallVector<Expr*, 8> TransformedExprs;
7768   TransformedExprs.reserve(SrcExprs.size());
7769   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7770     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7771     if (!Result.isUsable()) {
7772       HadError = true;
7773     } else {
7774       HadChange |= (Result.get() != SrcExprs[i]);
7775       TransformedExprs.push_back(Result.get());
7776     }
7777   }
7778 
7779   if (HadError) return StmtError();
7780   if (!HadChange && !getDerived().AlwaysRebuild())
7781     return Owned(S);
7782 
7783   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7784                                        AsmToks, S->getAsmString(),
7785                                        S->getNumOutputs(), S->getNumInputs(),
7786                                        S->getAllConstraints(), S->getClobbers(),
7787                                        TransformedExprs, S->getEndLoc());
7788 }
7789 
7790 // C++ Coroutines TS
7791 
7792 template<typename Derived>
7793 StmtResult
7794 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7795   auto *ScopeInfo = SemaRef.getCurFunction();
7796   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7797   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7798          ScopeInfo->NeedsCoroutineSuspends &&
7799          ScopeInfo->CoroutineSuspends.first == nullptr &&
7800          ScopeInfo->CoroutineSuspends.second == nullptr &&
7801          "expected clean scope info");
7802 
7803   // Set that we have (possibly-invalid) suspend points before we do anything
7804   // that may fail.
7805   ScopeInfo->setNeedsCoroutineSuspends(false);
7806 
7807   // We re-build the coroutine promise object (and the coroutine parameters its
7808   // type and constructor depend on) based on the types used in our current
7809   // function. We must do so, and set it on the current FunctionScopeInfo,
7810   // before attempting to transform the other parts of the coroutine body
7811   // statement, such as the implicit suspend statements (because those
7812   // statements reference the FunctionScopeInfo::CoroutinePromise).
7813   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7814     return StmtError();
7815   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7816   if (!Promise)
7817     return StmtError();
7818   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7819   ScopeInfo->CoroutinePromise = Promise;
7820 
7821   // Transform the implicit coroutine statements constructed using dependent
7822   // types during the previous parse: initial and final suspensions, the return
7823   // object, and others. We also transform the coroutine function's body.
7824   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7825   if (InitSuspend.isInvalid())
7826     return StmtError();
7827   StmtResult FinalSuspend =
7828       getDerived().TransformStmt(S->getFinalSuspendStmt());
7829   if (FinalSuspend.isInvalid() ||
7830       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
7831     return StmtError();
7832   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7833   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7834 
7835   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7836   if (BodyRes.isInvalid())
7837     return StmtError();
7838 
7839   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7840   if (Builder.isInvalid())
7841     return StmtError();
7842 
7843   Expr *ReturnObject = S->getReturnValueInit();
7844   assert(ReturnObject && "the return object is expected to be valid");
7845   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7846                                                      /*NoCopyInit*/ false);
7847   if (Res.isInvalid())
7848     return StmtError();
7849   Builder.ReturnValue = Res.get();
7850 
7851   // If during the previous parse the coroutine still had a dependent promise
7852   // statement, we may need to build some implicit coroutine statements
7853   // (such as exception and fallthrough handlers) for the first time.
7854   if (S->hasDependentPromiseType()) {
7855     // We can only build these statements, however, if the current promise type
7856     // is not dependent.
7857     if (!Promise->getType()->isDependentType()) {
7858       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7859              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7860              "these nodes should not have been built yet");
7861       if (!Builder.buildDependentStatements())
7862         return StmtError();
7863     }
7864   } else {
7865     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7866       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7867       if (Res.isInvalid())
7868         return StmtError();
7869       Builder.OnFallthrough = Res.get();
7870     }
7871 
7872     if (auto *OnException = S->getExceptionHandler()) {
7873       StmtResult Res = getDerived().TransformStmt(OnException);
7874       if (Res.isInvalid())
7875         return StmtError();
7876       Builder.OnException = Res.get();
7877     }
7878 
7879     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7880       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7881       if (Res.isInvalid())
7882         return StmtError();
7883       Builder.ReturnStmtOnAllocFailure = Res.get();
7884     }
7885 
7886     // Transform any additional statements we may have already built
7887     assert(S->getAllocate() && S->getDeallocate() &&
7888            "allocation and deallocation calls must already be built");
7889     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7890     if (AllocRes.isInvalid())
7891       return StmtError();
7892     Builder.Allocate = AllocRes.get();
7893 
7894     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7895     if (DeallocRes.isInvalid())
7896       return StmtError();
7897     Builder.Deallocate = DeallocRes.get();
7898 
7899     assert(S->getResultDecl() && "ResultDecl must already be built");
7900     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7901     if (ResultDecl.isInvalid())
7902       return StmtError();
7903     Builder.ResultDecl = ResultDecl.get();
7904 
7905     if (auto *ReturnStmt = S->getReturnStmt()) {
7906       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7907       if (Res.isInvalid())
7908         return StmtError();
7909       Builder.ReturnStmt = Res.get();
7910     }
7911   }
7912 
7913   return getDerived().RebuildCoroutineBodyStmt(Builder);
7914 }
7915 
7916 template<typename Derived>
7917 StmtResult
7918 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7919   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7920                                                         /*NotCopyInit*/false);
7921   if (Result.isInvalid())
7922     return StmtError();
7923 
7924   // Always rebuild; we don't know if this needs to be injected into a new
7925   // context or if the promise type has changed.
7926   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7927                                           S->isImplicit());
7928 }
7929 
7930 template<typename Derived>
7931 ExprResult
7932 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7933   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7934                                                         /*NotCopyInit*/false);
7935   if (Result.isInvalid())
7936     return ExprError();
7937 
7938   // Always rebuild; we don't know if this needs to be injected into a new
7939   // context or if the promise type has changed.
7940   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7941                                          E->isImplicit());
7942 }
7943 
7944 template <typename Derived>
7945 ExprResult
7946 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7947   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7948                                                         /*NotCopyInit*/ false);
7949   if (OperandResult.isInvalid())
7950     return ExprError();
7951 
7952   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7953           E->getOperatorCoawaitLookup());
7954 
7955   if (LookupResult.isInvalid())
7956     return ExprError();
7957 
7958   // Always rebuild; we don't know if this needs to be injected into a new
7959   // context or if the promise type has changed.
7960   return getDerived().RebuildDependentCoawaitExpr(
7961       E->getKeywordLoc(), OperandResult.get(),
7962       cast<UnresolvedLookupExpr>(LookupResult.get()));
7963 }
7964 
7965 template<typename Derived>
7966 ExprResult
7967 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7968   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7969                                                         /*NotCopyInit*/false);
7970   if (Result.isInvalid())
7971     return ExprError();
7972 
7973   // Always rebuild; we don't know if this needs to be injected into a new
7974   // context or if the promise type has changed.
7975   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7976 }
7977 
7978 // Objective-C Statements.
7979 
7980 template<typename Derived>
7981 StmtResult
7982 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7983   // Transform the body of the @try.
7984   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7985   if (TryBody.isInvalid())
7986     return StmtError();
7987 
7988   // Transform the @catch statements (if present).
7989   bool AnyCatchChanged = false;
7990   SmallVector<Stmt*, 8> CatchStmts;
7991   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7992     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7993     if (Catch.isInvalid())
7994       return StmtError();
7995     if (Catch.get() != S->getCatchStmt(I))
7996       AnyCatchChanged = true;
7997     CatchStmts.push_back(Catch.get());
7998   }
7999 
8000   // Transform the @finally statement (if present).
8001   StmtResult Finally;
8002   if (S->getFinallyStmt()) {
8003     Finally = getDerived().TransformStmt(S->getFinallyStmt());
8004     if (Finally.isInvalid())
8005       return StmtError();
8006   }
8007 
8008   // If nothing changed, just retain this statement.
8009   if (!getDerived().AlwaysRebuild() &&
8010       TryBody.get() == S->getTryBody() &&
8011       !AnyCatchChanged &&
8012       Finally.get() == S->getFinallyStmt())
8013     return S;
8014 
8015   // Build a new statement.
8016   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8017                                            CatchStmts, Finally.get());
8018 }
8019 
8020 template<typename Derived>
8021 StmtResult
8022 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8023   // Transform the @catch parameter, if there is one.
8024   VarDecl *Var = nullptr;
8025   if (VarDecl *FromVar = S->getCatchParamDecl()) {
8026     TypeSourceInfo *TSInfo = nullptr;
8027     if (FromVar->getTypeSourceInfo()) {
8028       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8029       if (!TSInfo)
8030         return StmtError();
8031     }
8032 
8033     QualType T;
8034     if (TSInfo)
8035       T = TSInfo->getType();
8036     else {
8037       T = getDerived().TransformType(FromVar->getType());
8038       if (T.isNull())
8039         return StmtError();
8040     }
8041 
8042     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8043     if (!Var)
8044       return StmtError();
8045   }
8046 
8047   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8048   if (Body.isInvalid())
8049     return StmtError();
8050 
8051   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8052                                              S->getRParenLoc(),
8053                                              Var, Body.get());
8054 }
8055 
8056 template<typename Derived>
8057 StmtResult
8058 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8059   // Transform the body.
8060   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8061   if (Body.isInvalid())
8062     return StmtError();
8063 
8064   // If nothing changed, just retain this statement.
8065   if (!getDerived().AlwaysRebuild() &&
8066       Body.get() == S->getFinallyBody())
8067     return S;
8068 
8069   // Build a new statement.
8070   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8071                                                Body.get());
8072 }
8073 
8074 template<typename Derived>
8075 StmtResult
8076 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8077   ExprResult Operand;
8078   if (S->getThrowExpr()) {
8079     Operand = getDerived().TransformExpr(S->getThrowExpr());
8080     if (Operand.isInvalid())
8081       return StmtError();
8082   }
8083 
8084   if (!getDerived().AlwaysRebuild() &&
8085       Operand.get() == S->getThrowExpr())
8086     return S;
8087 
8088   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8089 }
8090 
8091 template<typename Derived>
8092 StmtResult
8093 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8094                                                   ObjCAtSynchronizedStmt *S) {
8095   // Transform the object we are locking.
8096   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8097   if (Object.isInvalid())
8098     return StmtError();
8099   Object =
8100     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8101                                                   Object.get());
8102   if (Object.isInvalid())
8103     return StmtError();
8104 
8105   // Transform the body.
8106   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8107   if (Body.isInvalid())
8108     return StmtError();
8109 
8110   // If nothing change, just retain the current statement.
8111   if (!getDerived().AlwaysRebuild() &&
8112       Object.get() == S->getSynchExpr() &&
8113       Body.get() == S->getSynchBody())
8114     return S;
8115 
8116   // Build a new statement.
8117   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8118                                                     Object.get(), Body.get());
8119 }
8120 
8121 template<typename Derived>
8122 StmtResult
8123 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8124                                               ObjCAutoreleasePoolStmt *S) {
8125   // Transform the body.
8126   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8127   if (Body.isInvalid())
8128     return StmtError();
8129 
8130   // If nothing changed, just retain this statement.
8131   if (!getDerived().AlwaysRebuild() &&
8132       Body.get() == S->getSubStmt())
8133     return S;
8134 
8135   // Build a new statement.
8136   return getDerived().RebuildObjCAutoreleasePoolStmt(
8137                         S->getAtLoc(), Body.get());
8138 }
8139 
8140 template<typename Derived>
8141 StmtResult
8142 TreeTransform<Derived>::TransformObjCForCollectionStmt(
8143                                                   ObjCForCollectionStmt *S) {
8144   // Transform the element statement.
8145   StmtResult Element =
8146       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8147   if (Element.isInvalid())
8148     return StmtError();
8149 
8150   // Transform the collection expression.
8151   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8152   if (Collection.isInvalid())
8153     return StmtError();
8154 
8155   // Transform the body.
8156   StmtResult Body = getDerived().TransformStmt(S->getBody());
8157   if (Body.isInvalid())
8158     return StmtError();
8159 
8160   // If nothing changed, just retain this statement.
8161   if (!getDerived().AlwaysRebuild() &&
8162       Element.get() == S->getElement() &&
8163       Collection.get() == S->getCollection() &&
8164       Body.get() == S->getBody())
8165     return S;
8166 
8167   // Build a new statement.
8168   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8169                                                    Element.get(),
8170                                                    Collection.get(),
8171                                                    S->getRParenLoc(),
8172                                                    Body.get());
8173 }
8174 
8175 template <typename Derived>
8176 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8177   // Transform the exception declaration, if any.
8178   VarDecl *Var = nullptr;
8179   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8180     TypeSourceInfo *T =
8181         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8182     if (!T)
8183       return StmtError();
8184 
8185     Var = getDerived().RebuildExceptionDecl(
8186         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8187         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8188     if (!Var || Var->isInvalidDecl())
8189       return StmtError();
8190   }
8191 
8192   // Transform the actual exception handler.
8193   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8194   if (Handler.isInvalid())
8195     return StmtError();
8196 
8197   if (!getDerived().AlwaysRebuild() && !Var &&
8198       Handler.get() == S->getHandlerBlock())
8199     return S;
8200 
8201   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8202 }
8203 
8204 template <typename Derived>
8205 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8206   // Transform the try block itself.
8207   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8208   if (TryBlock.isInvalid())
8209     return StmtError();
8210 
8211   // Transform the handlers.
8212   bool HandlerChanged = false;
8213   SmallVector<Stmt *, 8> Handlers;
8214   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8215     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8216     if (Handler.isInvalid())
8217       return StmtError();
8218 
8219     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8220     Handlers.push_back(Handler.getAs<Stmt>());
8221   }
8222 
8223   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8224       !HandlerChanged)
8225     return S;
8226 
8227   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8228                                         Handlers);
8229 }
8230 
8231 template<typename Derived>
8232 StmtResult
8233 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8234   StmtResult Init =
8235       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8236   if (Init.isInvalid())
8237     return StmtError();
8238 
8239   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8240   if (Range.isInvalid())
8241     return StmtError();
8242 
8243   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8244   if (Begin.isInvalid())
8245     return StmtError();
8246   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8247   if (End.isInvalid())
8248     return StmtError();
8249 
8250   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8251   if (Cond.isInvalid())
8252     return StmtError();
8253   if (Cond.get())
8254     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8255   if (Cond.isInvalid())
8256     return StmtError();
8257   if (Cond.get())
8258     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8259 
8260   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8261   if (Inc.isInvalid())
8262     return StmtError();
8263   if (Inc.get())
8264     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8265 
8266   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8267   if (LoopVar.isInvalid())
8268     return StmtError();
8269 
8270   StmtResult NewStmt = S;
8271   if (getDerived().AlwaysRebuild() ||
8272       Init.get() != S->getInit() ||
8273       Range.get() != S->getRangeStmt() ||
8274       Begin.get() != S->getBeginStmt() ||
8275       End.get() != S->getEndStmt() ||
8276       Cond.get() != S->getCond() ||
8277       Inc.get() != S->getInc() ||
8278       LoopVar.get() != S->getLoopVarStmt()) {
8279     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8280                                                   S->getCoawaitLoc(), Init.get(),
8281                                                   S->getColonLoc(), Range.get(),
8282                                                   Begin.get(), End.get(),
8283                                                   Cond.get(),
8284                                                   Inc.get(), LoopVar.get(),
8285                                                   S->getRParenLoc());
8286     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8287       // Might not have attached any initializer to the loop variable.
8288       getSema().ActOnInitializerError(
8289           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8290       return StmtError();
8291     }
8292   }
8293 
8294   StmtResult Body = getDerived().TransformStmt(S->getBody());
8295   if (Body.isInvalid())
8296     return StmtError();
8297 
8298   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8299   // it now so we have a new statement to attach the body to.
8300   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8301     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8302                                                   S->getCoawaitLoc(), Init.get(),
8303                                                   S->getColonLoc(), Range.get(),
8304                                                   Begin.get(), End.get(),
8305                                                   Cond.get(),
8306                                                   Inc.get(), LoopVar.get(),
8307                                                   S->getRParenLoc());
8308     if (NewStmt.isInvalid())
8309       return StmtError();
8310   }
8311 
8312   if (NewStmt.get() == S)
8313     return S;
8314 
8315   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8316 }
8317 
8318 template<typename Derived>
8319 StmtResult
8320 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8321                                                     MSDependentExistsStmt *S) {
8322   // Transform the nested-name-specifier, if any.
8323   NestedNameSpecifierLoc QualifierLoc;
8324   if (S->getQualifierLoc()) {
8325     QualifierLoc
8326       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8327     if (!QualifierLoc)
8328       return StmtError();
8329   }
8330 
8331   // Transform the declaration name.
8332   DeclarationNameInfo NameInfo = S->getNameInfo();
8333   if (NameInfo.getName()) {
8334     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8335     if (!NameInfo.getName())
8336       return StmtError();
8337   }
8338 
8339   // Check whether anything changed.
8340   if (!getDerived().AlwaysRebuild() &&
8341       QualifierLoc == S->getQualifierLoc() &&
8342       NameInfo.getName() == S->getNameInfo().getName())
8343     return S;
8344 
8345   // Determine whether this name exists, if we can.
8346   CXXScopeSpec SS;
8347   SS.Adopt(QualifierLoc);
8348   bool Dependent = false;
8349   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8350   case Sema::IER_Exists:
8351     if (S->isIfExists())
8352       break;
8353 
8354     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8355 
8356   case Sema::IER_DoesNotExist:
8357     if (S->isIfNotExists())
8358       break;
8359 
8360     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8361 
8362   case Sema::IER_Dependent:
8363     Dependent = true;
8364     break;
8365 
8366   case Sema::IER_Error:
8367     return StmtError();
8368   }
8369 
8370   // We need to continue with the instantiation, so do so now.
8371   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8372   if (SubStmt.isInvalid())
8373     return StmtError();
8374 
8375   // If we have resolved the name, just transform to the substatement.
8376   if (!Dependent)
8377     return SubStmt;
8378 
8379   // The name is still dependent, so build a dependent expression again.
8380   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8381                                                    S->isIfExists(),
8382                                                    QualifierLoc,
8383                                                    NameInfo,
8384                                                    SubStmt.get());
8385 }
8386 
8387 template<typename Derived>
8388 ExprResult
8389 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8390   NestedNameSpecifierLoc QualifierLoc;
8391   if (E->getQualifierLoc()) {
8392     QualifierLoc
8393     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8394     if (!QualifierLoc)
8395       return ExprError();
8396   }
8397 
8398   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8399     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8400   if (!PD)
8401     return ExprError();
8402 
8403   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8404   if (Base.isInvalid())
8405     return ExprError();
8406 
8407   return new (SemaRef.getASTContext())
8408       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8409                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8410                         QualifierLoc, E->getMemberLoc());
8411 }
8412 
8413 template <typename Derived>
8414 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8415     MSPropertySubscriptExpr *E) {
8416   auto BaseRes = getDerived().TransformExpr(E->getBase());
8417   if (BaseRes.isInvalid())
8418     return ExprError();
8419   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8420   if (IdxRes.isInvalid())
8421     return ExprError();
8422 
8423   if (!getDerived().AlwaysRebuild() &&
8424       BaseRes.get() == E->getBase() &&
8425       IdxRes.get() == E->getIdx())
8426     return E;
8427 
8428   return getDerived().RebuildArraySubscriptExpr(
8429       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8430 }
8431 
8432 template <typename Derived>
8433 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8434   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8435   if (TryBlock.isInvalid())
8436     return StmtError();
8437 
8438   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8439   if (Handler.isInvalid())
8440     return StmtError();
8441 
8442   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8443       Handler.get() == S->getHandler())
8444     return S;
8445 
8446   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8447                                         TryBlock.get(), Handler.get());
8448 }
8449 
8450 template <typename Derived>
8451 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8452   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8453   if (Block.isInvalid())
8454     return StmtError();
8455 
8456   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8457 }
8458 
8459 template <typename Derived>
8460 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8461   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8462   if (FilterExpr.isInvalid())
8463     return StmtError();
8464 
8465   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8466   if (Block.isInvalid())
8467     return StmtError();
8468 
8469   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8470                                            Block.get());
8471 }
8472 
8473 template <typename Derived>
8474 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8475   if (isa<SEHFinallyStmt>(Handler))
8476     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8477   else
8478     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8479 }
8480 
8481 template<typename Derived>
8482 StmtResult
8483 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8484   return S;
8485 }
8486 
8487 //===----------------------------------------------------------------------===//
8488 // OpenMP directive transformation
8489 //===----------------------------------------------------------------------===//
8490 
8491 template <typename Derived>
8492 StmtResult
8493 TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8494   // OMPCanonicalLoops are eliminated during transformation, since they will be
8495   // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8496   // after transformation.
8497   return getDerived().TransformStmt(L->getLoopStmt());
8498 }
8499 
8500 template <typename Derived>
8501 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8502     OMPExecutableDirective *D) {
8503 
8504   // Transform the clauses
8505   llvm::SmallVector<OMPClause *, 16> TClauses;
8506   ArrayRef<OMPClause *> Clauses = D->clauses();
8507   TClauses.reserve(Clauses.size());
8508   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8509        I != E; ++I) {
8510     if (*I) {
8511       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8512       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8513       getDerived().getSema().EndOpenMPClause();
8514       if (Clause)
8515         TClauses.push_back(Clause);
8516     } else {
8517       TClauses.push_back(nullptr);
8518     }
8519   }
8520   StmtResult AssociatedStmt;
8521   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8522     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8523                                                   /*CurScope=*/nullptr);
8524     StmtResult Body;
8525     {
8526       Sema::CompoundScopeRAII CompoundScope(getSema());
8527       Stmt *CS;
8528       if (D->getDirectiveKind() == OMPD_atomic ||
8529           D->getDirectiveKind() == OMPD_critical ||
8530           D->getDirectiveKind() == OMPD_section ||
8531           D->getDirectiveKind() == OMPD_master)
8532         CS = D->getAssociatedStmt();
8533       else
8534         CS = D->getRawStmt();
8535       Body = getDerived().TransformStmt(CS);
8536       if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8537           getSema().getLangOpts().OpenMPIRBuilder)
8538         Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8539     }
8540     AssociatedStmt =
8541         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8542     if (AssociatedStmt.isInvalid()) {
8543       return StmtError();
8544     }
8545   }
8546   if (TClauses.size() != Clauses.size()) {
8547     return StmtError();
8548   }
8549 
8550   // Transform directive name for 'omp critical' directive.
8551   DeclarationNameInfo DirName;
8552   if (D->getDirectiveKind() == OMPD_critical) {
8553     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8554     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8555   }
8556   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8557   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8558     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8559   } else if (D->getDirectiveKind() == OMPD_cancel) {
8560     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8561   }
8562 
8563   return getDerived().RebuildOMPExecutableDirective(
8564       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8565       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8566 }
8567 
8568 template <typename Derived>
8569 StmtResult
8570 TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8571   // TODO: Fix This
8572   SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8573       << getOpenMPDirectiveName(D->getDirectiveKind());
8574   return StmtError();
8575 }
8576 
8577 template <typename Derived>
8578 StmtResult
8579 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8580   DeclarationNameInfo DirName;
8581   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8582                                              D->getBeginLoc());
8583   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8584   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8585   return Res;
8586 }
8587 
8588 template <typename Derived>
8589 StmtResult
8590 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8591   DeclarationNameInfo DirName;
8592   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8593                                              D->getBeginLoc());
8594   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8595   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8596   return Res;
8597 }
8598 
8599 template <typename Derived>
8600 StmtResult
8601 TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8602   DeclarationNameInfo DirName;
8603   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8604                                              nullptr, D->getBeginLoc());
8605   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8606   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8607   return Res;
8608 }
8609 
8610 template <typename Derived>
8611 StmtResult
8612 TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8613   DeclarationNameInfo DirName;
8614   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8615                                              nullptr, D->getBeginLoc());
8616   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8617   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8618   return Res;
8619 }
8620 
8621 template <typename Derived>
8622 StmtResult
8623 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8624   DeclarationNameInfo DirName;
8625   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8626                                              D->getBeginLoc());
8627   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8628   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8629   return Res;
8630 }
8631 
8632 template <typename Derived>
8633 StmtResult
8634 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8635   DeclarationNameInfo DirName;
8636   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8637                                              D->getBeginLoc());
8638   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8639   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8640   return Res;
8641 }
8642 
8643 template <typename Derived>
8644 StmtResult
8645 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8646   DeclarationNameInfo DirName;
8647   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8648                                              D->getBeginLoc());
8649   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8650   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8651   return Res;
8652 }
8653 
8654 template <typename Derived>
8655 StmtResult
8656 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8657   DeclarationNameInfo DirName;
8658   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8659                                              D->getBeginLoc());
8660   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8661   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8662   return Res;
8663 }
8664 
8665 template <typename Derived>
8666 StmtResult
8667 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8668   DeclarationNameInfo DirName;
8669   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8670                                              D->getBeginLoc());
8671   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8672   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8673   return Res;
8674 }
8675 
8676 template <typename Derived>
8677 StmtResult
8678 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8679   DeclarationNameInfo DirName;
8680   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8681                                              D->getBeginLoc());
8682   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8683   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8684   return Res;
8685 }
8686 
8687 template <typename Derived>
8688 StmtResult
8689 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8690   getDerived().getSema().StartOpenMPDSABlock(
8691       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8692   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8693   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8694   return Res;
8695 }
8696 
8697 template <typename Derived>
8698 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8699     OMPParallelForDirective *D) {
8700   DeclarationNameInfo DirName;
8701   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8702                                              nullptr, D->getBeginLoc());
8703   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8704   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8705   return Res;
8706 }
8707 
8708 template <typename Derived>
8709 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8710     OMPParallelForSimdDirective *D) {
8711   DeclarationNameInfo DirName;
8712   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8713                                              nullptr, D->getBeginLoc());
8714   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8715   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8716   return Res;
8717 }
8718 
8719 template <typename Derived>
8720 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8721     OMPParallelMasterDirective *D) {
8722   DeclarationNameInfo DirName;
8723   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8724                                              nullptr, D->getBeginLoc());
8725   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8726   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8727   return Res;
8728 }
8729 
8730 template <typename Derived>
8731 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8732     OMPParallelSectionsDirective *D) {
8733   DeclarationNameInfo DirName;
8734   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8735                                              nullptr, D->getBeginLoc());
8736   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8737   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8738   return Res;
8739 }
8740 
8741 template <typename Derived>
8742 StmtResult
8743 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8744   DeclarationNameInfo DirName;
8745   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8746                                              D->getBeginLoc());
8747   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8748   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8749   return Res;
8750 }
8751 
8752 template <typename Derived>
8753 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8754     OMPTaskyieldDirective *D) {
8755   DeclarationNameInfo DirName;
8756   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8757                                              D->getBeginLoc());
8758   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8759   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8760   return Res;
8761 }
8762 
8763 template <typename Derived>
8764 StmtResult
8765 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8766   DeclarationNameInfo DirName;
8767   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8768                                              D->getBeginLoc());
8769   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8770   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8771   return Res;
8772 }
8773 
8774 template <typename Derived>
8775 StmtResult
8776 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8777   DeclarationNameInfo DirName;
8778   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8779                                              D->getBeginLoc());
8780   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8781   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8782   return Res;
8783 }
8784 
8785 template <typename Derived>
8786 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8787     OMPTaskgroupDirective *D) {
8788   DeclarationNameInfo DirName;
8789   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8790                                              D->getBeginLoc());
8791   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8792   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8793   return Res;
8794 }
8795 
8796 template <typename Derived>
8797 StmtResult
8798 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8799   DeclarationNameInfo DirName;
8800   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8801                                              D->getBeginLoc());
8802   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8803   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8804   return Res;
8805 }
8806 
8807 template <typename Derived>
8808 StmtResult
8809 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
8810   DeclarationNameInfo DirName;
8811   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
8812                                              D->getBeginLoc());
8813   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8814   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8815   return Res;
8816 }
8817 
8818 template <typename Derived>
8819 StmtResult
8820 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
8821   DeclarationNameInfo DirName;
8822   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
8823                                              D->getBeginLoc());
8824   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8825   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8826   return Res;
8827 }
8828 
8829 template <typename Derived>
8830 StmtResult
8831 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8832   DeclarationNameInfo DirName;
8833   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8834                                              D->getBeginLoc());
8835   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8836   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8837   return Res;
8838 }
8839 
8840 template <typename Derived>
8841 StmtResult
8842 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8843   DeclarationNameInfo DirName;
8844   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8845                                              D->getBeginLoc());
8846   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8847   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8848   return Res;
8849 }
8850 
8851 template <typename Derived>
8852 StmtResult
8853 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8854   DeclarationNameInfo DirName;
8855   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8856                                              D->getBeginLoc());
8857   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8858   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8859   return Res;
8860 }
8861 
8862 template <typename Derived>
8863 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8864     OMPTargetDataDirective *D) {
8865   DeclarationNameInfo DirName;
8866   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8867                                              D->getBeginLoc());
8868   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8869   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8870   return Res;
8871 }
8872 
8873 template <typename Derived>
8874 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8875     OMPTargetEnterDataDirective *D) {
8876   DeclarationNameInfo DirName;
8877   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8878                                              nullptr, D->getBeginLoc());
8879   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8880   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8881   return Res;
8882 }
8883 
8884 template <typename Derived>
8885 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8886     OMPTargetExitDataDirective *D) {
8887   DeclarationNameInfo DirName;
8888   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8889                                              nullptr, D->getBeginLoc());
8890   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8891   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8892   return Res;
8893 }
8894 
8895 template <typename Derived>
8896 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8897     OMPTargetParallelDirective *D) {
8898   DeclarationNameInfo DirName;
8899   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8900                                              nullptr, D->getBeginLoc());
8901   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8902   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8903   return Res;
8904 }
8905 
8906 template <typename Derived>
8907 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8908     OMPTargetParallelForDirective *D) {
8909   DeclarationNameInfo DirName;
8910   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8911                                              nullptr, D->getBeginLoc());
8912   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8913   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8914   return Res;
8915 }
8916 
8917 template <typename Derived>
8918 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8919     OMPTargetUpdateDirective *D) {
8920   DeclarationNameInfo DirName;
8921   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8922                                              nullptr, D->getBeginLoc());
8923   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8924   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8925   return Res;
8926 }
8927 
8928 template <typename Derived>
8929 StmtResult
8930 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8931   DeclarationNameInfo DirName;
8932   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8933                                              D->getBeginLoc());
8934   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8935   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8936   return Res;
8937 }
8938 
8939 template <typename Derived>
8940 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8941     OMPCancellationPointDirective *D) {
8942   DeclarationNameInfo DirName;
8943   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8944                                              nullptr, D->getBeginLoc());
8945   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8946   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8947   return Res;
8948 }
8949 
8950 template <typename Derived>
8951 StmtResult
8952 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8953   DeclarationNameInfo DirName;
8954   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8955                                              D->getBeginLoc());
8956   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8957   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8958   return Res;
8959 }
8960 
8961 template <typename Derived>
8962 StmtResult
8963 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8964   DeclarationNameInfo DirName;
8965   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8966                                              D->getBeginLoc());
8967   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8968   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8969   return Res;
8970 }
8971 
8972 template <typename Derived>
8973 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8974     OMPTaskLoopSimdDirective *D) {
8975   DeclarationNameInfo DirName;
8976   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8977                                              nullptr, D->getBeginLoc());
8978   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8979   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8980   return Res;
8981 }
8982 
8983 template <typename Derived>
8984 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8985     OMPMasterTaskLoopDirective *D) {
8986   DeclarationNameInfo DirName;
8987   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8988                                              nullptr, D->getBeginLoc());
8989   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8990   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8991   return Res;
8992 }
8993 
8994 template <typename Derived>
8995 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
8996     OMPMasterTaskLoopSimdDirective *D) {
8997   DeclarationNameInfo DirName;
8998   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8999                                              nullptr, D->getBeginLoc());
9000   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9001   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9002   return Res;
9003 }
9004 
9005 template <typename Derived>
9006 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9007     OMPParallelMasterTaskLoopDirective *D) {
9008   DeclarationNameInfo DirName;
9009   getDerived().getSema().StartOpenMPDSABlock(
9010       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9011   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9012   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9013   return Res;
9014 }
9015 
9016 template <typename Derived>
9017 StmtResult
9018 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9019     OMPParallelMasterTaskLoopSimdDirective *D) {
9020   DeclarationNameInfo DirName;
9021   getDerived().getSema().StartOpenMPDSABlock(
9022       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9023   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9024   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9025   return Res;
9026 }
9027 
9028 template <typename Derived>
9029 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9030     OMPDistributeDirective *D) {
9031   DeclarationNameInfo DirName;
9032   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9033                                              D->getBeginLoc());
9034   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9035   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9036   return Res;
9037 }
9038 
9039 template <typename Derived>
9040 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9041     OMPDistributeParallelForDirective *D) {
9042   DeclarationNameInfo DirName;
9043   getDerived().getSema().StartOpenMPDSABlock(
9044       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9045   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9046   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9047   return Res;
9048 }
9049 
9050 template <typename Derived>
9051 StmtResult
9052 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9053     OMPDistributeParallelForSimdDirective *D) {
9054   DeclarationNameInfo DirName;
9055   getDerived().getSema().StartOpenMPDSABlock(
9056       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9057   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9058   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9059   return Res;
9060 }
9061 
9062 template <typename Derived>
9063 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9064     OMPDistributeSimdDirective *D) {
9065   DeclarationNameInfo DirName;
9066   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9067                                              nullptr, D->getBeginLoc());
9068   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9069   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9070   return Res;
9071 }
9072 
9073 template <typename Derived>
9074 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9075     OMPTargetParallelForSimdDirective *D) {
9076   DeclarationNameInfo DirName;
9077   getDerived().getSema().StartOpenMPDSABlock(
9078       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9079   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9080   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9081   return Res;
9082 }
9083 
9084 template <typename Derived>
9085 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9086     OMPTargetSimdDirective *D) {
9087   DeclarationNameInfo DirName;
9088   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9089                                              D->getBeginLoc());
9090   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9091   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9092   return Res;
9093 }
9094 
9095 template <typename Derived>
9096 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9097     OMPTeamsDistributeDirective *D) {
9098   DeclarationNameInfo DirName;
9099   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9100                                              nullptr, D->getBeginLoc());
9101   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9102   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9103   return Res;
9104 }
9105 
9106 template <typename Derived>
9107 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9108     OMPTeamsDistributeSimdDirective *D) {
9109   DeclarationNameInfo DirName;
9110   getDerived().getSema().StartOpenMPDSABlock(
9111       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9112   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9113   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9114   return Res;
9115 }
9116 
9117 template <typename Derived>
9118 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9119     OMPTeamsDistributeParallelForSimdDirective *D) {
9120   DeclarationNameInfo DirName;
9121   getDerived().getSema().StartOpenMPDSABlock(
9122       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9123       D->getBeginLoc());
9124   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9125   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9126   return Res;
9127 }
9128 
9129 template <typename Derived>
9130 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9131     OMPTeamsDistributeParallelForDirective *D) {
9132   DeclarationNameInfo DirName;
9133   getDerived().getSema().StartOpenMPDSABlock(
9134       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9135   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9136   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9137   return Res;
9138 }
9139 
9140 template <typename Derived>
9141 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9142     OMPTargetTeamsDirective *D) {
9143   DeclarationNameInfo DirName;
9144   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9145                                              nullptr, D->getBeginLoc());
9146   auto Res = getDerived().TransformOMPExecutableDirective(D);
9147   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9148   return Res;
9149 }
9150 
9151 template <typename Derived>
9152 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9153     OMPTargetTeamsDistributeDirective *D) {
9154   DeclarationNameInfo DirName;
9155   getDerived().getSema().StartOpenMPDSABlock(
9156       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9157   auto Res = getDerived().TransformOMPExecutableDirective(D);
9158   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9159   return Res;
9160 }
9161 
9162 template <typename Derived>
9163 StmtResult
9164 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9165     OMPTargetTeamsDistributeParallelForDirective *D) {
9166   DeclarationNameInfo DirName;
9167   getDerived().getSema().StartOpenMPDSABlock(
9168       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9169       D->getBeginLoc());
9170   auto Res = getDerived().TransformOMPExecutableDirective(D);
9171   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9172   return Res;
9173 }
9174 
9175 template <typename Derived>
9176 StmtResult TreeTransform<Derived>::
9177     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9178         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9179   DeclarationNameInfo DirName;
9180   getDerived().getSema().StartOpenMPDSABlock(
9181       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9182       D->getBeginLoc());
9183   auto Res = getDerived().TransformOMPExecutableDirective(D);
9184   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9185   return Res;
9186 }
9187 
9188 template <typename Derived>
9189 StmtResult
9190 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9191     OMPTargetTeamsDistributeSimdDirective *D) {
9192   DeclarationNameInfo DirName;
9193   getDerived().getSema().StartOpenMPDSABlock(
9194       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9195   auto Res = getDerived().TransformOMPExecutableDirective(D);
9196   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9197   return Res;
9198 }
9199 
9200 template <typename Derived>
9201 StmtResult
9202 TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9203   DeclarationNameInfo DirName;
9204   getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9205                                              D->getBeginLoc());
9206   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9207   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9208   return Res;
9209 }
9210 
9211 template <typename Derived>
9212 StmtResult
9213 TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9214   DeclarationNameInfo DirName;
9215   getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9216                                              D->getBeginLoc());
9217   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9218   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9219   return Res;
9220 }
9221 
9222 template <typename Derived>
9223 StmtResult
9224 TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9225   DeclarationNameInfo DirName;
9226   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9227                                              D->getBeginLoc());
9228   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9229   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9230   return Res;
9231 }
9232 
9233 template <typename Derived>
9234 StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9235     OMPGenericLoopDirective *D) {
9236   DeclarationNameInfo DirName;
9237   getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9238                                              D->getBeginLoc());
9239   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9240   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9241   return Res;
9242 }
9243 
9244 //===----------------------------------------------------------------------===//
9245 // OpenMP clause transformation
9246 //===----------------------------------------------------------------------===//
9247 template <typename Derived>
9248 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9249   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9250   if (Cond.isInvalid())
9251     return nullptr;
9252   return getDerived().RebuildOMPIfClause(
9253       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9254       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9255 }
9256 
9257 template <typename Derived>
9258 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9259   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9260   if (Cond.isInvalid())
9261     return nullptr;
9262   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9263                                             C->getLParenLoc(), C->getEndLoc());
9264 }
9265 
9266 template <typename Derived>
9267 OMPClause *
9268 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9269   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9270   if (NumThreads.isInvalid())
9271     return nullptr;
9272   return getDerived().RebuildOMPNumThreadsClause(
9273       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9274 }
9275 
9276 template <typename Derived>
9277 OMPClause *
9278 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9279   ExprResult E = getDerived().TransformExpr(C->getSafelen());
9280   if (E.isInvalid())
9281     return nullptr;
9282   return getDerived().RebuildOMPSafelenClause(
9283       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9284 }
9285 
9286 template <typename Derived>
9287 OMPClause *
9288 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9289   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9290   if (E.isInvalid())
9291     return nullptr;
9292   return getDerived().RebuildOMPAllocatorClause(
9293       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9294 }
9295 
9296 template <typename Derived>
9297 OMPClause *
9298 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9299   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9300   if (E.isInvalid())
9301     return nullptr;
9302   return getDerived().RebuildOMPSimdlenClause(
9303       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9304 }
9305 
9306 template <typename Derived>
9307 OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9308   SmallVector<Expr *, 4> TransformedSizes;
9309   TransformedSizes.reserve(C->getNumSizes());
9310   bool Changed = false;
9311   for (Expr *E : C->getSizesRefs()) {
9312     if (!E) {
9313       TransformedSizes.push_back(nullptr);
9314       continue;
9315     }
9316 
9317     ExprResult T = getDerived().TransformExpr(E);
9318     if (T.isInvalid())
9319       return nullptr;
9320     if (E != T.get())
9321       Changed = true;
9322     TransformedSizes.push_back(T.get());
9323   }
9324 
9325   if (!Changed && !getDerived().AlwaysRebuild())
9326     return C;
9327   return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9328                                C->getLParenLoc(), C->getEndLoc());
9329 }
9330 
9331 template <typename Derived>
9332 OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9333   if (!getDerived().AlwaysRebuild())
9334     return C;
9335   return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9336 }
9337 
9338 template <typename Derived>
9339 OMPClause *
9340 TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9341   ExprResult T = getDerived().TransformExpr(C->getFactor());
9342   if (T.isInvalid())
9343     return nullptr;
9344   Expr *Factor = T.get();
9345   bool Changed = Factor != C->getFactor();
9346 
9347   if (!Changed && !getDerived().AlwaysRebuild())
9348     return C;
9349   return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9350                                  C->getEndLoc());
9351 }
9352 
9353 template <typename Derived>
9354 OMPClause *
9355 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9356   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9357   if (E.isInvalid())
9358     return nullptr;
9359   return getDerived().RebuildOMPCollapseClause(
9360       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9361 }
9362 
9363 template <typename Derived>
9364 OMPClause *
9365 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9366   return getDerived().RebuildOMPDefaultClause(
9367       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9368       C->getLParenLoc(), C->getEndLoc());
9369 }
9370 
9371 template <typename Derived>
9372 OMPClause *
9373 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9374   return getDerived().RebuildOMPProcBindClause(
9375       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9376       C->getLParenLoc(), C->getEndLoc());
9377 }
9378 
9379 template <typename Derived>
9380 OMPClause *
9381 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9382   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9383   if (E.isInvalid())
9384     return nullptr;
9385   return getDerived().RebuildOMPScheduleClause(
9386       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9387       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9388       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9389       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9390 }
9391 
9392 template <typename Derived>
9393 OMPClause *
9394 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9395   ExprResult E;
9396   if (auto *Num = C->getNumForLoops()) {
9397     E = getDerived().TransformExpr(Num);
9398     if (E.isInvalid())
9399       return nullptr;
9400   }
9401   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9402                                               C->getLParenLoc(), E.get());
9403 }
9404 
9405 template <typename Derived>
9406 OMPClause *
9407 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9408   ExprResult E;
9409   if (Expr *Evt = C->getEventHandler()) {
9410     E = getDerived().TransformExpr(Evt);
9411     if (E.isInvalid())
9412       return nullptr;
9413   }
9414   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9415                                              C->getLParenLoc(), C->getEndLoc());
9416 }
9417 
9418 template <typename Derived>
9419 OMPClause *
9420 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9421   // No need to rebuild this clause, no template-dependent parameters.
9422   return C;
9423 }
9424 
9425 template <typename Derived>
9426 OMPClause *
9427 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9428   // No need to rebuild this clause, no template-dependent parameters.
9429   return C;
9430 }
9431 
9432 template <typename Derived>
9433 OMPClause *
9434 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9435   // No need to rebuild this clause, no template-dependent parameters.
9436   return C;
9437 }
9438 
9439 template <typename Derived>
9440 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9441   // No need to rebuild this clause, no template-dependent parameters.
9442   return C;
9443 }
9444 
9445 template <typename Derived>
9446 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9447   // No need to rebuild this clause, no template-dependent parameters.
9448   return C;
9449 }
9450 
9451 template <typename Derived>
9452 OMPClause *
9453 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9454   // No need to rebuild this clause, no template-dependent parameters.
9455   return C;
9456 }
9457 
9458 template <typename Derived>
9459 OMPClause *
9460 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9461   // No need to rebuild this clause, no template-dependent parameters.
9462   return C;
9463 }
9464 
9465 template <typename Derived>
9466 OMPClause *
9467 TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9468   // No need to rebuild this clause, no template-dependent parameters.
9469   return C;
9470 }
9471 
9472 template <typename Derived>
9473 OMPClause *
9474 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9475   // No need to rebuild this clause, no template-dependent parameters.
9476   return C;
9477 }
9478 
9479 template <typename Derived>
9480 OMPClause *
9481 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9482   // No need to rebuild this clause, no template-dependent parameters.
9483   return C;
9484 }
9485 
9486 template <typename Derived>
9487 OMPClause *
9488 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9489   // No need to rebuild this clause, no template-dependent parameters.
9490   return C;
9491 }
9492 
9493 template <typename Derived>
9494 OMPClause *
9495 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9496   // No need to rebuild this clause, no template-dependent parameters.
9497   return C;
9498 }
9499 
9500 template <typename Derived>
9501 OMPClause *
9502 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9503   // No need to rebuild this clause, no template-dependent parameters.
9504   return C;
9505 }
9506 
9507 template <typename Derived>
9508 OMPClause *
9509 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9510   // No need to rebuild this clause, no template-dependent parameters.
9511   return C;
9512 }
9513 
9514 template <typename Derived>
9515 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9516   // No need to rebuild this clause, no template-dependent parameters.
9517   return C;
9518 }
9519 
9520 template <typename Derived>
9521 OMPClause *
9522 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9523   // No need to rebuild this clause, no template-dependent parameters.
9524   return C;
9525 }
9526 
9527 template <typename Derived>
9528 OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9529   ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9530   if (IVR.isInvalid())
9531     return nullptr;
9532 
9533   llvm::SmallVector<Expr *, 8> PrefExprs;
9534   PrefExprs.reserve(C->varlist_size() - 1);
9535   for (Expr *E : llvm::drop_begin(C->varlists())) {
9536     ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9537     if (ER.isInvalid())
9538       return nullptr;
9539     PrefExprs.push_back(ER.get());
9540   }
9541   return getDerived().RebuildOMPInitClause(
9542       IVR.get(), PrefExprs, C->getIsTarget(), C->getIsTargetSync(),
9543       C->getBeginLoc(), C->getLParenLoc(), C->getVarLoc(), C->getEndLoc());
9544 }
9545 
9546 template <typename Derived>
9547 OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9548   ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9549   if (ER.isInvalid())
9550     return nullptr;
9551   return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9552                                           C->getLParenLoc(), C->getVarLoc(),
9553                                           C->getEndLoc());
9554 }
9555 
9556 template <typename Derived>
9557 OMPClause *
9558 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9559   ExprResult ER;
9560   if (Expr *IV = C->getInteropVar()) {
9561     ER = getDerived().TransformExpr(IV);
9562     if (ER.isInvalid())
9563       return nullptr;
9564   }
9565   return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9566                                               C->getLParenLoc(), C->getVarLoc(),
9567                                               C->getEndLoc());
9568 }
9569 
9570 template <typename Derived>
9571 OMPClause *
9572 TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9573   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9574   if (Cond.isInvalid())
9575     return nullptr;
9576   return getDerived().RebuildOMPNovariantsClause(
9577       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9578 }
9579 
9580 template <typename Derived>
9581 OMPClause *
9582 TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9583   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9584   if (Cond.isInvalid())
9585     return nullptr;
9586   return getDerived().RebuildOMPNocontextClause(
9587       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9588 }
9589 
9590 template <typename Derived>
9591 OMPClause *
9592 TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9593   ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9594   if (ThreadID.isInvalid())
9595     return nullptr;
9596   return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9597                                              C->getLParenLoc(), C->getEndLoc());
9598 }
9599 
9600 template <typename Derived>
9601 OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9602   ExprResult E = getDerived().TransformExpr(C->getAlignment());
9603   if (E.isInvalid())
9604     return nullptr;
9605   return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9606                                             C->getLParenLoc(), C->getEndLoc());
9607 }
9608 
9609 template <typename Derived>
9610 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9611     OMPUnifiedAddressClause *C) {
9612   llvm_unreachable("unified_address clause cannot appear in dependent context");
9613 }
9614 
9615 template <typename Derived>
9616 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9617     OMPUnifiedSharedMemoryClause *C) {
9618   llvm_unreachable(
9619       "unified_shared_memory clause cannot appear in dependent context");
9620 }
9621 
9622 template <typename Derived>
9623 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9624     OMPReverseOffloadClause *C) {
9625   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
9626 }
9627 
9628 template <typename Derived>
9629 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9630     OMPDynamicAllocatorsClause *C) {
9631   llvm_unreachable(
9632       "dynamic_allocators clause cannot appear in dependent context");
9633 }
9634 
9635 template <typename Derived>
9636 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9637     OMPAtomicDefaultMemOrderClause *C) {
9638   llvm_unreachable(
9639       "atomic_default_mem_order clause cannot appear in dependent context");
9640 }
9641 
9642 template <typename Derived>
9643 OMPClause *
9644 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9645   llvm::SmallVector<Expr *, 16> Vars;
9646   Vars.reserve(C->varlist_size());
9647   for (auto *VE : C->varlists()) {
9648     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9649     if (EVar.isInvalid())
9650       return nullptr;
9651     Vars.push_back(EVar.get());
9652   }
9653   return getDerived().RebuildOMPPrivateClause(
9654       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9655 }
9656 
9657 template <typename Derived>
9658 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
9659     OMPFirstprivateClause *C) {
9660   llvm::SmallVector<Expr *, 16> Vars;
9661   Vars.reserve(C->varlist_size());
9662   for (auto *VE : C->varlists()) {
9663     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9664     if (EVar.isInvalid())
9665       return nullptr;
9666     Vars.push_back(EVar.get());
9667   }
9668   return getDerived().RebuildOMPFirstprivateClause(
9669       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9670 }
9671 
9672 template <typename Derived>
9673 OMPClause *
9674 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
9675   llvm::SmallVector<Expr *, 16> Vars;
9676   Vars.reserve(C->varlist_size());
9677   for (auto *VE : C->varlists()) {
9678     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9679     if (EVar.isInvalid())
9680       return nullptr;
9681     Vars.push_back(EVar.get());
9682   }
9683   return getDerived().RebuildOMPLastprivateClause(
9684       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
9685       C->getLParenLoc(), C->getEndLoc());
9686 }
9687 
9688 template <typename Derived>
9689 OMPClause *
9690 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
9691   llvm::SmallVector<Expr *, 16> Vars;
9692   Vars.reserve(C->varlist_size());
9693   for (auto *VE : C->varlists()) {
9694     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9695     if (EVar.isInvalid())
9696       return nullptr;
9697     Vars.push_back(EVar.get());
9698   }
9699   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
9700                                              C->getLParenLoc(), C->getEndLoc());
9701 }
9702 
9703 template <typename Derived>
9704 OMPClause *
9705 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
9706   llvm::SmallVector<Expr *, 16> Vars;
9707   Vars.reserve(C->varlist_size());
9708   for (auto *VE : C->varlists()) {
9709     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9710     if (EVar.isInvalid())
9711       return nullptr;
9712     Vars.push_back(EVar.get());
9713   }
9714   CXXScopeSpec ReductionIdScopeSpec;
9715   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9716 
9717   DeclarationNameInfo NameInfo = C->getNameInfo();
9718   if (NameInfo.getName()) {
9719     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9720     if (!NameInfo.getName())
9721       return nullptr;
9722   }
9723   // Build a list of all UDR decls with the same names ranged by the Scopes.
9724   // The Scope boundary is a duplication of the previous decl.
9725   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9726   for (auto *E : C->reduction_ops()) {
9727     // Transform all the decls.
9728     if (E) {
9729       auto *ULE = cast<UnresolvedLookupExpr>(E);
9730       UnresolvedSet<8> Decls;
9731       for (auto *D : ULE->decls()) {
9732         NamedDecl *InstD =
9733             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9734         Decls.addDecl(InstD, InstD->getAccess());
9735       }
9736       UnresolvedReductions.push_back(
9737        UnresolvedLookupExpr::Create(
9738           SemaRef.Context, /*NamingClass=*/nullptr,
9739           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
9740           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
9741           Decls.begin(), Decls.end()));
9742     } else
9743       UnresolvedReductions.push_back(nullptr);
9744   }
9745   return getDerived().RebuildOMPReductionClause(
9746       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
9747       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
9748       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9749 }
9750 
9751 template <typename Derived>
9752 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
9753     OMPTaskReductionClause *C) {
9754   llvm::SmallVector<Expr *, 16> Vars;
9755   Vars.reserve(C->varlist_size());
9756   for (auto *VE : C->varlists()) {
9757     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9758     if (EVar.isInvalid())
9759       return nullptr;
9760     Vars.push_back(EVar.get());
9761   }
9762   CXXScopeSpec ReductionIdScopeSpec;
9763   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9764 
9765   DeclarationNameInfo NameInfo = C->getNameInfo();
9766   if (NameInfo.getName()) {
9767     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9768     if (!NameInfo.getName())
9769       return nullptr;
9770   }
9771   // Build a list of all UDR decls with the same names ranged by the Scopes.
9772   // The Scope boundary is a duplication of the previous decl.
9773   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9774   for (auto *E : C->reduction_ops()) {
9775     // Transform all the decls.
9776     if (E) {
9777       auto *ULE = cast<UnresolvedLookupExpr>(E);
9778       UnresolvedSet<8> Decls;
9779       for (auto *D : ULE->decls()) {
9780         NamedDecl *InstD =
9781             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9782         Decls.addDecl(InstD, InstD->getAccess());
9783       }
9784       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9785           SemaRef.Context, /*NamingClass=*/nullptr,
9786           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9787           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9788     } else
9789       UnresolvedReductions.push_back(nullptr);
9790   }
9791   return getDerived().RebuildOMPTaskReductionClause(
9792       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9793       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9794 }
9795 
9796 template <typename Derived>
9797 OMPClause *
9798 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
9799   llvm::SmallVector<Expr *, 16> Vars;
9800   Vars.reserve(C->varlist_size());
9801   for (auto *VE : C->varlists()) {
9802     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9803     if (EVar.isInvalid())
9804       return nullptr;
9805     Vars.push_back(EVar.get());
9806   }
9807   CXXScopeSpec ReductionIdScopeSpec;
9808   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9809 
9810   DeclarationNameInfo NameInfo = C->getNameInfo();
9811   if (NameInfo.getName()) {
9812     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9813     if (!NameInfo.getName())
9814       return nullptr;
9815   }
9816   // Build a list of all UDR decls with the same names ranged by the Scopes.
9817   // The Scope boundary is a duplication of the previous decl.
9818   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9819   for (auto *E : C->reduction_ops()) {
9820     // Transform all the decls.
9821     if (E) {
9822       auto *ULE = cast<UnresolvedLookupExpr>(E);
9823       UnresolvedSet<8> Decls;
9824       for (auto *D : ULE->decls()) {
9825         NamedDecl *InstD =
9826             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9827         Decls.addDecl(InstD, InstD->getAccess());
9828       }
9829       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9830           SemaRef.Context, /*NamingClass=*/nullptr,
9831           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9832           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9833     } else
9834       UnresolvedReductions.push_back(nullptr);
9835   }
9836   return getDerived().RebuildOMPInReductionClause(
9837       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9838       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9839 }
9840 
9841 template <typename Derived>
9842 OMPClause *
9843 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
9844   llvm::SmallVector<Expr *, 16> Vars;
9845   Vars.reserve(C->varlist_size());
9846   for (auto *VE : C->varlists()) {
9847     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9848     if (EVar.isInvalid())
9849       return nullptr;
9850     Vars.push_back(EVar.get());
9851   }
9852   ExprResult Step = getDerived().TransformExpr(C->getStep());
9853   if (Step.isInvalid())
9854     return nullptr;
9855   return getDerived().RebuildOMPLinearClause(
9856       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
9857       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
9858 }
9859 
9860 template <typename Derived>
9861 OMPClause *
9862 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
9863   llvm::SmallVector<Expr *, 16> Vars;
9864   Vars.reserve(C->varlist_size());
9865   for (auto *VE : C->varlists()) {
9866     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9867     if (EVar.isInvalid())
9868       return nullptr;
9869     Vars.push_back(EVar.get());
9870   }
9871   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
9872   if (Alignment.isInvalid())
9873     return nullptr;
9874   return getDerived().RebuildOMPAlignedClause(
9875       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
9876       C->getColonLoc(), C->getEndLoc());
9877 }
9878 
9879 template <typename Derived>
9880 OMPClause *
9881 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
9882   llvm::SmallVector<Expr *, 16> Vars;
9883   Vars.reserve(C->varlist_size());
9884   for (auto *VE : C->varlists()) {
9885     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9886     if (EVar.isInvalid())
9887       return nullptr;
9888     Vars.push_back(EVar.get());
9889   }
9890   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
9891                                              C->getLParenLoc(), C->getEndLoc());
9892 }
9893 
9894 template <typename Derived>
9895 OMPClause *
9896 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
9897   llvm::SmallVector<Expr *, 16> Vars;
9898   Vars.reserve(C->varlist_size());
9899   for (auto *VE : C->varlists()) {
9900     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9901     if (EVar.isInvalid())
9902       return nullptr;
9903     Vars.push_back(EVar.get());
9904   }
9905   return getDerived().RebuildOMPCopyprivateClause(
9906       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9907 }
9908 
9909 template <typename Derived>
9910 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
9911   llvm::SmallVector<Expr *, 16> Vars;
9912   Vars.reserve(C->varlist_size());
9913   for (auto *VE : C->varlists()) {
9914     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9915     if (EVar.isInvalid())
9916       return nullptr;
9917     Vars.push_back(EVar.get());
9918   }
9919   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9920                                             C->getLParenLoc(), C->getEndLoc());
9921 }
9922 
9923 template <typename Derived>
9924 OMPClause *
9925 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
9926   ExprResult E = getDerived().TransformExpr(C->getDepobj());
9927   if (E.isInvalid())
9928     return nullptr;
9929   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
9930                                              C->getLParenLoc(), C->getEndLoc());
9931 }
9932 
9933 template <typename Derived>
9934 OMPClause *
9935 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9936   llvm::SmallVector<Expr *, 16> Vars;
9937   Expr *DepModifier = C->getModifier();
9938   if (DepModifier) {
9939     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
9940     if (DepModRes.isInvalid())
9941       return nullptr;
9942     DepModifier = DepModRes.get();
9943   }
9944   Vars.reserve(C->varlist_size());
9945   for (auto *VE : C->varlists()) {
9946     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9947     if (EVar.isInvalid())
9948       return nullptr;
9949     Vars.push_back(EVar.get());
9950   }
9951   return getDerived().RebuildOMPDependClause(
9952       DepModifier, C->getDependencyKind(), C->getDependencyLoc(),
9953       C->getColonLoc(), Vars, C->getBeginLoc(), C->getLParenLoc(),
9954       C->getEndLoc());
9955 }
9956 
9957 template <typename Derived>
9958 OMPClause *
9959 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9960   ExprResult E = getDerived().TransformExpr(C->getDevice());
9961   if (E.isInvalid())
9962     return nullptr;
9963   return getDerived().RebuildOMPDeviceClause(
9964       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9965       C->getModifierLoc(), C->getEndLoc());
9966 }
9967 
9968 template <typename Derived, class T>
9969 bool transformOMPMappableExprListClause(
9970     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9971     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9972     DeclarationNameInfo &MapperIdInfo,
9973     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9974   // Transform expressions in the list.
9975   Vars.reserve(C->varlist_size());
9976   for (auto *VE : C->varlists()) {
9977     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9978     if (EVar.isInvalid())
9979       return true;
9980     Vars.push_back(EVar.get());
9981   }
9982   // Transform mapper scope specifier and identifier.
9983   NestedNameSpecifierLoc QualifierLoc;
9984   if (C->getMapperQualifierLoc()) {
9985     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9986         C->getMapperQualifierLoc());
9987     if (!QualifierLoc)
9988       return true;
9989   }
9990   MapperIdScopeSpec.Adopt(QualifierLoc);
9991   MapperIdInfo = C->getMapperIdInfo();
9992   if (MapperIdInfo.getName()) {
9993     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9994     if (!MapperIdInfo.getName())
9995       return true;
9996   }
9997   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9998   // the previous user-defined mapper lookup in dependent environment.
9999   for (auto *E : C->mapperlists()) {
10000     // Transform all the decls.
10001     if (E) {
10002       auto *ULE = cast<UnresolvedLookupExpr>(E);
10003       UnresolvedSet<8> Decls;
10004       for (auto *D : ULE->decls()) {
10005         NamedDecl *InstD =
10006             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10007         Decls.addDecl(InstD, InstD->getAccess());
10008       }
10009       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10010           TT.getSema().Context, /*NamingClass=*/nullptr,
10011           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10012           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10013           Decls.end()));
10014     } else {
10015       UnresolvedMappers.push_back(nullptr);
10016     }
10017   }
10018   return false;
10019 }
10020 
10021 template <typename Derived>
10022 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10023   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10024   llvm::SmallVector<Expr *, 16> Vars;
10025   CXXScopeSpec MapperIdScopeSpec;
10026   DeclarationNameInfo MapperIdInfo;
10027   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10028   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10029           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10030     return nullptr;
10031   return getDerived().RebuildOMPMapClause(
10032       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
10033       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
10034       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10035 }
10036 
10037 template <typename Derived>
10038 OMPClause *
10039 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10040   Expr *Allocator = C->getAllocator();
10041   if (Allocator) {
10042     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10043     if (AllocatorRes.isInvalid())
10044       return nullptr;
10045     Allocator = AllocatorRes.get();
10046   }
10047   llvm::SmallVector<Expr *, 16> Vars;
10048   Vars.reserve(C->varlist_size());
10049   for (auto *VE : C->varlists()) {
10050     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10051     if (EVar.isInvalid())
10052       return nullptr;
10053     Vars.push_back(EVar.get());
10054   }
10055   return getDerived().RebuildOMPAllocateClause(
10056       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10057       C->getEndLoc());
10058 }
10059 
10060 template <typename Derived>
10061 OMPClause *
10062 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10063   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10064   if (E.isInvalid())
10065     return nullptr;
10066   return getDerived().RebuildOMPNumTeamsClause(
10067       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10068 }
10069 
10070 template <typename Derived>
10071 OMPClause *
10072 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10073   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10074   if (E.isInvalid())
10075     return nullptr;
10076   return getDerived().RebuildOMPThreadLimitClause(
10077       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10078 }
10079 
10080 template <typename Derived>
10081 OMPClause *
10082 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10083   ExprResult E = getDerived().TransformExpr(C->getPriority());
10084   if (E.isInvalid())
10085     return nullptr;
10086   return getDerived().RebuildOMPPriorityClause(
10087       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10088 }
10089 
10090 template <typename Derived>
10091 OMPClause *
10092 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10093   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10094   if (E.isInvalid())
10095     return nullptr;
10096   return getDerived().RebuildOMPGrainsizeClause(
10097       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10098 }
10099 
10100 template <typename Derived>
10101 OMPClause *
10102 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10103   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10104   if (E.isInvalid())
10105     return nullptr;
10106   return getDerived().RebuildOMPNumTasksClause(
10107       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10108 }
10109 
10110 template <typename Derived>
10111 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10112   ExprResult E = getDerived().TransformExpr(C->getHint());
10113   if (E.isInvalid())
10114     return nullptr;
10115   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10116                                            C->getLParenLoc(), C->getEndLoc());
10117 }
10118 
10119 template <typename Derived>
10120 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10121     OMPDistScheduleClause *C) {
10122   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10123   if (E.isInvalid())
10124     return nullptr;
10125   return getDerived().RebuildOMPDistScheduleClause(
10126       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10127       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10128 }
10129 
10130 template <typename Derived>
10131 OMPClause *
10132 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10133   // Rebuild Defaultmap Clause since we need to invoke the checking of
10134   // defaultmap(none:variable-category) after template initialization.
10135   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10136                                                  C->getDefaultmapKind(),
10137                                                  C->getBeginLoc(),
10138                                                  C->getLParenLoc(),
10139                                                  C->getDefaultmapModifierLoc(),
10140                                                  C->getDefaultmapKindLoc(),
10141                                                  C->getEndLoc());
10142 }
10143 
10144 template <typename Derived>
10145 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10146   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10147   llvm::SmallVector<Expr *, 16> Vars;
10148   CXXScopeSpec MapperIdScopeSpec;
10149   DeclarationNameInfo MapperIdInfo;
10150   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10151   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10152           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10153     return nullptr;
10154   return getDerived().RebuildOMPToClause(
10155       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10156       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10157 }
10158 
10159 template <typename Derived>
10160 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10161   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10162   llvm::SmallVector<Expr *, 16> Vars;
10163   CXXScopeSpec MapperIdScopeSpec;
10164   DeclarationNameInfo MapperIdInfo;
10165   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10166   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10167           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10168     return nullptr;
10169   return getDerived().RebuildOMPFromClause(
10170       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10171       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10172 }
10173 
10174 template <typename Derived>
10175 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10176     OMPUseDevicePtrClause *C) {
10177   llvm::SmallVector<Expr *, 16> Vars;
10178   Vars.reserve(C->varlist_size());
10179   for (auto *VE : C->varlists()) {
10180     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10181     if (EVar.isInvalid())
10182       return nullptr;
10183     Vars.push_back(EVar.get());
10184   }
10185   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10186   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10187 }
10188 
10189 template <typename Derived>
10190 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10191     OMPUseDeviceAddrClause *C) {
10192   llvm::SmallVector<Expr *, 16> Vars;
10193   Vars.reserve(C->varlist_size());
10194   for (auto *VE : C->varlists()) {
10195     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10196     if (EVar.isInvalid())
10197       return nullptr;
10198     Vars.push_back(EVar.get());
10199   }
10200   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10201   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10202 }
10203 
10204 template <typename Derived>
10205 OMPClause *
10206 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10207   llvm::SmallVector<Expr *, 16> Vars;
10208   Vars.reserve(C->varlist_size());
10209   for (auto *VE : C->varlists()) {
10210     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10211     if (EVar.isInvalid())
10212       return nullptr;
10213     Vars.push_back(EVar.get());
10214   }
10215   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10216   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10217 }
10218 
10219 template <typename Derived>
10220 OMPClause *
10221 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10222   llvm::SmallVector<Expr *, 16> Vars;
10223   Vars.reserve(C->varlist_size());
10224   for (auto *VE : C->varlists()) {
10225     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10226     if (EVar.isInvalid())
10227       return nullptr;
10228     Vars.push_back(EVar.get());
10229   }
10230   return getDerived().RebuildOMPNontemporalClause(
10231       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10232 }
10233 
10234 template <typename Derived>
10235 OMPClause *
10236 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10237   llvm::SmallVector<Expr *, 16> Vars;
10238   Vars.reserve(C->varlist_size());
10239   for (auto *VE : C->varlists()) {
10240     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10241     if (EVar.isInvalid())
10242       return nullptr;
10243     Vars.push_back(EVar.get());
10244   }
10245   return getDerived().RebuildOMPInclusiveClause(
10246       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10247 }
10248 
10249 template <typename Derived>
10250 OMPClause *
10251 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10252   llvm::SmallVector<Expr *, 16> Vars;
10253   Vars.reserve(C->varlist_size());
10254   for (auto *VE : C->varlists()) {
10255     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10256     if (EVar.isInvalid())
10257       return nullptr;
10258     Vars.push_back(EVar.get());
10259   }
10260   return getDerived().RebuildOMPExclusiveClause(
10261       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10262 }
10263 
10264 template <typename Derived>
10265 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10266     OMPUsesAllocatorsClause *C) {
10267   SmallVector<Sema::UsesAllocatorsData, 16> Data;
10268   Data.reserve(C->getNumberOfAllocators());
10269   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10270     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10271     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10272     if (Allocator.isInvalid())
10273       continue;
10274     ExprResult AllocatorTraits;
10275     if (Expr *AT = D.AllocatorTraits) {
10276       AllocatorTraits = getDerived().TransformExpr(AT);
10277       if (AllocatorTraits.isInvalid())
10278         continue;
10279     }
10280     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10281     NewD.Allocator = Allocator.get();
10282     NewD.AllocatorTraits = AllocatorTraits.get();
10283     NewD.LParenLoc = D.LParenLoc;
10284     NewD.RParenLoc = D.RParenLoc;
10285   }
10286   return getDerived().RebuildOMPUsesAllocatorsClause(
10287       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10288 }
10289 
10290 template <typename Derived>
10291 OMPClause *
10292 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10293   SmallVector<Expr *, 4> Locators;
10294   Locators.reserve(C->varlist_size());
10295   ExprResult ModifierRes;
10296   if (Expr *Modifier = C->getModifier()) {
10297     ModifierRes = getDerived().TransformExpr(Modifier);
10298     if (ModifierRes.isInvalid())
10299       return nullptr;
10300   }
10301   for (Expr *E : C->varlists()) {
10302     ExprResult Locator = getDerived().TransformExpr(E);
10303     if (Locator.isInvalid())
10304       continue;
10305     Locators.push_back(Locator.get());
10306   }
10307   return getDerived().RebuildOMPAffinityClause(
10308       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10309       ModifierRes.get(), Locators);
10310 }
10311 
10312 template <typename Derived>
10313 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10314   return getDerived().RebuildOMPOrderClause(C->getKind(), C->getKindKwLoc(),
10315                                             C->getBeginLoc(), C->getLParenLoc(),
10316                                             C->getEndLoc());
10317 }
10318 
10319 template <typename Derived>
10320 OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10321   return getDerived().RebuildOMPBindClause(
10322       C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10323       C->getLParenLoc(), C->getEndLoc());
10324 }
10325 
10326 //===----------------------------------------------------------------------===//
10327 // Expression transformation
10328 //===----------------------------------------------------------------------===//
10329 template<typename Derived>
10330 ExprResult
10331 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10332   return TransformExpr(E->getSubExpr());
10333 }
10334 
10335 template <typename Derived>
10336 ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10337     SYCLUniqueStableNameExpr *E) {
10338   if (!E->isTypeDependent())
10339     return E;
10340 
10341   TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10342 
10343   if (!NewT)
10344     return ExprError();
10345 
10346   if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10347     return E;
10348 
10349   return getDerived().RebuildSYCLUniqueStableNameExpr(
10350       E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10351 }
10352 
10353 template<typename Derived>
10354 ExprResult
10355 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10356   if (!E->isTypeDependent())
10357     return E;
10358 
10359   return getDerived().RebuildPredefinedExpr(E->getLocation(),
10360                                             E->getIdentKind());
10361 }
10362 
10363 template<typename Derived>
10364 ExprResult
10365 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10366   NestedNameSpecifierLoc QualifierLoc;
10367   if (E->getQualifierLoc()) {
10368     QualifierLoc
10369       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10370     if (!QualifierLoc)
10371       return ExprError();
10372   }
10373 
10374   ValueDecl *ND
10375     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10376                                                          E->getDecl()));
10377   if (!ND)
10378     return ExprError();
10379 
10380   NamedDecl *Found = ND;
10381   if (E->getFoundDecl() != E->getDecl()) {
10382     Found = cast_or_null<NamedDecl>(
10383         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10384     if (!Found)
10385       return ExprError();
10386   }
10387 
10388   DeclarationNameInfo NameInfo = E->getNameInfo();
10389   if (NameInfo.getName()) {
10390     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10391     if (!NameInfo.getName())
10392       return ExprError();
10393   }
10394 
10395   if (!getDerived().AlwaysRebuild() &&
10396       QualifierLoc == E->getQualifierLoc() &&
10397       ND == E->getDecl() &&
10398       Found == E->getFoundDecl() &&
10399       NameInfo.getName() == E->getDecl()->getDeclName() &&
10400       !E->hasExplicitTemplateArgs()) {
10401 
10402     // Mark it referenced in the new context regardless.
10403     // FIXME: this is a bit instantiation-specific.
10404     SemaRef.MarkDeclRefReferenced(E);
10405 
10406     return E;
10407   }
10408 
10409   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10410   if (E->hasExplicitTemplateArgs()) {
10411     TemplateArgs = &TransArgs;
10412     TransArgs.setLAngleLoc(E->getLAngleLoc());
10413     TransArgs.setRAngleLoc(E->getRAngleLoc());
10414     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10415                                                 E->getNumTemplateArgs(),
10416                                                 TransArgs))
10417       return ExprError();
10418   }
10419 
10420   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10421                                          Found, TemplateArgs);
10422 }
10423 
10424 template<typename Derived>
10425 ExprResult
10426 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10427   return E;
10428 }
10429 
10430 template <typename Derived>
10431 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10432     FixedPointLiteral *E) {
10433   return E;
10434 }
10435 
10436 template<typename Derived>
10437 ExprResult
10438 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10439   return E;
10440 }
10441 
10442 template<typename Derived>
10443 ExprResult
10444 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10445   return E;
10446 }
10447 
10448 template<typename Derived>
10449 ExprResult
10450 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10451   return E;
10452 }
10453 
10454 template<typename Derived>
10455 ExprResult
10456 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10457   return E;
10458 }
10459 
10460 template<typename Derived>
10461 ExprResult
10462 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10463   if (FunctionDecl *FD = E->getDirectCallee())
10464     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
10465   return SemaRef.MaybeBindToTemporary(E);
10466 }
10467 
10468 template<typename Derived>
10469 ExprResult
10470 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10471   ExprResult ControllingExpr =
10472     getDerived().TransformExpr(E->getControllingExpr());
10473   if (ControllingExpr.isInvalid())
10474     return ExprError();
10475 
10476   SmallVector<Expr *, 4> AssocExprs;
10477   SmallVector<TypeSourceInfo *, 4> AssocTypes;
10478   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10479     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10480     if (TSI) {
10481       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10482       if (!AssocType)
10483         return ExprError();
10484       AssocTypes.push_back(AssocType);
10485     } else {
10486       AssocTypes.push_back(nullptr);
10487     }
10488 
10489     ExprResult AssocExpr =
10490         getDerived().TransformExpr(Assoc.getAssociationExpr());
10491     if (AssocExpr.isInvalid())
10492       return ExprError();
10493     AssocExprs.push_back(AssocExpr.get());
10494   }
10495 
10496   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10497                                                   E->getDefaultLoc(),
10498                                                   E->getRParenLoc(),
10499                                                   ControllingExpr.get(),
10500                                                   AssocTypes,
10501                                                   AssocExprs);
10502 }
10503 
10504 template<typename Derived>
10505 ExprResult
10506 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10507   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10508   if (SubExpr.isInvalid())
10509     return ExprError();
10510 
10511   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10512     return E;
10513 
10514   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10515                                        E->getRParen());
10516 }
10517 
10518 /// The operand of a unary address-of operator has special rules: it's
10519 /// allowed to refer to a non-static member of a class even if there's no 'this'
10520 /// object available.
10521 template<typename Derived>
10522 ExprResult
10523 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10524   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10525     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10526   else
10527     return getDerived().TransformExpr(E);
10528 }
10529 
10530 template<typename Derived>
10531 ExprResult
10532 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10533   ExprResult SubExpr;
10534   if (E->getOpcode() == UO_AddrOf)
10535     SubExpr = TransformAddressOfOperand(E->getSubExpr());
10536   else
10537     SubExpr = TransformExpr(E->getSubExpr());
10538   if (SubExpr.isInvalid())
10539     return ExprError();
10540 
10541   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10542     return E;
10543 
10544   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10545                                            E->getOpcode(),
10546                                            SubExpr.get());
10547 }
10548 
10549 template<typename Derived>
10550 ExprResult
10551 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10552   // Transform the type.
10553   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10554   if (!Type)
10555     return ExprError();
10556 
10557   // Transform all of the components into components similar to what the
10558   // parser uses.
10559   // FIXME: It would be slightly more efficient in the non-dependent case to
10560   // just map FieldDecls, rather than requiring the rebuilder to look for
10561   // the fields again. However, __builtin_offsetof is rare enough in
10562   // template code that we don't care.
10563   bool ExprChanged = false;
10564   typedef Sema::OffsetOfComponent Component;
10565   SmallVector<Component, 4> Components;
10566   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10567     const OffsetOfNode &ON = E->getComponent(I);
10568     Component Comp;
10569     Comp.isBrackets = true;
10570     Comp.LocStart = ON.getSourceRange().getBegin();
10571     Comp.LocEnd = ON.getSourceRange().getEnd();
10572     switch (ON.getKind()) {
10573     case OffsetOfNode::Array: {
10574       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10575       ExprResult Index = getDerived().TransformExpr(FromIndex);
10576       if (Index.isInvalid())
10577         return ExprError();
10578 
10579       ExprChanged = ExprChanged || Index.get() != FromIndex;
10580       Comp.isBrackets = true;
10581       Comp.U.E = Index.get();
10582       break;
10583     }
10584 
10585     case OffsetOfNode::Field:
10586     case OffsetOfNode::Identifier:
10587       Comp.isBrackets = false;
10588       Comp.U.IdentInfo = ON.getFieldName();
10589       if (!Comp.U.IdentInfo)
10590         continue;
10591 
10592       break;
10593 
10594     case OffsetOfNode::Base:
10595       // Will be recomputed during the rebuild.
10596       continue;
10597     }
10598 
10599     Components.push_back(Comp);
10600   }
10601 
10602   // If nothing changed, retain the existing expression.
10603   if (!getDerived().AlwaysRebuild() &&
10604       Type == E->getTypeSourceInfo() &&
10605       !ExprChanged)
10606     return E;
10607 
10608   // Build a new offsetof expression.
10609   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10610                                           Components, E->getRParenLoc());
10611 }
10612 
10613 template<typename Derived>
10614 ExprResult
10615 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
10616   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
10617          "opaque value expression requires transformation");
10618   return E;
10619 }
10620 
10621 template<typename Derived>
10622 ExprResult
10623 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
10624   return E;
10625 }
10626 
10627 template <typename Derived>
10628 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
10629   llvm::SmallVector<Expr *, 8> Children;
10630   bool Changed = false;
10631   for (Expr *C : E->subExpressions()) {
10632     ExprResult NewC = getDerived().TransformExpr(C);
10633     if (NewC.isInvalid())
10634       return ExprError();
10635     Children.push_back(NewC.get());
10636 
10637     Changed |= NewC.get() != C;
10638   }
10639   if (!getDerived().AlwaysRebuild() && !Changed)
10640     return E;
10641   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
10642                                           Children, E->getType());
10643 }
10644 
10645 template<typename Derived>
10646 ExprResult
10647 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
10648   // Rebuild the syntactic form.  The original syntactic form has
10649   // opaque-value expressions in it, so strip those away and rebuild
10650   // the result.  This is a really awful way of doing this, but the
10651   // better solution (rebuilding the semantic expressions and
10652   // rebinding OVEs as necessary) doesn't work; we'd need
10653   // TreeTransform to not strip away implicit conversions.
10654   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
10655   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
10656   if (result.isInvalid()) return ExprError();
10657 
10658   // If that gives us a pseudo-object result back, the pseudo-object
10659   // expression must have been an lvalue-to-rvalue conversion which we
10660   // should reapply.
10661   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
10662     result = SemaRef.checkPseudoObjectRValue(result.get());
10663 
10664   return result;
10665 }
10666 
10667 template<typename Derived>
10668 ExprResult
10669 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
10670                                                 UnaryExprOrTypeTraitExpr *E) {
10671   if (E->isArgumentType()) {
10672     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
10673 
10674     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10675     if (!NewT)
10676       return ExprError();
10677 
10678     if (!getDerived().AlwaysRebuild() && OldT == NewT)
10679       return E;
10680 
10681     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
10682                                                     E->getKind(),
10683                                                     E->getSourceRange());
10684   }
10685 
10686   // C++0x [expr.sizeof]p1:
10687   //   The operand is either an expression, which is an unevaluated operand
10688   //   [...]
10689   EnterExpressionEvaluationContext Unevaluated(
10690       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10691       Sema::ReuseLambdaContextDecl);
10692 
10693   // Try to recover if we have something like sizeof(T::X) where X is a type.
10694   // Notably, there must be *exactly* one set of parens if X is a type.
10695   TypeSourceInfo *RecoveryTSI = nullptr;
10696   ExprResult SubExpr;
10697   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
10698   if (auto *DRE =
10699           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
10700     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
10701         PE, DRE, false, &RecoveryTSI);
10702   else
10703     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
10704 
10705   if (RecoveryTSI) {
10706     return getDerived().RebuildUnaryExprOrTypeTrait(
10707         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
10708   } else if (SubExpr.isInvalid())
10709     return ExprError();
10710 
10711   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
10712     return E;
10713 
10714   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
10715                                                   E->getOperatorLoc(),
10716                                                   E->getKind(),
10717                                                   E->getSourceRange());
10718 }
10719 
10720 template<typename Derived>
10721 ExprResult
10722 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
10723   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10724   if (LHS.isInvalid())
10725     return ExprError();
10726 
10727   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10728   if (RHS.isInvalid())
10729     return ExprError();
10730 
10731 
10732   if (!getDerived().AlwaysRebuild() &&
10733       LHS.get() == E->getLHS() &&
10734       RHS.get() == E->getRHS())
10735     return E;
10736 
10737   return getDerived().RebuildArraySubscriptExpr(
10738       LHS.get(),
10739       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
10740 }
10741 
10742 template <typename Derived>
10743 ExprResult
10744 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
10745   ExprResult Base = getDerived().TransformExpr(E->getBase());
10746   if (Base.isInvalid())
10747     return ExprError();
10748 
10749   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
10750   if (RowIdx.isInvalid())
10751     return ExprError();
10752 
10753   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
10754   if (ColumnIdx.isInvalid())
10755     return ExprError();
10756 
10757   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10758       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
10759     return E;
10760 
10761   return getDerived().RebuildMatrixSubscriptExpr(
10762       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
10763 }
10764 
10765 template <typename Derived>
10766 ExprResult
10767 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
10768   ExprResult Base = getDerived().TransformExpr(E->getBase());
10769   if (Base.isInvalid())
10770     return ExprError();
10771 
10772   ExprResult LowerBound;
10773   if (E->getLowerBound()) {
10774     LowerBound = getDerived().TransformExpr(E->getLowerBound());
10775     if (LowerBound.isInvalid())
10776       return ExprError();
10777   }
10778 
10779   ExprResult Length;
10780   if (E->getLength()) {
10781     Length = getDerived().TransformExpr(E->getLength());
10782     if (Length.isInvalid())
10783       return ExprError();
10784   }
10785 
10786   ExprResult Stride;
10787   if (Expr *Str = E->getStride()) {
10788     Stride = getDerived().TransformExpr(Str);
10789     if (Stride.isInvalid())
10790       return ExprError();
10791   }
10792 
10793   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10794       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
10795     return E;
10796 
10797   return getDerived().RebuildOMPArraySectionExpr(
10798       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
10799       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
10800       E->getRBracketLoc());
10801 }
10802 
10803 template <typename Derived>
10804 ExprResult
10805 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
10806   ExprResult Base = getDerived().TransformExpr(E->getBase());
10807   if (Base.isInvalid())
10808     return ExprError();
10809 
10810   SmallVector<Expr *, 4> Dims;
10811   bool ErrorFound = false;
10812   for (Expr *Dim : E->getDimensions()) {
10813     ExprResult DimRes = getDerived().TransformExpr(Dim);
10814     if (DimRes.isInvalid()) {
10815       ErrorFound = true;
10816       continue;
10817     }
10818     Dims.push_back(DimRes.get());
10819   }
10820 
10821   if (ErrorFound)
10822     return ExprError();
10823   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
10824                                                  E->getRParenLoc(), Dims,
10825                                                  E->getBracketsRanges());
10826 }
10827 
10828 template <typename Derived>
10829 ExprResult
10830 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
10831   unsigned NumIterators = E->numOfIterators();
10832   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
10833 
10834   bool ErrorFound = false;
10835   bool NeedToRebuild = getDerived().AlwaysRebuild();
10836   for (unsigned I = 0; I < NumIterators; ++I) {
10837     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
10838     Data[I].DeclIdent = D->getIdentifier();
10839     Data[I].DeclIdentLoc = D->getLocation();
10840     if (D->getLocation() == D->getBeginLoc()) {
10841       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
10842              "Implicit type must be int.");
10843     } else {
10844       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
10845       QualType DeclTy = getDerived().TransformType(D->getType());
10846       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
10847     }
10848     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
10849     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
10850     ExprResult End = getDerived().TransformExpr(Range.End);
10851     ExprResult Step = getDerived().TransformExpr(Range.Step);
10852     ErrorFound = ErrorFound ||
10853                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
10854                                                !Data[I].Type.get().isNull())) ||
10855                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
10856     if (ErrorFound)
10857       continue;
10858     Data[I].Range.Begin = Begin.get();
10859     Data[I].Range.End = End.get();
10860     Data[I].Range.Step = Step.get();
10861     Data[I].AssignLoc = E->getAssignLoc(I);
10862     Data[I].ColonLoc = E->getColonLoc(I);
10863     Data[I].SecColonLoc = E->getSecondColonLoc(I);
10864     NeedToRebuild =
10865         NeedToRebuild ||
10866         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
10867                                        D->getType().getTypePtrOrNull()) ||
10868         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
10869         Range.Step != Data[I].Range.Step;
10870   }
10871   if (ErrorFound)
10872     return ExprError();
10873   if (!NeedToRebuild)
10874     return E;
10875 
10876   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
10877       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
10878   if (!Res.isUsable())
10879     return Res;
10880   auto *IE = cast<OMPIteratorExpr>(Res.get());
10881   for (unsigned I = 0; I < NumIterators; ++I)
10882     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
10883                                       IE->getIteratorDecl(I));
10884   return Res;
10885 }
10886 
10887 template<typename Derived>
10888 ExprResult
10889 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
10890   // Transform the callee.
10891   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10892   if (Callee.isInvalid())
10893     return ExprError();
10894 
10895   // Transform arguments.
10896   bool ArgChanged = false;
10897   SmallVector<Expr*, 8> Args;
10898   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10899                                   &ArgChanged))
10900     return ExprError();
10901 
10902   if (!getDerived().AlwaysRebuild() &&
10903       Callee.get() == E->getCallee() &&
10904       !ArgChanged)
10905     return SemaRef.MaybeBindToTemporary(E);
10906 
10907   // FIXME: Wrong source location information for the '('.
10908   SourceLocation FakeLParenLoc
10909     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10910 
10911   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10912   if (E->hasStoredFPFeatures()) {
10913     FPOptionsOverride NewOverrides = E->getFPFeatures();
10914     getSema().CurFPFeatures =
10915         NewOverrides.applyOverrides(getSema().getLangOpts());
10916     getSema().FpPragmaStack.CurrentValue = NewOverrides;
10917   }
10918 
10919   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10920                                       Args,
10921                                       E->getRParenLoc());
10922 }
10923 
10924 template<typename Derived>
10925 ExprResult
10926 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
10927   ExprResult Base = getDerived().TransformExpr(E->getBase());
10928   if (Base.isInvalid())
10929     return ExprError();
10930 
10931   NestedNameSpecifierLoc QualifierLoc;
10932   if (E->hasQualifier()) {
10933     QualifierLoc
10934       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10935 
10936     if (!QualifierLoc)
10937       return ExprError();
10938   }
10939   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10940 
10941   ValueDecl *Member
10942     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
10943                                                          E->getMemberDecl()));
10944   if (!Member)
10945     return ExprError();
10946 
10947   NamedDecl *FoundDecl = E->getFoundDecl();
10948   if (FoundDecl == E->getMemberDecl()) {
10949     FoundDecl = Member;
10950   } else {
10951     FoundDecl = cast_or_null<NamedDecl>(
10952                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
10953     if (!FoundDecl)
10954       return ExprError();
10955   }
10956 
10957   if (!getDerived().AlwaysRebuild() &&
10958       Base.get() == E->getBase() &&
10959       QualifierLoc == E->getQualifierLoc() &&
10960       Member == E->getMemberDecl() &&
10961       FoundDecl == E->getFoundDecl() &&
10962       !E->hasExplicitTemplateArgs()) {
10963 
10964     // Mark it referenced in the new context regardless.
10965     // FIXME: this is a bit instantiation-specific.
10966     SemaRef.MarkMemberReferenced(E);
10967 
10968     return E;
10969   }
10970 
10971   TemplateArgumentListInfo TransArgs;
10972   if (E->hasExplicitTemplateArgs()) {
10973     TransArgs.setLAngleLoc(E->getLAngleLoc());
10974     TransArgs.setRAngleLoc(E->getRAngleLoc());
10975     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10976                                                 E->getNumTemplateArgs(),
10977                                                 TransArgs))
10978       return ExprError();
10979   }
10980 
10981   // FIXME: Bogus source location for the operator
10982   SourceLocation FakeOperatorLoc =
10983       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
10984 
10985   // FIXME: to do this check properly, we will need to preserve the
10986   // first-qualifier-in-scope here, just in case we had a dependent
10987   // base (and therefore couldn't do the check) and a
10988   // nested-name-qualifier (and therefore could do the lookup).
10989   NamedDecl *FirstQualifierInScope = nullptr;
10990   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
10991   if (MemberNameInfo.getName()) {
10992     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
10993     if (!MemberNameInfo.getName())
10994       return ExprError();
10995   }
10996 
10997   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
10998                                         E->isArrow(),
10999                                         QualifierLoc,
11000                                         TemplateKWLoc,
11001                                         MemberNameInfo,
11002                                         Member,
11003                                         FoundDecl,
11004                                         (E->hasExplicitTemplateArgs()
11005                                            ? &TransArgs : nullptr),
11006                                         FirstQualifierInScope);
11007 }
11008 
11009 template<typename Derived>
11010 ExprResult
11011 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11012   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11013   if (LHS.isInvalid())
11014     return ExprError();
11015 
11016   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11017   if (RHS.isInvalid())
11018     return ExprError();
11019 
11020   if (!getDerived().AlwaysRebuild() &&
11021       LHS.get() == E->getLHS() &&
11022       RHS.get() == E->getRHS())
11023     return E;
11024 
11025   if (E->isCompoundAssignmentOp())
11026     // FPFeatures has already been established from trailing storage
11027     return getDerived().RebuildBinaryOperator(
11028         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11029   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11030   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
11031   getSema().CurFPFeatures =
11032       NewOverrides.applyOverrides(getSema().getLangOpts());
11033   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11034   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11035                                             LHS.get(), RHS.get());
11036 }
11037 
11038 template <typename Derived>
11039 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11040     CXXRewrittenBinaryOperator *E) {
11041   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11042 
11043   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11044   if (LHS.isInvalid())
11045     return ExprError();
11046 
11047   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11048   if (RHS.isInvalid())
11049     return ExprError();
11050 
11051   // Extract the already-resolved callee declarations so that we can restrict
11052   // ourselves to using them as the unqualified lookup results when rebuilding.
11053   UnresolvedSet<2> UnqualLookups;
11054   bool ChangedAnyLookups = false;
11055   Expr *PossibleBinOps[] = {E->getSemanticForm(),
11056                             const_cast<Expr *>(Decomp.InnerBinOp)};
11057   for (Expr *PossibleBinOp : PossibleBinOps) {
11058     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11059     if (!Op)
11060       continue;
11061     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11062     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11063       continue;
11064 
11065     // Transform the callee in case we built a call to a local extern
11066     // declaration.
11067     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11068         E->getOperatorLoc(), Callee->getFoundDecl()));
11069     if (!Found)
11070       return ExprError();
11071     if (Found != Callee->getFoundDecl())
11072       ChangedAnyLookups = true;
11073     UnqualLookups.addDecl(Found);
11074   }
11075 
11076   if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11077       LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11078     // Mark all functions used in the rewrite as referenced. Note that when
11079     // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11080     // function calls, and/or there might be a user-defined conversion sequence
11081     // applied to the operands of the <.
11082     // FIXME: this is a bit instantiation-specific.
11083     const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11084     SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11085     return E;
11086   }
11087 
11088   return getDerived().RebuildCXXRewrittenBinaryOperator(
11089       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11090 }
11091 
11092 template<typename Derived>
11093 ExprResult
11094 TreeTransform<Derived>::TransformCompoundAssignOperator(
11095                                                       CompoundAssignOperator *E) {
11096   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11097   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
11098   getSema().CurFPFeatures =
11099       NewOverrides.applyOverrides(getSema().getLangOpts());
11100   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11101   return getDerived().TransformBinaryOperator(E);
11102 }
11103 
11104 template<typename Derived>
11105 ExprResult TreeTransform<Derived>::
11106 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11107   // Just rebuild the common and RHS expressions and see whether we
11108   // get any changes.
11109 
11110   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11111   if (commonExpr.isInvalid())
11112     return ExprError();
11113 
11114   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11115   if (rhs.isInvalid())
11116     return ExprError();
11117 
11118   if (!getDerived().AlwaysRebuild() &&
11119       commonExpr.get() == e->getCommon() &&
11120       rhs.get() == e->getFalseExpr())
11121     return e;
11122 
11123   return getDerived().RebuildConditionalOperator(commonExpr.get(),
11124                                                  e->getQuestionLoc(),
11125                                                  nullptr,
11126                                                  e->getColonLoc(),
11127                                                  rhs.get());
11128 }
11129 
11130 template<typename Derived>
11131 ExprResult
11132 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11133   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11134   if (Cond.isInvalid())
11135     return ExprError();
11136 
11137   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11138   if (LHS.isInvalid())
11139     return ExprError();
11140 
11141   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11142   if (RHS.isInvalid())
11143     return ExprError();
11144 
11145   if (!getDerived().AlwaysRebuild() &&
11146       Cond.get() == E->getCond() &&
11147       LHS.get() == E->getLHS() &&
11148       RHS.get() == E->getRHS())
11149     return E;
11150 
11151   return getDerived().RebuildConditionalOperator(Cond.get(),
11152                                                  E->getQuestionLoc(),
11153                                                  LHS.get(),
11154                                                  E->getColonLoc(),
11155                                                  RHS.get());
11156 }
11157 
11158 template<typename Derived>
11159 ExprResult
11160 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11161   // Implicit casts are eliminated during transformation, since they
11162   // will be recomputed by semantic analysis after transformation.
11163   return getDerived().TransformExpr(E->getSubExprAsWritten());
11164 }
11165 
11166 template<typename Derived>
11167 ExprResult
11168 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11169   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11170   if (!Type)
11171     return ExprError();
11172 
11173   ExprResult SubExpr
11174     = getDerived().TransformExpr(E->getSubExprAsWritten());
11175   if (SubExpr.isInvalid())
11176     return ExprError();
11177 
11178   if (!getDerived().AlwaysRebuild() &&
11179       Type == E->getTypeInfoAsWritten() &&
11180       SubExpr.get() == E->getSubExpr())
11181     return E;
11182 
11183   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11184                                             Type,
11185                                             E->getRParenLoc(),
11186                                             SubExpr.get());
11187 }
11188 
11189 template<typename Derived>
11190 ExprResult
11191 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11192   TypeSourceInfo *OldT = E->getTypeSourceInfo();
11193   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11194   if (!NewT)
11195     return ExprError();
11196 
11197   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11198   if (Init.isInvalid())
11199     return ExprError();
11200 
11201   if (!getDerived().AlwaysRebuild() &&
11202       OldT == NewT &&
11203       Init.get() == E->getInitializer())
11204     return SemaRef.MaybeBindToTemporary(E);
11205 
11206   // Note: the expression type doesn't necessarily match the
11207   // type-as-written, but that's okay, because it should always be
11208   // derivable from the initializer.
11209 
11210   return getDerived().RebuildCompoundLiteralExpr(
11211       E->getLParenLoc(), NewT,
11212       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11213 }
11214 
11215 template<typename Derived>
11216 ExprResult
11217 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11218   ExprResult Base = getDerived().TransformExpr(E->getBase());
11219   if (Base.isInvalid())
11220     return ExprError();
11221 
11222   if (!getDerived().AlwaysRebuild() &&
11223       Base.get() == E->getBase())
11224     return E;
11225 
11226   // FIXME: Bad source location
11227   SourceLocation FakeOperatorLoc =
11228       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11229   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
11230                                                   E->getAccessorLoc(),
11231                                                   E->getAccessor());
11232 }
11233 
11234 template<typename Derived>
11235 ExprResult
11236 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11237   if (InitListExpr *Syntactic = E->getSyntacticForm())
11238     E = Syntactic;
11239 
11240   bool InitChanged = false;
11241 
11242   EnterExpressionEvaluationContext Context(
11243       getSema(), EnterExpressionEvaluationContext::InitList);
11244 
11245   SmallVector<Expr*, 4> Inits;
11246   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11247                                   Inits, &InitChanged))
11248     return ExprError();
11249 
11250   if (!getDerived().AlwaysRebuild() && !InitChanged) {
11251     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11252     // in some cases. We can't reuse it in general, because the syntactic and
11253     // semantic forms are linked, and we can't know that semantic form will
11254     // match even if the syntactic form does.
11255   }
11256 
11257   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11258                                       E->getRBraceLoc());
11259 }
11260 
11261 template<typename Derived>
11262 ExprResult
11263 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11264   Designation Desig;
11265 
11266   // transform the initializer value
11267   ExprResult Init = getDerived().TransformExpr(E->getInit());
11268   if (Init.isInvalid())
11269     return ExprError();
11270 
11271   // transform the designators.
11272   SmallVector<Expr*, 4> ArrayExprs;
11273   bool ExprChanged = false;
11274   for (const DesignatedInitExpr::Designator &D : E->designators()) {
11275     if (D.isFieldDesignator()) {
11276       Desig.AddDesignator(Designator::getField(D.getFieldName(),
11277                                                D.getDotLoc(),
11278                                                D.getFieldLoc()));
11279       if (D.getField()) {
11280         FieldDecl *Field = cast_or_null<FieldDecl>(
11281             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
11282         if (Field != D.getField())
11283           // Rebuild the expression when the transformed FieldDecl is
11284           // different to the already assigned FieldDecl.
11285           ExprChanged = true;
11286       } else {
11287         // Ensure that the designator expression is rebuilt when there isn't
11288         // a resolved FieldDecl in the designator as we don't want to assign
11289         // a FieldDecl to a pattern designator that will be instantiated again.
11290         ExprChanged = true;
11291       }
11292       continue;
11293     }
11294 
11295     if (D.isArrayDesignator()) {
11296       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11297       if (Index.isInvalid())
11298         return ExprError();
11299 
11300       Desig.AddDesignator(
11301           Designator::getArray(Index.get(), D.getLBracketLoc()));
11302 
11303       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11304       ArrayExprs.push_back(Index.get());
11305       continue;
11306     }
11307 
11308     assert(D.isArrayRangeDesignator() && "New kind of designator?");
11309     ExprResult Start
11310       = getDerived().TransformExpr(E->getArrayRangeStart(D));
11311     if (Start.isInvalid())
11312       return ExprError();
11313 
11314     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11315     if (End.isInvalid())
11316       return ExprError();
11317 
11318     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
11319                                                   End.get(),
11320                                                   D.getLBracketLoc(),
11321                                                   D.getEllipsisLoc()));
11322 
11323     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11324                   End.get() != E->getArrayRangeEnd(D);
11325 
11326     ArrayExprs.push_back(Start.get());
11327     ArrayExprs.push_back(End.get());
11328   }
11329 
11330   if (!getDerived().AlwaysRebuild() &&
11331       Init.get() == E->getInit() &&
11332       !ExprChanged)
11333     return E;
11334 
11335   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11336                                                 E->getEqualOrColonLoc(),
11337                                                 E->usesGNUSyntax(), Init.get());
11338 }
11339 
11340 // Seems that if TransformInitListExpr() only works on the syntactic form of an
11341 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11342 template<typename Derived>
11343 ExprResult
11344 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11345     DesignatedInitUpdateExpr *E) {
11346   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
11347                    "initializer");
11348   return ExprError();
11349 }
11350 
11351 template<typename Derived>
11352 ExprResult
11353 TreeTransform<Derived>::TransformNoInitExpr(
11354     NoInitExpr *E) {
11355   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
11356   return ExprError();
11357 }
11358 
11359 template<typename Derived>
11360 ExprResult
11361 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11362   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
11363   return ExprError();
11364 }
11365 
11366 template<typename Derived>
11367 ExprResult
11368 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11369   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
11370   return ExprError();
11371 }
11372 
11373 template<typename Derived>
11374 ExprResult
11375 TreeTransform<Derived>::TransformImplicitValueInitExpr(
11376                                                      ImplicitValueInitExpr *E) {
11377   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11378 
11379   // FIXME: Will we ever have proper type location here? Will we actually
11380   // need to transform the type?
11381   QualType T = getDerived().TransformType(E->getType());
11382   if (T.isNull())
11383     return ExprError();
11384 
11385   if (!getDerived().AlwaysRebuild() &&
11386       T == E->getType())
11387     return E;
11388 
11389   return getDerived().RebuildImplicitValueInitExpr(T);
11390 }
11391 
11392 template<typename Derived>
11393 ExprResult
11394 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11395   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11396   if (!TInfo)
11397     return ExprError();
11398 
11399   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11400   if (SubExpr.isInvalid())
11401     return ExprError();
11402 
11403   if (!getDerived().AlwaysRebuild() &&
11404       TInfo == E->getWrittenTypeInfo() &&
11405       SubExpr.get() == E->getSubExpr())
11406     return E;
11407 
11408   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11409                                        TInfo, E->getRParenLoc());
11410 }
11411 
11412 template<typename Derived>
11413 ExprResult
11414 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11415   bool ArgumentChanged = false;
11416   SmallVector<Expr*, 4> Inits;
11417   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11418                      &ArgumentChanged))
11419     return ExprError();
11420 
11421   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11422                                            Inits,
11423                                            E->getRParenLoc());
11424 }
11425 
11426 /// Transform an address-of-label expression.
11427 ///
11428 /// By default, the transformation of an address-of-label expression always
11429 /// rebuilds the expression, so that the label identifier can be resolved to
11430 /// the corresponding label statement by semantic analysis.
11431 template<typename Derived>
11432 ExprResult
11433 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11434   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11435                                         E->getLabel());
11436   if (!LD)
11437     return ExprError();
11438 
11439   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11440                                            cast<LabelDecl>(LD));
11441 }
11442 
11443 template<typename Derived>
11444 ExprResult
11445 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11446   SemaRef.ActOnStartStmtExpr();
11447   StmtResult SubStmt
11448     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11449   if (SubStmt.isInvalid()) {
11450     SemaRef.ActOnStmtExprError();
11451     return ExprError();
11452   }
11453 
11454   unsigned OldDepth = E->getTemplateDepth();
11455   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11456 
11457   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11458       SubStmt.get() == E->getSubStmt()) {
11459     // Calling this an 'error' is unintuitive, but it does the right thing.
11460     SemaRef.ActOnStmtExprError();
11461     return SemaRef.MaybeBindToTemporary(E);
11462   }
11463 
11464   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11465                                       E->getRParenLoc(), NewDepth);
11466 }
11467 
11468 template<typename Derived>
11469 ExprResult
11470 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11471   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11472   if (Cond.isInvalid())
11473     return ExprError();
11474 
11475   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11476   if (LHS.isInvalid())
11477     return ExprError();
11478 
11479   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11480   if (RHS.isInvalid())
11481     return ExprError();
11482 
11483   if (!getDerived().AlwaysRebuild() &&
11484       Cond.get() == E->getCond() &&
11485       LHS.get() == E->getLHS() &&
11486       RHS.get() == E->getRHS())
11487     return E;
11488 
11489   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11490                                         Cond.get(), LHS.get(), RHS.get(),
11491                                         E->getRParenLoc());
11492 }
11493 
11494 template<typename Derived>
11495 ExprResult
11496 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11497   return E;
11498 }
11499 
11500 template<typename Derived>
11501 ExprResult
11502 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11503   switch (E->getOperator()) {
11504   case OO_New:
11505   case OO_Delete:
11506   case OO_Array_New:
11507   case OO_Array_Delete:
11508     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
11509 
11510   case OO_Call: {
11511     // This is a call to an object's operator().
11512     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
11513 
11514     // Transform the object itself.
11515     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11516     if (Object.isInvalid())
11517       return ExprError();
11518 
11519     // FIXME: Poor location information
11520     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11521         static_cast<Expr *>(Object.get())->getEndLoc());
11522 
11523     // Transform the call arguments.
11524     SmallVector<Expr*, 8> Args;
11525     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11526                                     Args))
11527       return ExprError();
11528 
11529     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11530                                         E->getEndLoc());
11531   }
11532 
11533 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11534   case OO_##Name:
11535 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11536 #include "clang/Basic/OperatorKinds.def"
11537   case OO_Subscript:
11538     // Handled below.
11539     break;
11540 
11541   case OO_Conditional:
11542     llvm_unreachable("conditional operator is not actually overloadable");
11543 
11544   case OO_None:
11545   case NUM_OVERLOADED_OPERATORS:
11546     llvm_unreachable("not an overloaded operator?");
11547   }
11548 
11549   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11550   if (Callee.isInvalid())
11551     return ExprError();
11552 
11553   ExprResult First;
11554   if (E->getOperator() == OO_Amp)
11555     First = getDerived().TransformAddressOfOperand(E->getArg(0));
11556   else
11557     First = getDerived().TransformExpr(E->getArg(0));
11558   if (First.isInvalid())
11559     return ExprError();
11560 
11561   ExprResult Second;
11562   if (E->getNumArgs() == 2) {
11563     Second = getDerived().TransformExpr(E->getArg(1));
11564     if (Second.isInvalid())
11565       return ExprError();
11566   }
11567 
11568   if (!getDerived().AlwaysRebuild() &&
11569       Callee.get() == E->getCallee() &&
11570       First.get() == E->getArg(0) &&
11571       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11572     return SemaRef.MaybeBindToTemporary(E);
11573 
11574   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11575   FPOptionsOverride NewOverrides(E->getFPFeatures());
11576   getSema().CurFPFeatures =
11577       NewOverrides.applyOverrides(getSema().getLangOpts());
11578   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11579 
11580   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11581                                                  E->getOperatorLoc(),
11582                                                  Callee.get(),
11583                                                  First.get(),
11584                                                  Second.get());
11585 }
11586 
11587 template<typename Derived>
11588 ExprResult
11589 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11590   return getDerived().TransformCallExpr(E);
11591 }
11592 
11593 template <typename Derived>
11594 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11595   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11596                          getSema().CurContext != E->getParentContext();
11597 
11598   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11599     return E;
11600 
11601   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
11602                                            E->getEndLoc(),
11603                                            getSema().CurContext);
11604 }
11605 
11606 template<typename Derived>
11607 ExprResult
11608 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11609   // Transform the callee.
11610   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11611   if (Callee.isInvalid())
11612     return ExprError();
11613 
11614   // Transform exec config.
11615   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
11616   if (EC.isInvalid())
11617     return ExprError();
11618 
11619   // Transform arguments.
11620   bool ArgChanged = false;
11621   SmallVector<Expr*, 8> Args;
11622   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11623                                   &ArgChanged))
11624     return ExprError();
11625 
11626   if (!getDerived().AlwaysRebuild() &&
11627       Callee.get() == E->getCallee() &&
11628       !ArgChanged)
11629     return SemaRef.MaybeBindToTemporary(E);
11630 
11631   // FIXME: Wrong source location information for the '('.
11632   SourceLocation FakeLParenLoc
11633     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11634   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11635                                       Args,
11636                                       E->getRParenLoc(), EC.get());
11637 }
11638 
11639 template<typename Derived>
11640 ExprResult
11641 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
11642   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11643   if (!Type)
11644     return ExprError();
11645 
11646   ExprResult SubExpr
11647     = getDerived().TransformExpr(E->getSubExprAsWritten());
11648   if (SubExpr.isInvalid())
11649     return ExprError();
11650 
11651   if (!getDerived().AlwaysRebuild() &&
11652       Type == E->getTypeInfoAsWritten() &&
11653       SubExpr.get() == E->getSubExpr())
11654     return E;
11655   return getDerived().RebuildCXXNamedCastExpr(
11656       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
11657       Type, E->getAngleBrackets().getEnd(),
11658       // FIXME. this should be '(' location
11659       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
11660 }
11661 
11662 template<typename Derived>
11663 ExprResult
11664 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
11665   TypeSourceInfo *TSI =
11666       getDerived().TransformType(BCE->getTypeInfoAsWritten());
11667   if (!TSI)
11668     return ExprError();
11669 
11670   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
11671   if (Sub.isInvalid())
11672     return ExprError();
11673 
11674   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
11675                                                 Sub.get(), BCE->getEndLoc());
11676 }
11677 
11678 template<typename Derived>
11679 ExprResult
11680 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
11681   return getDerived().TransformCXXNamedCastExpr(E);
11682 }
11683 
11684 template<typename Derived>
11685 ExprResult
11686 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
11687   return getDerived().TransformCXXNamedCastExpr(E);
11688 }
11689 
11690 template<typename Derived>
11691 ExprResult
11692 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
11693                                                       CXXReinterpretCastExpr *E) {
11694   return getDerived().TransformCXXNamedCastExpr(E);
11695 }
11696 
11697 template<typename Derived>
11698 ExprResult
11699 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
11700   return getDerived().TransformCXXNamedCastExpr(E);
11701 }
11702 
11703 template<typename Derived>
11704 ExprResult
11705 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
11706   return getDerived().TransformCXXNamedCastExpr(E);
11707 }
11708 
11709 template<typename Derived>
11710 ExprResult
11711 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
11712                                                      CXXFunctionalCastExpr *E) {
11713   TypeSourceInfo *Type =
11714       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
11715   if (!Type)
11716     return ExprError();
11717 
11718   ExprResult SubExpr
11719     = getDerived().TransformExpr(E->getSubExprAsWritten());
11720   if (SubExpr.isInvalid())
11721     return ExprError();
11722 
11723   if (!getDerived().AlwaysRebuild() &&
11724       Type == E->getTypeInfoAsWritten() &&
11725       SubExpr.get() == E->getSubExpr())
11726     return E;
11727 
11728   return getDerived().RebuildCXXFunctionalCastExpr(Type,
11729                                                    E->getLParenLoc(),
11730                                                    SubExpr.get(),
11731                                                    E->getRParenLoc(),
11732                                                    E->isListInitialization());
11733 }
11734 
11735 template<typename Derived>
11736 ExprResult
11737 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
11738   if (E->isTypeOperand()) {
11739     TypeSourceInfo *TInfo
11740       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11741     if (!TInfo)
11742       return ExprError();
11743 
11744     if (!getDerived().AlwaysRebuild() &&
11745         TInfo == E->getTypeOperandSourceInfo())
11746       return E;
11747 
11748     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11749                                              TInfo, E->getEndLoc());
11750   }
11751 
11752   // Typeid's operand is an unevaluated context, unless it's a polymorphic
11753   // type.  We must not unilaterally enter unevaluated context here, as then
11754   // semantic processing can re-transform an already transformed operand.
11755   Expr *Op = E->getExprOperand();
11756   auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
11757   if (E->isGLValue())
11758     if (auto *RecordT = Op->getType()->getAs<RecordType>())
11759       if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
11760         EvalCtx = SemaRef.ExprEvalContexts.back().Context;
11761 
11762   EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
11763                                                Sema::ReuseLambdaContextDecl);
11764 
11765   ExprResult SubExpr = getDerived().TransformExpr(Op);
11766   if (SubExpr.isInvalid())
11767     return ExprError();
11768 
11769   if (!getDerived().AlwaysRebuild() &&
11770       SubExpr.get() == E->getExprOperand())
11771     return E;
11772 
11773   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11774                                            SubExpr.get(), E->getEndLoc());
11775 }
11776 
11777 template<typename Derived>
11778 ExprResult
11779 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
11780   if (E->isTypeOperand()) {
11781     TypeSourceInfo *TInfo
11782       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11783     if (!TInfo)
11784       return ExprError();
11785 
11786     if (!getDerived().AlwaysRebuild() &&
11787         TInfo == E->getTypeOperandSourceInfo())
11788       return E;
11789 
11790     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11791                                              TInfo, E->getEndLoc());
11792   }
11793 
11794   EnterExpressionEvaluationContext Unevaluated(
11795       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11796 
11797   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11798   if (SubExpr.isInvalid())
11799     return ExprError();
11800 
11801   if (!getDerived().AlwaysRebuild() &&
11802       SubExpr.get() == E->getExprOperand())
11803     return E;
11804 
11805   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11806                                            SubExpr.get(), E->getEndLoc());
11807 }
11808 
11809 template<typename Derived>
11810 ExprResult
11811 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
11812   return E;
11813 }
11814 
11815 template<typename Derived>
11816 ExprResult
11817 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
11818                                                      CXXNullPtrLiteralExpr *E) {
11819   return E;
11820 }
11821 
11822 template<typename Derived>
11823 ExprResult
11824 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
11825   QualType T = getSema().getCurrentThisType();
11826 
11827   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
11828     // Mark it referenced in the new context regardless.
11829     // FIXME: this is a bit instantiation-specific.
11830     getSema().MarkThisReferenced(E);
11831     return E;
11832   }
11833 
11834   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
11835 }
11836 
11837 template<typename Derived>
11838 ExprResult
11839 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
11840   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11841   if (SubExpr.isInvalid())
11842     return ExprError();
11843 
11844   if (!getDerived().AlwaysRebuild() &&
11845       SubExpr.get() == E->getSubExpr())
11846     return E;
11847 
11848   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
11849                                           E->isThrownVariableInScope());
11850 }
11851 
11852 template<typename Derived>
11853 ExprResult
11854 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11855   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
11856       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
11857   if (!Param)
11858     return ExprError();
11859 
11860   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
11861       E->getUsedContext() == SemaRef.CurContext)
11862     return E;
11863 
11864   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
11865 }
11866 
11867 template<typename Derived>
11868 ExprResult
11869 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
11870   FieldDecl *Field = cast_or_null<FieldDecl>(
11871       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
11872   if (!Field)
11873     return ExprError();
11874 
11875   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
11876       E->getUsedContext() == SemaRef.CurContext)
11877     return E;
11878 
11879   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
11880 }
11881 
11882 template<typename Derived>
11883 ExprResult
11884 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
11885                                                     CXXScalarValueInitExpr *E) {
11886   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
11887   if (!T)
11888     return ExprError();
11889 
11890   if (!getDerived().AlwaysRebuild() &&
11891       T == E->getTypeSourceInfo())
11892     return E;
11893 
11894   return getDerived().RebuildCXXScalarValueInitExpr(T,
11895                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
11896                                                     E->getRParenLoc());
11897 }
11898 
11899 template<typename Derived>
11900 ExprResult
11901 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
11902   // Transform the type that we're allocating
11903   TypeSourceInfo *AllocTypeInfo =
11904       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
11905   if (!AllocTypeInfo)
11906     return ExprError();
11907 
11908   // Transform the size of the array we're allocating (if any).
11909   Optional<Expr *> ArraySize;
11910   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
11911     ExprResult NewArraySize;
11912     if (*OldArraySize) {
11913       NewArraySize = getDerived().TransformExpr(*OldArraySize);
11914       if (NewArraySize.isInvalid())
11915         return ExprError();
11916     }
11917     ArraySize = NewArraySize.get();
11918   }
11919 
11920   // Transform the placement arguments (if any).
11921   bool ArgumentChanged = false;
11922   SmallVector<Expr*, 8> PlacementArgs;
11923   if (getDerived().TransformExprs(E->getPlacementArgs(),
11924                                   E->getNumPlacementArgs(), true,
11925                                   PlacementArgs, &ArgumentChanged))
11926     return ExprError();
11927 
11928   // Transform the initializer (if any).
11929   Expr *OldInit = E->getInitializer();
11930   ExprResult NewInit;
11931   if (OldInit)
11932     NewInit = getDerived().TransformInitializer(OldInit, true);
11933   if (NewInit.isInvalid())
11934     return ExprError();
11935 
11936   // Transform new operator and delete operator.
11937   FunctionDecl *OperatorNew = nullptr;
11938   if (E->getOperatorNew()) {
11939     OperatorNew = cast_or_null<FunctionDecl>(
11940         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
11941     if (!OperatorNew)
11942       return ExprError();
11943   }
11944 
11945   FunctionDecl *OperatorDelete = nullptr;
11946   if (E->getOperatorDelete()) {
11947     OperatorDelete = cast_or_null<FunctionDecl>(
11948         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
11949     if (!OperatorDelete)
11950       return ExprError();
11951   }
11952 
11953   if (!getDerived().AlwaysRebuild() &&
11954       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
11955       ArraySize == E->getArraySize() &&
11956       NewInit.get() == OldInit &&
11957       OperatorNew == E->getOperatorNew() &&
11958       OperatorDelete == E->getOperatorDelete() &&
11959       !ArgumentChanged) {
11960     // Mark any declarations we need as referenced.
11961     // FIXME: instantiation-specific.
11962     if (OperatorNew)
11963       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
11964     if (OperatorDelete)
11965       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
11966 
11967     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
11968       QualType ElementType
11969         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
11970       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
11971         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
11972         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
11973           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
11974         }
11975       }
11976     }
11977 
11978     return E;
11979   }
11980 
11981   QualType AllocType = AllocTypeInfo->getType();
11982   if (!ArraySize) {
11983     // If no array size was specified, but the new expression was
11984     // instantiated with an array type (e.g., "new T" where T is
11985     // instantiated with "int[4]"), extract the outer bound from the
11986     // array type as our array size. We do this with constant and
11987     // dependently-sized array types.
11988     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
11989     if (!ArrayT) {
11990       // Do nothing
11991     } else if (const ConstantArrayType *ConsArrayT
11992                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
11993       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
11994                                          SemaRef.Context.getSizeType(),
11995                                          /*FIXME:*/ E->getBeginLoc());
11996       AllocType = ConsArrayT->getElementType();
11997     } else if (const DependentSizedArrayType *DepArrayT
11998                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
11999       if (DepArrayT->getSizeExpr()) {
12000         ArraySize = DepArrayT->getSizeExpr();
12001         AllocType = DepArrayT->getElementType();
12002       }
12003     }
12004   }
12005 
12006   return getDerived().RebuildCXXNewExpr(
12007       E->getBeginLoc(), E->isGlobalNew(),
12008       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12009       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12010       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12011 }
12012 
12013 template<typename Derived>
12014 ExprResult
12015 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12016   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12017   if (Operand.isInvalid())
12018     return ExprError();
12019 
12020   // Transform the delete operator, if known.
12021   FunctionDecl *OperatorDelete = nullptr;
12022   if (E->getOperatorDelete()) {
12023     OperatorDelete = cast_or_null<FunctionDecl>(
12024         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12025     if (!OperatorDelete)
12026       return ExprError();
12027   }
12028 
12029   if (!getDerived().AlwaysRebuild() &&
12030       Operand.get() == E->getArgument() &&
12031       OperatorDelete == E->getOperatorDelete()) {
12032     // Mark any declarations we need as referenced.
12033     // FIXME: instantiation-specific.
12034     if (OperatorDelete)
12035       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12036 
12037     if (!E->getArgument()->isTypeDependent()) {
12038       QualType Destroyed = SemaRef.Context.getBaseElementType(
12039                                                          E->getDestroyedType());
12040       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12041         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12042         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12043                                        SemaRef.LookupDestructor(Record));
12044       }
12045     }
12046 
12047     return E;
12048   }
12049 
12050   return getDerived().RebuildCXXDeleteExpr(
12051       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12052 }
12053 
12054 template<typename Derived>
12055 ExprResult
12056 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12057                                                      CXXPseudoDestructorExpr *E) {
12058   ExprResult Base = getDerived().TransformExpr(E->getBase());
12059   if (Base.isInvalid())
12060     return ExprError();
12061 
12062   ParsedType ObjectTypePtr;
12063   bool MayBePseudoDestructor = false;
12064   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12065                                               E->getOperatorLoc(),
12066                                         E->isArrow()? tok::arrow : tok::period,
12067                                               ObjectTypePtr,
12068                                               MayBePseudoDestructor);
12069   if (Base.isInvalid())
12070     return ExprError();
12071 
12072   QualType ObjectType = ObjectTypePtr.get();
12073   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12074   if (QualifierLoc) {
12075     QualifierLoc
12076       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12077     if (!QualifierLoc)
12078       return ExprError();
12079   }
12080   CXXScopeSpec SS;
12081   SS.Adopt(QualifierLoc);
12082 
12083   PseudoDestructorTypeStorage Destroyed;
12084   if (E->getDestroyedTypeInfo()) {
12085     TypeSourceInfo *DestroyedTypeInfo
12086       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12087                                                 ObjectType, nullptr, SS);
12088     if (!DestroyedTypeInfo)
12089       return ExprError();
12090     Destroyed = DestroyedTypeInfo;
12091   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12092     // We aren't likely to be able to resolve the identifier down to a type
12093     // now anyway, so just retain the identifier.
12094     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12095                                             E->getDestroyedTypeLoc());
12096   } else {
12097     // Look for a destructor known with the given name.
12098     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12099                                               *E->getDestroyedTypeIdentifier(),
12100                                                 E->getDestroyedTypeLoc(),
12101                                                 /*Scope=*/nullptr,
12102                                                 SS, ObjectTypePtr,
12103                                                 false);
12104     if (!T)
12105       return ExprError();
12106 
12107     Destroyed
12108       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12109                                                  E->getDestroyedTypeLoc());
12110   }
12111 
12112   TypeSourceInfo *ScopeTypeInfo = nullptr;
12113   if (E->getScopeTypeInfo()) {
12114     CXXScopeSpec EmptySS;
12115     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12116                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12117     if (!ScopeTypeInfo)
12118       return ExprError();
12119   }
12120 
12121   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12122                                                      E->getOperatorLoc(),
12123                                                      E->isArrow(),
12124                                                      SS,
12125                                                      ScopeTypeInfo,
12126                                                      E->getColonColonLoc(),
12127                                                      E->getTildeLoc(),
12128                                                      Destroyed);
12129 }
12130 
12131 template <typename Derived>
12132 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12133                                                         bool RequiresADL,
12134                                                         LookupResult &R) {
12135   // Transform all the decls.
12136   bool AllEmptyPacks = true;
12137   for (auto *OldD : Old->decls()) {
12138     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12139     if (!InstD) {
12140       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12141       // This can happen because of dependent hiding.
12142       if (isa<UsingShadowDecl>(OldD))
12143         continue;
12144       else {
12145         R.clear();
12146         return true;
12147       }
12148     }
12149 
12150     // Expand using pack declarations.
12151     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12152     ArrayRef<NamedDecl*> Decls = SingleDecl;
12153     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12154       Decls = UPD->expansions();
12155 
12156     // Expand using declarations.
12157     for (auto *D : Decls) {
12158       if (auto *UD = dyn_cast<UsingDecl>(D)) {
12159         for (auto *SD : UD->shadows())
12160           R.addDecl(SD);
12161       } else {
12162         R.addDecl(D);
12163       }
12164     }
12165 
12166     AllEmptyPacks &= Decls.empty();
12167   };
12168 
12169   // C++ [temp.res]/8.4.2:
12170   //   The program is ill-formed, no diagnostic required, if [...] lookup for
12171   //   a name in the template definition found a using-declaration, but the
12172   //   lookup in the corresponding scope in the instantiation odoes not find
12173   //   any declarations because the using-declaration was a pack expansion and
12174   //   the corresponding pack is empty
12175   if (AllEmptyPacks && !RequiresADL) {
12176     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12177         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12178     return true;
12179   }
12180 
12181   // Resolve a kind, but don't do any further analysis.  If it's
12182   // ambiguous, the callee needs to deal with it.
12183   R.resolveKind();
12184   return false;
12185 }
12186 
12187 template<typename Derived>
12188 ExprResult
12189 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12190                                                   UnresolvedLookupExpr *Old) {
12191   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12192                  Sema::LookupOrdinaryName);
12193 
12194   // Transform the declaration set.
12195   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12196     return ExprError();
12197 
12198   // Rebuild the nested-name qualifier, if present.
12199   CXXScopeSpec SS;
12200   if (Old->getQualifierLoc()) {
12201     NestedNameSpecifierLoc QualifierLoc
12202       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12203     if (!QualifierLoc)
12204       return ExprError();
12205 
12206     SS.Adopt(QualifierLoc);
12207   }
12208 
12209   if (Old->getNamingClass()) {
12210     CXXRecordDecl *NamingClass
12211       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12212                                                             Old->getNameLoc(),
12213                                                         Old->getNamingClass()));
12214     if (!NamingClass) {
12215       R.clear();
12216       return ExprError();
12217     }
12218 
12219     R.setNamingClass(NamingClass);
12220   }
12221 
12222   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12223 
12224   // If we have neither explicit template arguments, nor the template keyword,
12225   // it's a normal declaration name or member reference.
12226   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12227     NamedDecl *D = R.getAsSingle<NamedDecl>();
12228     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12229     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12230     // give a good diagnostic.
12231     if (D && D->isCXXInstanceMember()) {
12232       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12233                                                      /*TemplateArgs=*/nullptr,
12234                                                      /*Scope=*/nullptr);
12235     }
12236 
12237     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12238   }
12239 
12240   // If we have template arguments, rebuild them, then rebuild the
12241   // templateid expression.
12242   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12243   if (Old->hasExplicitTemplateArgs() &&
12244       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12245                                               Old->getNumTemplateArgs(),
12246                                               TransArgs)) {
12247     R.clear();
12248     return ExprError();
12249   }
12250 
12251   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12252                                             Old->requiresADL(), &TransArgs);
12253 }
12254 
12255 template<typename Derived>
12256 ExprResult
12257 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12258   bool ArgChanged = false;
12259   SmallVector<TypeSourceInfo *, 4> Args;
12260   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12261     TypeSourceInfo *From = E->getArg(I);
12262     TypeLoc FromTL = From->getTypeLoc();
12263     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12264       TypeLocBuilder TLB;
12265       TLB.reserve(FromTL.getFullDataSize());
12266       QualType To = getDerived().TransformType(TLB, FromTL);
12267       if (To.isNull())
12268         return ExprError();
12269 
12270       if (To == From->getType())
12271         Args.push_back(From);
12272       else {
12273         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12274         ArgChanged = true;
12275       }
12276       continue;
12277     }
12278 
12279     ArgChanged = true;
12280 
12281     // We have a pack expansion. Instantiate it.
12282     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12283     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12284     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12285     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12286 
12287     // Determine whether the set of unexpanded parameter packs can and should
12288     // be expanded.
12289     bool Expand = true;
12290     bool RetainExpansion = false;
12291     Optional<unsigned> OrigNumExpansions =
12292         ExpansionTL.getTypePtr()->getNumExpansions();
12293     Optional<unsigned> NumExpansions = OrigNumExpansions;
12294     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12295                                              PatternTL.getSourceRange(),
12296                                              Unexpanded,
12297                                              Expand, RetainExpansion,
12298                                              NumExpansions))
12299       return ExprError();
12300 
12301     if (!Expand) {
12302       // The transform has determined that we should perform a simple
12303       // transformation on the pack expansion, producing another pack
12304       // expansion.
12305       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12306 
12307       TypeLocBuilder TLB;
12308       TLB.reserve(From->getTypeLoc().getFullDataSize());
12309 
12310       QualType To = getDerived().TransformType(TLB, PatternTL);
12311       if (To.isNull())
12312         return ExprError();
12313 
12314       To = getDerived().RebuildPackExpansionType(To,
12315                                                  PatternTL.getSourceRange(),
12316                                                  ExpansionTL.getEllipsisLoc(),
12317                                                  NumExpansions);
12318       if (To.isNull())
12319         return ExprError();
12320 
12321       PackExpansionTypeLoc ToExpansionTL
12322         = TLB.push<PackExpansionTypeLoc>(To);
12323       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12324       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12325       continue;
12326     }
12327 
12328     // Expand the pack expansion by substituting for each argument in the
12329     // pack(s).
12330     for (unsigned I = 0; I != *NumExpansions; ++I) {
12331       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12332       TypeLocBuilder TLB;
12333       TLB.reserve(PatternTL.getFullDataSize());
12334       QualType To = getDerived().TransformType(TLB, PatternTL);
12335       if (To.isNull())
12336         return ExprError();
12337 
12338       if (To->containsUnexpandedParameterPack()) {
12339         To = getDerived().RebuildPackExpansionType(To,
12340                                                    PatternTL.getSourceRange(),
12341                                                    ExpansionTL.getEllipsisLoc(),
12342                                                    NumExpansions);
12343         if (To.isNull())
12344           return ExprError();
12345 
12346         PackExpansionTypeLoc ToExpansionTL
12347           = TLB.push<PackExpansionTypeLoc>(To);
12348         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12349       }
12350 
12351       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12352     }
12353 
12354     if (!RetainExpansion)
12355       continue;
12356 
12357     // If we're supposed to retain a pack expansion, do so by temporarily
12358     // forgetting the partially-substituted parameter pack.
12359     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12360 
12361     TypeLocBuilder TLB;
12362     TLB.reserve(From->getTypeLoc().getFullDataSize());
12363 
12364     QualType To = getDerived().TransformType(TLB, PatternTL);
12365     if (To.isNull())
12366       return ExprError();
12367 
12368     To = getDerived().RebuildPackExpansionType(To,
12369                                                PatternTL.getSourceRange(),
12370                                                ExpansionTL.getEllipsisLoc(),
12371                                                NumExpansions);
12372     if (To.isNull())
12373       return ExprError();
12374 
12375     PackExpansionTypeLoc ToExpansionTL
12376       = TLB.push<PackExpansionTypeLoc>(To);
12377     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12378     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12379   }
12380 
12381   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12382     return E;
12383 
12384   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12385                                        E->getEndLoc());
12386 }
12387 
12388 template<typename Derived>
12389 ExprResult
12390 TreeTransform<Derived>::TransformConceptSpecializationExpr(
12391                                                  ConceptSpecializationExpr *E) {
12392   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12393   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12394   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12395                                               Old->NumTemplateArgs, TransArgs))
12396     return ExprError();
12397 
12398   return getDerived().RebuildConceptSpecializationExpr(
12399       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12400       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12401       &TransArgs);
12402 }
12403 
12404 template<typename Derived>
12405 ExprResult
12406 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12407   SmallVector<ParmVarDecl*, 4> TransParams;
12408   SmallVector<QualType, 4> TransParamTypes;
12409   Sema::ExtParameterInfoBuilder ExtParamInfos;
12410 
12411   // C++2a [expr.prim.req]p2
12412   // Expressions appearing within a requirement-body are unevaluated operands.
12413   EnterExpressionEvaluationContext Ctx(
12414       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12415 
12416   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12417       getSema().Context, getSema().CurContext,
12418       E->getBody()->getBeginLoc());
12419 
12420   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12421 
12422   if (getDerived().TransformFunctionTypeParams(E->getRequiresKWLoc(),
12423                                                E->getLocalParameters(),
12424                                                /*ParamTypes=*/nullptr,
12425                                                /*ParamInfos=*/nullptr,
12426                                                TransParamTypes, &TransParams,
12427                                                ExtParamInfos))
12428     return ExprError();
12429 
12430   for (ParmVarDecl *Param : TransParams)
12431     Param->setDeclContext(Body);
12432 
12433   SmallVector<concepts::Requirement *, 4> TransReqs;
12434   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12435                                                      TransReqs))
12436     return ExprError();
12437 
12438   for (concepts::Requirement *Req : TransReqs) {
12439     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12440       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12441         ER->getReturnTypeRequirement()
12442                 .getTypeConstraintTemplateParameterList()->getParam(0)
12443                 ->setDeclContext(Body);
12444       }
12445     }
12446   }
12447 
12448   return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12449                                           TransParams, TransReqs,
12450                                           E->getRBraceLoc());
12451 }
12452 
12453 template<typename Derived>
12454 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12455     ArrayRef<concepts::Requirement *> Reqs,
12456     SmallVectorImpl<concepts::Requirement *> &Transformed) {
12457   for (concepts::Requirement *Req : Reqs) {
12458     concepts::Requirement *TransReq = nullptr;
12459     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12460       TransReq = getDerived().TransformTypeRequirement(TypeReq);
12461     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12462       TransReq = getDerived().TransformExprRequirement(ExprReq);
12463     else
12464       TransReq = getDerived().TransformNestedRequirement(
12465                      cast<concepts::NestedRequirement>(Req));
12466     if (!TransReq)
12467       return true;
12468     Transformed.push_back(TransReq);
12469   }
12470   return false;
12471 }
12472 
12473 template<typename Derived>
12474 concepts::TypeRequirement *
12475 TreeTransform<Derived>::TransformTypeRequirement(
12476     concepts::TypeRequirement *Req) {
12477   if (Req->isSubstitutionFailure()) {
12478     if (getDerived().AlwaysRebuild())
12479       return getDerived().RebuildTypeRequirement(
12480               Req->getSubstitutionDiagnostic());
12481     return Req;
12482   }
12483   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12484   if (!TransType)
12485     return nullptr;
12486   return getDerived().RebuildTypeRequirement(TransType);
12487 }
12488 
12489 template<typename Derived>
12490 concepts::ExprRequirement *
12491 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12492   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12493   if (Req->isExprSubstitutionFailure())
12494     TransExpr = Req->getExprSubstitutionDiagnostic();
12495   else {
12496     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12497     if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12498       TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12499     if (TransExprRes.isInvalid())
12500       return nullptr;
12501     TransExpr = TransExprRes.get();
12502   }
12503 
12504   llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12505   const auto &RetReq = Req->getReturnTypeRequirement();
12506   if (RetReq.isEmpty())
12507     TransRetReq.emplace();
12508   else if (RetReq.isSubstitutionFailure())
12509     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12510   else if (RetReq.isTypeConstraint()) {
12511     TemplateParameterList *OrigTPL =
12512         RetReq.getTypeConstraintTemplateParameterList();
12513     TemplateParameterList *TPL =
12514         getDerived().TransformTemplateParameterList(OrigTPL);
12515     if (!TPL)
12516       return nullptr;
12517     TransRetReq.emplace(TPL);
12518   }
12519   assert(TransRetReq.hasValue() &&
12520          "All code paths leading here must set TransRetReq");
12521   if (Expr *E = TransExpr.dyn_cast<Expr *>())
12522     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12523                                                Req->getNoexceptLoc(),
12524                                                std::move(*TransRetReq));
12525   return getDerived().RebuildExprRequirement(
12526       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12527       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12528 }
12529 
12530 template<typename Derived>
12531 concepts::NestedRequirement *
12532 TreeTransform<Derived>::TransformNestedRequirement(
12533     concepts::NestedRequirement *Req) {
12534   if (Req->isSubstitutionFailure()) {
12535     if (getDerived().AlwaysRebuild())
12536       return getDerived().RebuildNestedRequirement(
12537           Req->getSubstitutionDiagnostic());
12538     return Req;
12539   }
12540   ExprResult TransConstraint =
12541       getDerived().TransformExpr(Req->getConstraintExpr());
12542   if (TransConstraint.isInvalid())
12543     return nullptr;
12544   return getDerived().RebuildNestedRequirement(TransConstraint.get());
12545 }
12546 
12547 template<typename Derived>
12548 ExprResult
12549 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12550   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12551   if (!T)
12552     return ExprError();
12553 
12554   if (!getDerived().AlwaysRebuild() &&
12555       T == E->getQueriedTypeSourceInfo())
12556     return E;
12557 
12558   ExprResult SubExpr;
12559   {
12560     EnterExpressionEvaluationContext Unevaluated(
12561         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12562     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12563     if (SubExpr.isInvalid())
12564       return ExprError();
12565 
12566     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12567       return E;
12568   }
12569 
12570   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12571                                             SubExpr.get(), E->getEndLoc());
12572 }
12573 
12574 template<typename Derived>
12575 ExprResult
12576 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12577   ExprResult SubExpr;
12578   {
12579     EnterExpressionEvaluationContext Unevaluated(
12580         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12581     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12582     if (SubExpr.isInvalid())
12583       return ExprError();
12584 
12585     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12586       return E;
12587   }
12588 
12589   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12590                                              SubExpr.get(), E->getEndLoc());
12591 }
12592 
12593 template <typename Derived>
12594 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12595     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12596     TypeSourceInfo **RecoveryTSI) {
12597   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
12598       DRE, AddrTaken, RecoveryTSI);
12599 
12600   // Propagate both errors and recovered types, which return ExprEmpty.
12601   if (!NewDRE.isUsable())
12602     return NewDRE;
12603 
12604   // We got an expr, wrap it up in parens.
12605   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
12606     return PE;
12607   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
12608                                        PE->getRParen());
12609 }
12610 
12611 template <typename Derived>
12612 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12613     DependentScopeDeclRefExpr *E) {
12614   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
12615                                             nullptr);
12616 }
12617 
12618 template <typename Derived>
12619 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12620     DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
12621     TypeSourceInfo **RecoveryTSI) {
12622   assert(E->getQualifierLoc());
12623   NestedNameSpecifierLoc QualifierLoc =
12624       getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
12625   if (!QualifierLoc)
12626     return ExprError();
12627   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12628 
12629   // TODO: If this is a conversion-function-id, verify that the
12630   // destination type name (if present) resolves the same way after
12631   // instantiation as it did in the local scope.
12632 
12633   DeclarationNameInfo NameInfo =
12634       getDerived().TransformDeclarationNameInfo(E->getNameInfo());
12635   if (!NameInfo.getName())
12636     return ExprError();
12637 
12638   if (!E->hasExplicitTemplateArgs()) {
12639     if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
12640         // Note: it is sufficient to compare the Name component of NameInfo:
12641         // if name has not changed, DNLoc has not changed either.
12642         NameInfo.getName() == E->getDeclName())
12643       return E;
12644 
12645     return getDerived().RebuildDependentScopeDeclRefExpr(
12646         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
12647         IsAddressOfOperand, RecoveryTSI);
12648   }
12649 
12650   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12651   if (getDerived().TransformTemplateArguments(
12652           E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
12653     return ExprError();
12654 
12655   return getDerived().RebuildDependentScopeDeclRefExpr(
12656       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
12657       RecoveryTSI);
12658 }
12659 
12660 template<typename Derived>
12661 ExprResult
12662 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
12663   // CXXConstructExprs other than for list-initialization and
12664   // CXXTemporaryObjectExpr are always implicit, so when we have
12665   // a 1-argument construction we just transform that argument.
12666   if (getDerived().AllowSkippingCXXConstructExpr() &&
12667       ((E->getNumArgs() == 1 ||
12668         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
12669        (!getDerived().DropCallArgument(E->getArg(0))) &&
12670        !E->isListInitialization()))
12671     return getDerived().TransformInitializer(E->getArg(0),
12672                                              /*DirectInit*/ false);
12673 
12674   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
12675 
12676   QualType T = getDerived().TransformType(E->getType());
12677   if (T.isNull())
12678     return ExprError();
12679 
12680   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12681       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12682   if (!Constructor)
12683     return ExprError();
12684 
12685   bool ArgumentChanged = false;
12686   SmallVector<Expr*, 8> Args;
12687   {
12688     EnterExpressionEvaluationContext Context(
12689         getSema(), EnterExpressionEvaluationContext::InitList,
12690         E->isListInitialization());
12691     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12692                                     &ArgumentChanged))
12693       return ExprError();
12694   }
12695 
12696   if (!getDerived().AlwaysRebuild() &&
12697       T == E->getType() &&
12698       Constructor == E->getConstructor() &&
12699       !ArgumentChanged) {
12700     // Mark the constructor as referenced.
12701     // FIXME: Instantiation-specific
12702     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12703     return E;
12704   }
12705 
12706   return getDerived().RebuildCXXConstructExpr(
12707       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
12708       E->hadMultipleCandidates(), E->isListInitialization(),
12709       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
12710       E->getConstructionKind(), E->getParenOrBraceRange());
12711 }
12712 
12713 template<typename Derived>
12714 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
12715     CXXInheritedCtorInitExpr *E) {
12716   QualType T = getDerived().TransformType(E->getType());
12717   if (T.isNull())
12718     return ExprError();
12719 
12720   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12721       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12722   if (!Constructor)
12723     return ExprError();
12724 
12725   if (!getDerived().AlwaysRebuild() &&
12726       T == E->getType() &&
12727       Constructor == E->getConstructor()) {
12728     // Mark the constructor as referenced.
12729     // FIXME: Instantiation-specific
12730     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12731     return E;
12732   }
12733 
12734   return getDerived().RebuildCXXInheritedCtorInitExpr(
12735       T, E->getLocation(), Constructor,
12736       E->constructsVBase(), E->inheritedFromVBase());
12737 }
12738 
12739 /// Transform a C++ temporary-binding expression.
12740 ///
12741 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
12742 /// transform the subexpression and return that.
12743 template<typename Derived>
12744 ExprResult
12745 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12746   return getDerived().TransformExpr(E->getSubExpr());
12747 }
12748 
12749 /// Transform a C++ expression that contains cleanups that should
12750 /// be run after the expression is evaluated.
12751 ///
12752 /// Since ExprWithCleanups nodes are implicitly generated, we
12753 /// just transform the subexpression and return that.
12754 template<typename Derived>
12755 ExprResult
12756 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
12757   return getDerived().TransformExpr(E->getSubExpr());
12758 }
12759 
12760 template<typename Derived>
12761 ExprResult
12762 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
12763                                                     CXXTemporaryObjectExpr *E) {
12764   TypeSourceInfo *T =
12765       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12766   if (!T)
12767     return ExprError();
12768 
12769   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12770       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12771   if (!Constructor)
12772     return ExprError();
12773 
12774   bool ArgumentChanged = false;
12775   SmallVector<Expr*, 8> Args;
12776   Args.reserve(E->getNumArgs());
12777   {
12778     EnterExpressionEvaluationContext Context(
12779         getSema(), EnterExpressionEvaluationContext::InitList,
12780         E->isListInitialization());
12781     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12782                        &ArgumentChanged))
12783       return ExprError();
12784   }
12785 
12786   if (!getDerived().AlwaysRebuild() &&
12787       T == E->getTypeSourceInfo() &&
12788       Constructor == E->getConstructor() &&
12789       !ArgumentChanged) {
12790     // FIXME: Instantiation-specific
12791     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12792     return SemaRef.MaybeBindToTemporary(E);
12793   }
12794 
12795   // FIXME: We should just pass E->isListInitialization(), but we're not
12796   // prepared to handle list-initialization without a child InitListExpr.
12797   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
12798   return getDerived().RebuildCXXTemporaryObjectExpr(
12799       T, LParenLoc, Args, E->getEndLoc(),
12800       /*ListInitialization=*/LParenLoc.isInvalid());
12801 }
12802 
12803 template<typename Derived>
12804 ExprResult
12805 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
12806   // Transform any init-capture expressions before entering the scope of the
12807   // lambda body, because they are not semantically within that scope.
12808   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
12809   struct TransformedInitCapture {
12810     // The location of the ... if the result is retaining a pack expansion.
12811     SourceLocation EllipsisLoc;
12812     // Zero or more expansions of the init-capture.
12813     SmallVector<InitCaptureInfoTy, 4> Expansions;
12814   };
12815   SmallVector<TransformedInitCapture, 4> InitCaptures;
12816   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
12817   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12818                                     CEnd = E->capture_end();
12819        C != CEnd; ++C) {
12820     if (!E->isInitCapture(C))
12821       continue;
12822 
12823     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
12824     VarDecl *OldVD = C->getCapturedVar();
12825 
12826     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
12827                                 Optional<unsigned> NumExpansions) {
12828       ExprResult NewExprInitResult = getDerived().TransformInitializer(
12829           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
12830 
12831       if (NewExprInitResult.isInvalid()) {
12832         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
12833         return;
12834       }
12835       Expr *NewExprInit = NewExprInitResult.get();
12836 
12837       QualType NewInitCaptureType =
12838           getSema().buildLambdaInitCaptureInitialization(
12839               C->getLocation(), OldVD->getType()->isReferenceType(),
12840               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
12841               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
12842               NewExprInit);
12843       Result.Expansions.push_back(
12844           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
12845     };
12846 
12847     // If this is an init-capture pack, consider expanding the pack now.
12848     if (OldVD->isParameterPack()) {
12849       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
12850                                              ->getTypeLoc()
12851                                              .castAs<PackExpansionTypeLoc>();
12852       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12853       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
12854 
12855       // Determine whether the set of unexpanded parameter packs can and should
12856       // be expanded.
12857       bool Expand = true;
12858       bool RetainExpansion = false;
12859       Optional<unsigned> OrigNumExpansions =
12860           ExpansionTL.getTypePtr()->getNumExpansions();
12861       Optional<unsigned> NumExpansions = OrigNumExpansions;
12862       if (getDerived().TryExpandParameterPacks(
12863               ExpansionTL.getEllipsisLoc(),
12864               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
12865               RetainExpansion, NumExpansions))
12866         return ExprError();
12867       if (Expand) {
12868         for (unsigned I = 0; I != *NumExpansions; ++I) {
12869           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12870           SubstInitCapture(SourceLocation(), None);
12871         }
12872       }
12873       if (!Expand || RetainExpansion) {
12874         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12875         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
12876         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
12877       }
12878     } else {
12879       SubstInitCapture(SourceLocation(), None);
12880     }
12881   }
12882 
12883   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
12884   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
12885 
12886   // Transform the template parameters, and add them to the current
12887   // instantiation scope. The null case is handled correctly.
12888   auto TPL = getDerived().TransformTemplateParameterList(
12889       E->getTemplateParameterList());
12890   LSI->GLTemplateParameterList = TPL;
12891 
12892   // Transform the type of the original lambda's call operator.
12893   // The transformation MUST be done in the CurrentInstantiationScope since
12894   // it introduces a mapping of the original to the newly created
12895   // transformed parameters.
12896   TypeSourceInfo *NewCallOpTSI = nullptr;
12897   {
12898     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
12899     FunctionProtoTypeLoc OldCallOpFPTL =
12900         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
12901 
12902     TypeLocBuilder NewCallOpTLBuilder;
12903     SmallVector<QualType, 4> ExceptionStorage;
12904     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
12905     QualType NewCallOpType = TransformFunctionProtoType(
12906         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
12907         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
12908           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
12909                                               ExceptionStorage, Changed);
12910         });
12911     if (NewCallOpType.isNull())
12912       return ExprError();
12913     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
12914                                                         NewCallOpType);
12915   }
12916 
12917   // Transform the trailing requires clause
12918   ExprResult NewTrailingRequiresClause;
12919   if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
12920     // FIXME: Concepts: Substitution into requires clause should only happen
12921     //                  when checking satisfaction.
12922     NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
12923 
12924   // Create the local class that will describe the lambda.
12925   // FIXME: KnownDependent below is wrong when substituting inside a templated
12926   // context that isn't a DeclContext (such as a variable template).
12927   CXXRecordDecl *OldClass = E->getLambdaClass();
12928   CXXRecordDecl *Class
12929     = getSema().createLambdaClosureType(E->getIntroducerRange(),
12930                                         NewCallOpTSI,
12931                                         /*KnownDependent=*/false,
12932                                         E->getCaptureDefault());
12933   getDerived().transformedLocalDecl(OldClass, {Class});
12934 
12935   Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling;
12936   if (getDerived().ReplacingOriginal())
12937     Mangling = std::make_tuple(OldClass->hasKnownLambdaInternalLinkage(),
12938                                OldClass->getLambdaManglingNumber(),
12939                                OldClass->getDeviceLambdaManglingNumber(),
12940                                OldClass->getLambdaContextDecl());
12941 
12942   // Build the call operator.
12943   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
12944       Class, E->getIntroducerRange(), NewCallOpTSI,
12945       E->getCallOperator()->getEndLoc(),
12946       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
12947       E->getCallOperator()->getConstexprKind(),
12948       NewTrailingRequiresClause.get());
12949 
12950   LSI->CallOperator = NewCallOperator;
12951 
12952   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
12953   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
12954 
12955   // Number the lambda for linkage purposes if necessary.
12956   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
12957 
12958   // Introduce the context of the call operator.
12959   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
12960                                  /*NewThisContext*/false);
12961 
12962   // Enter the scope of the lambda.
12963   getSema().buildLambdaScope(LSI, NewCallOperator,
12964                              E->getIntroducerRange(),
12965                              E->getCaptureDefault(),
12966                              E->getCaptureDefaultLoc(),
12967                              E->hasExplicitParameters(),
12968                              E->hasExplicitResultType(),
12969                              E->isMutable());
12970 
12971   bool Invalid = false;
12972 
12973   // Transform captures.
12974   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12975                                  CEnd = E->capture_end();
12976        C != CEnd; ++C) {
12977     // When we hit the first implicit capture, tell Sema that we've finished
12978     // the list of explicit captures.
12979     if (C->isImplicit())
12980       break;
12981 
12982     // Capturing 'this' is trivial.
12983     if (C->capturesThis()) {
12984       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
12985                                     /*BuildAndDiagnose*/ true, nullptr,
12986                                     C->getCaptureKind() == LCK_StarThis);
12987       continue;
12988     }
12989     // Captured expression will be recaptured during captured variables
12990     // rebuilding.
12991     if (C->capturesVLAType())
12992       continue;
12993 
12994     // Rebuild init-captures, including the implied field declaration.
12995     if (E->isInitCapture(C)) {
12996       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
12997 
12998       VarDecl *OldVD = C->getCapturedVar();
12999       llvm::SmallVector<Decl*, 4> NewVDs;
13000 
13001       for (InitCaptureInfoTy &Info : NewC.Expansions) {
13002         ExprResult Init = Info.first;
13003         QualType InitQualType = Info.second;
13004         if (Init.isInvalid() || InitQualType.isNull()) {
13005           Invalid = true;
13006           break;
13007         }
13008         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13009             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13010             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
13011         if (!NewVD) {
13012           Invalid = true;
13013           break;
13014         }
13015         NewVDs.push_back(NewVD);
13016         getSema().addInitCapture(LSI, NewVD);
13017       }
13018 
13019       if (Invalid)
13020         break;
13021 
13022       getDerived().transformedLocalDecl(OldVD, NewVDs);
13023       continue;
13024     }
13025 
13026     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13027 
13028     // Determine the capture kind for Sema.
13029     Sema::TryCaptureKind Kind
13030       = C->isImplicit()? Sema::TryCapture_Implicit
13031                        : C->getCaptureKind() == LCK_ByCopy
13032                            ? Sema::TryCapture_ExplicitByVal
13033                            : Sema::TryCapture_ExplicitByRef;
13034     SourceLocation EllipsisLoc;
13035     if (C->isPackExpansion()) {
13036       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13037       bool ShouldExpand = false;
13038       bool RetainExpansion = false;
13039       Optional<unsigned> NumExpansions;
13040       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13041                                                C->getLocation(),
13042                                                Unexpanded,
13043                                                ShouldExpand, RetainExpansion,
13044                                                NumExpansions)) {
13045         Invalid = true;
13046         continue;
13047       }
13048 
13049       if (ShouldExpand) {
13050         // The transform has determined that we should perform an expansion;
13051         // transform and capture each of the arguments.
13052         // expansion of the pattern. Do so.
13053         VarDecl *Pack = C->getCapturedVar();
13054         for (unsigned I = 0; I != *NumExpansions; ++I) {
13055           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13056           VarDecl *CapturedVar
13057             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13058                                                                Pack));
13059           if (!CapturedVar) {
13060             Invalid = true;
13061             continue;
13062           }
13063 
13064           // Capture the transformed variable.
13065           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13066         }
13067 
13068         // FIXME: Retain a pack expansion if RetainExpansion is true.
13069 
13070         continue;
13071       }
13072 
13073       EllipsisLoc = C->getEllipsisLoc();
13074     }
13075 
13076     // Transform the captured variable.
13077     VarDecl *CapturedVar
13078       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13079                                                          C->getCapturedVar()));
13080     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13081       Invalid = true;
13082       continue;
13083     }
13084 
13085     // Capture the transformed variable.
13086     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13087                                  EllipsisLoc);
13088   }
13089   getSema().finishLambdaExplicitCaptures(LSI);
13090 
13091   // FIXME: Sema's lambda-building mechanism expects us to push an expression
13092   // evaluation context even if we're not transforming the function body.
13093   getSema().PushExpressionEvaluationContext(
13094       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13095 
13096   // Instantiate the body of the lambda expression.
13097   StmtResult Body =
13098       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13099 
13100   // ActOnLambda* will pop the function scope for us.
13101   FuncScopeCleanup.disable();
13102 
13103   if (Body.isInvalid()) {
13104     SavedContext.pop();
13105     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13106                                /*IsInstantiation=*/true);
13107     return ExprError();
13108   }
13109 
13110   // Copy the LSI before ActOnFinishFunctionBody removes it.
13111   // FIXME: This is dumb. Store the lambda information somewhere that outlives
13112   // the call operator.
13113   auto LSICopy = *LSI;
13114   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13115                                     /*IsInstantiation*/ true);
13116   SavedContext.pop();
13117 
13118   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13119                                    &LSICopy);
13120 }
13121 
13122 template<typename Derived>
13123 StmtResult
13124 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13125   return TransformStmt(S);
13126 }
13127 
13128 template<typename Derived>
13129 StmtResult
13130 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13131   // Transform captures.
13132   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13133                                  CEnd = E->capture_end();
13134        C != CEnd; ++C) {
13135     // When we hit the first implicit capture, tell Sema that we've finished
13136     // the list of explicit captures.
13137     if (!C->isImplicit())
13138       continue;
13139 
13140     // Capturing 'this' is trivial.
13141     if (C->capturesThis()) {
13142       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13143                                     /*BuildAndDiagnose*/ true, nullptr,
13144                                     C->getCaptureKind() == LCK_StarThis);
13145       continue;
13146     }
13147     // Captured expression will be recaptured during captured variables
13148     // rebuilding.
13149     if (C->capturesVLAType())
13150       continue;
13151 
13152     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13153     assert(!E->isInitCapture(C) && "implicit init-capture?");
13154 
13155     // Transform the captured variable.
13156     VarDecl *CapturedVar = cast_or_null<VarDecl>(
13157         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13158     if (!CapturedVar || CapturedVar->isInvalidDecl())
13159       return StmtError();
13160 
13161     // Capture the transformed variable.
13162     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13163   }
13164 
13165   return S;
13166 }
13167 
13168 template<typename Derived>
13169 ExprResult
13170 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13171                                                   CXXUnresolvedConstructExpr *E) {
13172   TypeSourceInfo *T =
13173       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13174   if (!T)
13175     return ExprError();
13176 
13177   bool ArgumentChanged = false;
13178   SmallVector<Expr*, 8> Args;
13179   Args.reserve(E->getNumArgs());
13180   {
13181     EnterExpressionEvaluationContext Context(
13182         getSema(), EnterExpressionEvaluationContext::InitList,
13183         E->isListInitialization());
13184     if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13185                                     &ArgumentChanged))
13186       return ExprError();
13187   }
13188 
13189   if (!getDerived().AlwaysRebuild() &&
13190       T == E->getTypeSourceInfo() &&
13191       !ArgumentChanged)
13192     return E;
13193 
13194   // FIXME: we're faking the locations of the commas
13195   return getDerived().RebuildCXXUnresolvedConstructExpr(
13196       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13197 }
13198 
13199 template<typename Derived>
13200 ExprResult
13201 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13202                                              CXXDependentScopeMemberExpr *E) {
13203   // Transform the base of the expression.
13204   ExprResult Base((Expr*) nullptr);
13205   Expr *OldBase;
13206   QualType BaseType;
13207   QualType ObjectType;
13208   if (!E->isImplicitAccess()) {
13209     OldBase = E->getBase();
13210     Base = getDerived().TransformExpr(OldBase);
13211     if (Base.isInvalid())
13212       return ExprError();
13213 
13214     // Start the member reference and compute the object's type.
13215     ParsedType ObjectTy;
13216     bool MayBePseudoDestructor = false;
13217     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13218                                                 E->getOperatorLoc(),
13219                                       E->isArrow()? tok::arrow : tok::period,
13220                                                 ObjectTy,
13221                                                 MayBePseudoDestructor);
13222     if (Base.isInvalid())
13223       return ExprError();
13224 
13225     ObjectType = ObjectTy.get();
13226     BaseType = ((Expr*) Base.get())->getType();
13227   } else {
13228     OldBase = nullptr;
13229     BaseType = getDerived().TransformType(E->getBaseType());
13230     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13231   }
13232 
13233   // Transform the first part of the nested-name-specifier that qualifies
13234   // the member name.
13235   NamedDecl *FirstQualifierInScope
13236     = getDerived().TransformFirstQualifierInScope(
13237                                             E->getFirstQualifierFoundInScope(),
13238                                             E->getQualifierLoc().getBeginLoc());
13239 
13240   NestedNameSpecifierLoc QualifierLoc;
13241   if (E->getQualifier()) {
13242     QualifierLoc
13243       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13244                                                      ObjectType,
13245                                                      FirstQualifierInScope);
13246     if (!QualifierLoc)
13247       return ExprError();
13248   }
13249 
13250   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13251 
13252   // TODO: If this is a conversion-function-id, verify that the
13253   // destination type name (if present) resolves the same way after
13254   // instantiation as it did in the local scope.
13255 
13256   DeclarationNameInfo NameInfo
13257     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13258   if (!NameInfo.getName())
13259     return ExprError();
13260 
13261   if (!E->hasExplicitTemplateArgs()) {
13262     // This is a reference to a member without an explicitly-specified
13263     // template argument list. Optimize for this common case.
13264     if (!getDerived().AlwaysRebuild() &&
13265         Base.get() == OldBase &&
13266         BaseType == E->getBaseType() &&
13267         QualifierLoc == E->getQualifierLoc() &&
13268         NameInfo.getName() == E->getMember() &&
13269         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13270       return E;
13271 
13272     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13273                                                        BaseType,
13274                                                        E->isArrow(),
13275                                                        E->getOperatorLoc(),
13276                                                        QualifierLoc,
13277                                                        TemplateKWLoc,
13278                                                        FirstQualifierInScope,
13279                                                        NameInfo,
13280                                                        /*TemplateArgs*/nullptr);
13281   }
13282 
13283   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13284   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13285                                               E->getNumTemplateArgs(),
13286                                               TransArgs))
13287     return ExprError();
13288 
13289   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13290                                                      BaseType,
13291                                                      E->isArrow(),
13292                                                      E->getOperatorLoc(),
13293                                                      QualifierLoc,
13294                                                      TemplateKWLoc,
13295                                                      FirstQualifierInScope,
13296                                                      NameInfo,
13297                                                      &TransArgs);
13298 }
13299 
13300 template <typename Derived>
13301 ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13302     UnresolvedMemberExpr *Old) {
13303   // Transform the base of the expression.
13304   ExprResult Base((Expr *)nullptr);
13305   QualType BaseType;
13306   if (!Old->isImplicitAccess()) {
13307     Base = getDerived().TransformExpr(Old->getBase());
13308     if (Base.isInvalid())
13309       return ExprError();
13310     Base =
13311         getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13312     if (Base.isInvalid())
13313       return ExprError();
13314     BaseType = Base.get()->getType();
13315   } else {
13316     BaseType = getDerived().TransformType(Old->getBaseType());
13317   }
13318 
13319   NestedNameSpecifierLoc QualifierLoc;
13320   if (Old->getQualifierLoc()) {
13321     QualifierLoc =
13322         getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13323     if (!QualifierLoc)
13324       return ExprError();
13325   }
13326 
13327   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13328 
13329   LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13330 
13331   // Transform the declaration set.
13332   if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13333     return ExprError();
13334 
13335   // Determine the naming class.
13336   if (Old->getNamingClass()) {
13337     CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13338         getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13339     if (!NamingClass)
13340       return ExprError();
13341 
13342     R.setNamingClass(NamingClass);
13343   }
13344 
13345   TemplateArgumentListInfo TransArgs;
13346   if (Old->hasExplicitTemplateArgs()) {
13347     TransArgs.setLAngleLoc(Old->getLAngleLoc());
13348     TransArgs.setRAngleLoc(Old->getRAngleLoc());
13349     if (getDerived().TransformTemplateArguments(
13350             Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13351       return ExprError();
13352   }
13353 
13354   // FIXME: to do this check properly, we will need to preserve the
13355   // first-qualifier-in-scope here, just in case we had a dependent
13356   // base (and therefore couldn't do the check) and a
13357   // nested-name-qualifier (and therefore could do the lookup).
13358   NamedDecl *FirstQualifierInScope = nullptr;
13359 
13360   return getDerived().RebuildUnresolvedMemberExpr(
13361       Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13362       TemplateKWLoc, FirstQualifierInScope, R,
13363       (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13364 }
13365 
13366 template<typename Derived>
13367 ExprResult
13368 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13369   EnterExpressionEvaluationContext Unevaluated(
13370       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13371   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13372   if (SubExpr.isInvalid())
13373     return ExprError();
13374 
13375   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13376     return E;
13377 
13378   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13379 }
13380 
13381 template<typename Derived>
13382 ExprResult
13383 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13384   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13385   if (Pattern.isInvalid())
13386     return ExprError();
13387 
13388   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13389     return E;
13390 
13391   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13392                                            E->getNumExpansions());
13393 }
13394 
13395 template<typename Derived>
13396 ExprResult
13397 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13398   // If E is not value-dependent, then nothing will change when we transform it.
13399   // Note: This is an instantiation-centric view.
13400   if (!E->isValueDependent())
13401     return E;
13402 
13403   EnterExpressionEvaluationContext Unevaluated(
13404       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13405 
13406   ArrayRef<TemplateArgument> PackArgs;
13407   TemplateArgument ArgStorage;
13408 
13409   // Find the argument list to transform.
13410   if (E->isPartiallySubstituted()) {
13411     PackArgs = E->getPartialArguments();
13412   } else if (E->isValueDependent()) {
13413     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13414     bool ShouldExpand = false;
13415     bool RetainExpansion = false;
13416     Optional<unsigned> NumExpansions;
13417     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13418                                              Unexpanded,
13419                                              ShouldExpand, RetainExpansion,
13420                                              NumExpansions))
13421       return ExprError();
13422 
13423     // If we need to expand the pack, build a template argument from it and
13424     // expand that.
13425     if (ShouldExpand) {
13426       auto *Pack = E->getPack();
13427       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13428         ArgStorage = getSema().Context.getPackExpansionType(
13429             getSema().Context.getTypeDeclType(TTPD), None);
13430       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13431         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
13432       } else {
13433         auto *VD = cast<ValueDecl>(Pack);
13434         ExprResult DRE = getSema().BuildDeclRefExpr(
13435             VD, VD->getType().getNonLValueExprType(getSema().Context),
13436             VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13437             E->getPackLoc());
13438         if (DRE.isInvalid())
13439           return ExprError();
13440         ArgStorage = new (getSema().Context) PackExpansionExpr(
13441             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
13442       }
13443       PackArgs = ArgStorage;
13444     }
13445   }
13446 
13447   // If we're not expanding the pack, just transform the decl.
13448   if (!PackArgs.size()) {
13449     auto *Pack = cast_or_null<NamedDecl>(
13450         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13451     if (!Pack)
13452       return ExprError();
13453     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
13454                                               E->getPackLoc(),
13455                                               E->getRParenLoc(), None, None);
13456   }
13457 
13458   // Try to compute the result without performing a partial substitution.
13459   Optional<unsigned> Result = 0;
13460   for (const TemplateArgument &Arg : PackArgs) {
13461     if (!Arg.isPackExpansion()) {
13462       Result = *Result + 1;
13463       continue;
13464     }
13465 
13466     TemplateArgumentLoc ArgLoc;
13467     InventTemplateArgumentLoc(Arg, ArgLoc);
13468 
13469     // Find the pattern of the pack expansion.
13470     SourceLocation Ellipsis;
13471     Optional<unsigned> OrigNumExpansions;
13472     TemplateArgumentLoc Pattern =
13473         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13474                                                           OrigNumExpansions);
13475 
13476     // Substitute under the pack expansion. Do not expand the pack (yet).
13477     TemplateArgumentLoc OutPattern;
13478     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13479     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13480                                                /*Uneval*/ true))
13481       return true;
13482 
13483     // See if we can determine the number of arguments from the result.
13484     Optional<unsigned> NumExpansions =
13485         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13486     if (!NumExpansions) {
13487       // No: we must be in an alias template expansion, and we're going to need
13488       // to actually expand the packs.
13489       Result = None;
13490       break;
13491     }
13492 
13493     Result = *Result + *NumExpansions;
13494   }
13495 
13496   // Common case: we could determine the number of expansions without
13497   // substituting.
13498   if (Result)
13499     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13500                                               E->getPackLoc(),
13501                                               E->getRParenLoc(), *Result, None);
13502 
13503   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13504                                                E->getPackLoc());
13505   {
13506     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13507     typedef TemplateArgumentLocInventIterator<
13508         Derived, const TemplateArgument*> PackLocIterator;
13509     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13510                                    PackLocIterator(*this, PackArgs.end()),
13511                                    TransformedPackArgs, /*Uneval*/true))
13512       return ExprError();
13513   }
13514 
13515   // Check whether we managed to fully-expand the pack.
13516   // FIXME: Is it possible for us to do so and not hit the early exit path?
13517   SmallVector<TemplateArgument, 8> Args;
13518   bool PartialSubstitution = false;
13519   for (auto &Loc : TransformedPackArgs.arguments()) {
13520     Args.push_back(Loc.getArgument());
13521     if (Loc.getArgument().isPackExpansion())
13522       PartialSubstitution = true;
13523   }
13524 
13525   if (PartialSubstitution)
13526     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13527                                               E->getPackLoc(),
13528                                               E->getRParenLoc(), None, Args);
13529 
13530   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13531                                             E->getPackLoc(), E->getRParenLoc(),
13532                                             Args.size(), None);
13533 }
13534 
13535 template<typename Derived>
13536 ExprResult
13537 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13538                                           SubstNonTypeTemplateParmPackExpr *E) {
13539   // Default behavior is to do nothing with this transformation.
13540   return E;
13541 }
13542 
13543 template<typename Derived>
13544 ExprResult
13545 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13546                                           SubstNonTypeTemplateParmExpr *E) {
13547   // Default behavior is to do nothing with this transformation.
13548   return E;
13549 }
13550 
13551 template<typename Derived>
13552 ExprResult
13553 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13554   // Default behavior is to do nothing with this transformation.
13555   return E;
13556 }
13557 
13558 template<typename Derived>
13559 ExprResult
13560 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13561                                                   MaterializeTemporaryExpr *E) {
13562   return getDerived().TransformExpr(E->getSubExpr());
13563 }
13564 
13565 template<typename Derived>
13566 ExprResult
13567 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13568   UnresolvedLookupExpr *Callee = nullptr;
13569   if (Expr *OldCallee = E->getCallee()) {
13570     ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13571     if (CalleeResult.isInvalid())
13572       return ExprError();
13573     Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13574   }
13575 
13576   Expr *Pattern = E->getPattern();
13577 
13578   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13579   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13580   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13581 
13582   // Determine whether the set of unexpanded parameter packs can and should
13583   // be expanded.
13584   bool Expand = true;
13585   bool RetainExpansion = false;
13586   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13587                      NumExpansions = OrigNumExpansions;
13588   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
13589                                            Pattern->getSourceRange(),
13590                                            Unexpanded,
13591                                            Expand, RetainExpansion,
13592                                            NumExpansions))
13593     return true;
13594 
13595   if (!Expand) {
13596     // Do not expand any packs here, just transform and rebuild a fold
13597     // expression.
13598     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13599 
13600     ExprResult LHS =
13601         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
13602     if (LHS.isInvalid())
13603       return true;
13604 
13605     ExprResult RHS =
13606         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
13607     if (RHS.isInvalid())
13608       return true;
13609 
13610     if (!getDerived().AlwaysRebuild() &&
13611         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
13612       return E;
13613 
13614     return getDerived().RebuildCXXFoldExpr(
13615         Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
13616         E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
13617   }
13618 
13619   // Formally a fold expression expands to nested parenthesized expressions.
13620   // Enforce this limit to avoid creating trees so deep we can't safely traverse
13621   // them.
13622   if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
13623     SemaRef.Diag(E->getEllipsisLoc(),
13624                  clang::diag::err_fold_expression_limit_exceeded)
13625         << *NumExpansions << SemaRef.getLangOpts().BracketDepth
13626         << E->getSourceRange();
13627     SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
13628     return ExprError();
13629   }
13630 
13631   // The transform has determined that we should perform an elementwise
13632   // expansion of the pattern. Do so.
13633   ExprResult Result = getDerived().TransformExpr(E->getInit());
13634   if (Result.isInvalid())
13635     return true;
13636   bool LeftFold = E->isLeftFold();
13637 
13638   // If we're retaining an expansion for a right fold, it is the innermost
13639   // component and takes the init (if any).
13640   if (!LeftFold && RetainExpansion) {
13641     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13642 
13643     ExprResult Out = getDerived().TransformExpr(Pattern);
13644     if (Out.isInvalid())
13645       return true;
13646 
13647     Result = getDerived().RebuildCXXFoldExpr(
13648         Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
13649         E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
13650     if (Result.isInvalid())
13651       return true;
13652   }
13653 
13654   for (unsigned I = 0; I != *NumExpansions; ++I) {
13655     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
13656         getSema(), LeftFold ? I : *NumExpansions - I - 1);
13657     ExprResult Out = getDerived().TransformExpr(Pattern);
13658     if (Out.isInvalid())
13659       return true;
13660 
13661     if (Out.get()->containsUnexpandedParameterPack()) {
13662       // We still have a pack; retain a pack expansion for this slice.
13663       Result = getDerived().RebuildCXXFoldExpr(
13664           Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
13665           E->getOperator(), E->getEllipsisLoc(),
13666           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
13667           OrigNumExpansions);
13668     } else if (Result.isUsable()) {
13669       // We've got down to a single element; build a binary operator.
13670       Expr *LHS = LeftFold ? Result.get() : Out.get();
13671       Expr *RHS = LeftFold ? Out.get() : Result.get();
13672       if (Callee)
13673         Result = getDerived().RebuildCXXOperatorCallExpr(
13674             BinaryOperator::getOverloadedOperator(E->getOperator()),
13675             E->getEllipsisLoc(), Callee, LHS, RHS);
13676       else
13677         Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
13678                                                     E->getOperator(), LHS, RHS);
13679     } else
13680       Result = Out;
13681 
13682     if (Result.isInvalid())
13683       return true;
13684   }
13685 
13686   // If we're retaining an expansion for a left fold, it is the outermost
13687   // component and takes the complete expansion so far as its init (if any).
13688   if (LeftFold && RetainExpansion) {
13689     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13690 
13691     ExprResult Out = getDerived().TransformExpr(Pattern);
13692     if (Out.isInvalid())
13693       return true;
13694 
13695     Result = getDerived().RebuildCXXFoldExpr(
13696         Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
13697         E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
13698     if (Result.isInvalid())
13699       return true;
13700   }
13701 
13702   // If we had no init and an empty pack, and we're not retaining an expansion,
13703   // then produce a fallback value or error.
13704   if (Result.isUnset())
13705     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
13706                                                 E->getOperator());
13707 
13708   return Result;
13709 }
13710 
13711 template<typename Derived>
13712 ExprResult
13713 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
13714     CXXStdInitializerListExpr *E) {
13715   return getDerived().TransformExpr(E->getSubExpr());
13716 }
13717 
13718 template<typename Derived>
13719 ExprResult
13720 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
13721   return SemaRef.MaybeBindToTemporary(E);
13722 }
13723 
13724 template<typename Derived>
13725 ExprResult
13726 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
13727   return E;
13728 }
13729 
13730 template<typename Derived>
13731 ExprResult
13732 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
13733   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
13734   if (SubExpr.isInvalid())
13735     return ExprError();
13736 
13737   if (!getDerived().AlwaysRebuild() &&
13738       SubExpr.get() == E->getSubExpr())
13739     return E;
13740 
13741   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
13742 }
13743 
13744 template<typename Derived>
13745 ExprResult
13746 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
13747   // Transform each of the elements.
13748   SmallVector<Expr *, 8> Elements;
13749   bool ArgChanged = false;
13750   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
13751                                   /*IsCall=*/false, Elements, &ArgChanged))
13752     return ExprError();
13753 
13754   if (!getDerived().AlwaysRebuild() && !ArgChanged)
13755     return SemaRef.MaybeBindToTemporary(E);
13756 
13757   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
13758                                               Elements.data(),
13759                                               Elements.size());
13760 }
13761 
13762 template<typename Derived>
13763 ExprResult
13764 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
13765                                                     ObjCDictionaryLiteral *E) {
13766   // Transform each of the elements.
13767   SmallVector<ObjCDictionaryElement, 8> Elements;
13768   bool ArgChanged = false;
13769   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
13770     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
13771 
13772     if (OrigElement.isPackExpansion()) {
13773       // This key/value element is a pack expansion.
13774       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13775       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
13776       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
13777       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13778 
13779       // Determine whether the set of unexpanded parameter packs can
13780       // and should be expanded.
13781       bool Expand = true;
13782       bool RetainExpansion = false;
13783       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
13784       Optional<unsigned> NumExpansions = OrigNumExpansions;
13785       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
13786                                OrigElement.Value->getEndLoc());
13787       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
13788                                                PatternRange, Unexpanded, Expand,
13789                                                RetainExpansion, NumExpansions))
13790         return ExprError();
13791 
13792       if (!Expand) {
13793         // The transform has determined that we should perform a simple
13794         // transformation on the pack expansion, producing another pack
13795         // expansion.
13796         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13797         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13798         if (Key.isInvalid())
13799           return ExprError();
13800 
13801         if (Key.get() != OrigElement.Key)
13802           ArgChanged = true;
13803 
13804         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13805         if (Value.isInvalid())
13806           return ExprError();
13807 
13808         if (Value.get() != OrigElement.Value)
13809           ArgChanged = true;
13810 
13811         ObjCDictionaryElement Expansion = {
13812           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
13813         };
13814         Elements.push_back(Expansion);
13815         continue;
13816       }
13817 
13818       // Record right away that the argument was changed.  This needs
13819       // to happen even if the array expands to nothing.
13820       ArgChanged = true;
13821 
13822       // The transform has determined that we should perform an elementwise
13823       // expansion of the pattern. Do so.
13824       for (unsigned I = 0; I != *NumExpansions; ++I) {
13825         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13826         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13827         if (Key.isInvalid())
13828           return ExprError();
13829 
13830         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13831         if (Value.isInvalid())
13832           return ExprError();
13833 
13834         ObjCDictionaryElement Element = {
13835           Key.get(), Value.get(), SourceLocation(), NumExpansions
13836         };
13837 
13838         // If any unexpanded parameter packs remain, we still have a
13839         // pack expansion.
13840         // FIXME: Can this really happen?
13841         if (Key.get()->containsUnexpandedParameterPack() ||
13842             Value.get()->containsUnexpandedParameterPack())
13843           Element.EllipsisLoc = OrigElement.EllipsisLoc;
13844 
13845         Elements.push_back(Element);
13846       }
13847 
13848       // FIXME: Retain a pack expansion if RetainExpansion is true.
13849 
13850       // We've finished with this pack expansion.
13851       continue;
13852     }
13853 
13854     // Transform and check key.
13855     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13856     if (Key.isInvalid())
13857       return ExprError();
13858 
13859     if (Key.get() != OrigElement.Key)
13860       ArgChanged = true;
13861 
13862     // Transform and check value.
13863     ExprResult Value
13864       = getDerived().TransformExpr(OrigElement.Value);
13865     if (Value.isInvalid())
13866       return ExprError();
13867 
13868     if (Value.get() != OrigElement.Value)
13869       ArgChanged = true;
13870 
13871     ObjCDictionaryElement Element = {
13872       Key.get(), Value.get(), SourceLocation(), None
13873     };
13874     Elements.push_back(Element);
13875   }
13876 
13877   if (!getDerived().AlwaysRebuild() && !ArgChanged)
13878     return SemaRef.MaybeBindToTemporary(E);
13879 
13880   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
13881                                                    Elements);
13882 }
13883 
13884 template<typename Derived>
13885 ExprResult
13886 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
13887   TypeSourceInfo *EncodedTypeInfo
13888     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
13889   if (!EncodedTypeInfo)
13890     return ExprError();
13891 
13892   if (!getDerived().AlwaysRebuild() &&
13893       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
13894     return E;
13895 
13896   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
13897                                             EncodedTypeInfo,
13898                                             E->getRParenLoc());
13899 }
13900 
13901 template<typename Derived>
13902 ExprResult TreeTransform<Derived>::
13903 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
13904   // This is a kind of implicit conversion, and it needs to get dropped
13905   // and recomputed for the same general reasons that ImplicitCastExprs
13906   // do, as well a more specific one: this expression is only valid when
13907   // it appears *immediately* as an argument expression.
13908   return getDerived().TransformExpr(E->getSubExpr());
13909 }
13910 
13911 template<typename Derived>
13912 ExprResult TreeTransform<Derived>::
13913 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
13914   TypeSourceInfo *TSInfo
13915     = getDerived().TransformType(E->getTypeInfoAsWritten());
13916   if (!TSInfo)
13917     return ExprError();
13918 
13919   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
13920   if (Result.isInvalid())
13921     return ExprError();
13922 
13923   if (!getDerived().AlwaysRebuild() &&
13924       TSInfo == E->getTypeInfoAsWritten() &&
13925       Result.get() == E->getSubExpr())
13926     return E;
13927 
13928   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
13929                                       E->getBridgeKeywordLoc(), TSInfo,
13930                                       Result.get());
13931 }
13932 
13933 template <typename Derived>
13934 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
13935     ObjCAvailabilityCheckExpr *E) {
13936   return E;
13937 }
13938 
13939 template<typename Derived>
13940 ExprResult
13941 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
13942   // Transform arguments.
13943   bool ArgChanged = false;
13944   SmallVector<Expr*, 8> Args;
13945   Args.reserve(E->getNumArgs());
13946   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
13947                                   &ArgChanged))
13948     return ExprError();
13949 
13950   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
13951     // Class message: transform the receiver type.
13952     TypeSourceInfo *ReceiverTypeInfo
13953       = getDerived().TransformType(E->getClassReceiverTypeInfo());
13954     if (!ReceiverTypeInfo)
13955       return ExprError();
13956 
13957     // If nothing changed, just retain the existing message send.
13958     if (!getDerived().AlwaysRebuild() &&
13959         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
13960       return SemaRef.MaybeBindToTemporary(E);
13961 
13962     // Build a new class message send.
13963     SmallVector<SourceLocation, 16> SelLocs;
13964     E->getSelectorLocs(SelLocs);
13965     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
13966                                                E->getSelector(),
13967                                                SelLocs,
13968                                                E->getMethodDecl(),
13969                                                E->getLeftLoc(),
13970                                                Args,
13971                                                E->getRightLoc());
13972   }
13973   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
13974            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13975     if (!E->getMethodDecl())
13976       return ExprError();
13977 
13978     // Build a new class message send to 'super'.
13979     SmallVector<SourceLocation, 16> SelLocs;
13980     E->getSelectorLocs(SelLocs);
13981     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
13982                                                E->getSelector(),
13983                                                SelLocs,
13984                                                E->getReceiverType(),
13985                                                E->getMethodDecl(),
13986                                                E->getLeftLoc(),
13987                                                Args,
13988                                                E->getRightLoc());
13989   }
13990 
13991   // Instance message: transform the receiver
13992   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
13993          "Only class and instance messages may be instantiated");
13994   ExprResult Receiver
13995     = getDerived().TransformExpr(E->getInstanceReceiver());
13996   if (Receiver.isInvalid())
13997     return ExprError();
13998 
13999   // If nothing changed, just retain the existing message send.
14000   if (!getDerived().AlwaysRebuild() &&
14001       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14002     return SemaRef.MaybeBindToTemporary(E);
14003 
14004   // Build a new instance message send.
14005   SmallVector<SourceLocation, 16> SelLocs;
14006   E->getSelectorLocs(SelLocs);
14007   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14008                                              E->getSelector(),
14009                                              SelLocs,
14010                                              E->getMethodDecl(),
14011                                              E->getLeftLoc(),
14012                                              Args,
14013                                              E->getRightLoc());
14014 }
14015 
14016 template<typename Derived>
14017 ExprResult
14018 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14019   return E;
14020 }
14021 
14022 template<typename Derived>
14023 ExprResult
14024 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14025   return E;
14026 }
14027 
14028 template<typename Derived>
14029 ExprResult
14030 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14031   // Transform the base expression.
14032   ExprResult Base = getDerived().TransformExpr(E->getBase());
14033   if (Base.isInvalid())
14034     return ExprError();
14035 
14036   // We don't need to transform the ivar; it will never change.
14037 
14038   // If nothing changed, just retain the existing expression.
14039   if (!getDerived().AlwaysRebuild() &&
14040       Base.get() == E->getBase())
14041     return E;
14042 
14043   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14044                                              E->getLocation(),
14045                                              E->isArrow(), E->isFreeIvar());
14046 }
14047 
14048 template<typename Derived>
14049 ExprResult
14050 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14051   // 'super' and types never change. Property never changes. Just
14052   // retain the existing expression.
14053   if (!E->isObjectReceiver())
14054     return E;
14055 
14056   // Transform the base expression.
14057   ExprResult Base = getDerived().TransformExpr(E->getBase());
14058   if (Base.isInvalid())
14059     return ExprError();
14060 
14061   // We don't need to transform the property; it will never change.
14062 
14063   // If nothing changed, just retain the existing expression.
14064   if (!getDerived().AlwaysRebuild() &&
14065       Base.get() == E->getBase())
14066     return E;
14067 
14068   if (E->isExplicitProperty())
14069     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14070                                                    E->getExplicitProperty(),
14071                                                    E->getLocation());
14072 
14073   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14074                                                  SemaRef.Context.PseudoObjectTy,
14075                                                  E->getImplicitPropertyGetter(),
14076                                                  E->getImplicitPropertySetter(),
14077                                                  E->getLocation());
14078 }
14079 
14080 template<typename Derived>
14081 ExprResult
14082 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14083   // Transform the base expression.
14084   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14085   if (Base.isInvalid())
14086     return ExprError();
14087 
14088   // Transform the key expression.
14089   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14090   if (Key.isInvalid())
14091     return ExprError();
14092 
14093   // If nothing changed, just retain the existing expression.
14094   if (!getDerived().AlwaysRebuild() &&
14095       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14096     return E;
14097 
14098   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14099                                                   Base.get(), Key.get(),
14100                                                   E->getAtIndexMethodDecl(),
14101                                                   E->setAtIndexMethodDecl());
14102 }
14103 
14104 template<typename Derived>
14105 ExprResult
14106 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14107   // Transform the base expression.
14108   ExprResult Base = getDerived().TransformExpr(E->getBase());
14109   if (Base.isInvalid())
14110     return ExprError();
14111 
14112   // If nothing changed, just retain the existing expression.
14113   if (!getDerived().AlwaysRebuild() &&
14114       Base.get() == E->getBase())
14115     return E;
14116 
14117   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14118                                          E->getOpLoc(),
14119                                          E->isArrow());
14120 }
14121 
14122 template<typename Derived>
14123 ExprResult
14124 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14125   bool ArgumentChanged = false;
14126   SmallVector<Expr*, 8> SubExprs;
14127   SubExprs.reserve(E->getNumSubExprs());
14128   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14129                                   SubExprs, &ArgumentChanged))
14130     return ExprError();
14131 
14132   if (!getDerived().AlwaysRebuild() &&
14133       !ArgumentChanged)
14134     return E;
14135 
14136   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14137                                                SubExprs,
14138                                                E->getRParenLoc());
14139 }
14140 
14141 template<typename Derived>
14142 ExprResult
14143 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14144   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14145   if (SrcExpr.isInvalid())
14146     return ExprError();
14147 
14148   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14149   if (!Type)
14150     return ExprError();
14151 
14152   if (!getDerived().AlwaysRebuild() &&
14153       Type == E->getTypeSourceInfo() &&
14154       SrcExpr.get() == E->getSrcExpr())
14155     return E;
14156 
14157   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14158                                                SrcExpr.get(), Type,
14159                                                E->getRParenLoc());
14160 }
14161 
14162 template<typename Derived>
14163 ExprResult
14164 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14165   BlockDecl *oldBlock = E->getBlockDecl();
14166 
14167   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14168   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14169 
14170   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14171   blockScope->TheDecl->setBlockMissingReturnType(
14172                          oldBlock->blockMissingReturnType());
14173 
14174   SmallVector<ParmVarDecl*, 4> params;
14175   SmallVector<QualType, 4> paramTypes;
14176 
14177   const FunctionProtoType *exprFunctionType = E->getFunctionType();
14178 
14179   // Parameter substitution.
14180   Sema::ExtParameterInfoBuilder extParamInfos;
14181   if (getDerived().TransformFunctionTypeParams(
14182           E->getCaretLocation(), oldBlock->parameters(), nullptr,
14183           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14184           extParamInfos)) {
14185     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14186     return ExprError();
14187   }
14188 
14189   QualType exprResultType =
14190       getDerived().TransformType(exprFunctionType->getReturnType());
14191 
14192   auto epi = exprFunctionType->getExtProtoInfo();
14193   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14194 
14195   QualType functionType =
14196     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14197   blockScope->FunctionType = functionType;
14198 
14199   // Set the parameters on the block decl.
14200   if (!params.empty())
14201     blockScope->TheDecl->setParams(params);
14202 
14203   if (!oldBlock->blockMissingReturnType()) {
14204     blockScope->HasImplicitReturnType = false;
14205     blockScope->ReturnType = exprResultType;
14206   }
14207 
14208   // Transform the body
14209   StmtResult body = getDerived().TransformStmt(E->getBody());
14210   if (body.isInvalid()) {
14211     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14212     return ExprError();
14213   }
14214 
14215 #ifndef NDEBUG
14216   // In builds with assertions, make sure that we captured everything we
14217   // captured before.
14218   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14219     for (const auto &I : oldBlock->captures()) {
14220       VarDecl *oldCapture = I.getVariable();
14221 
14222       // Ignore parameter packs.
14223       if (oldCapture->isParameterPack())
14224         continue;
14225 
14226       VarDecl *newCapture =
14227         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14228                                                  oldCapture));
14229       assert(blockScope->CaptureMap.count(newCapture));
14230     }
14231     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
14232   }
14233 #endif
14234 
14235   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14236                                     /*Scope=*/nullptr);
14237 }
14238 
14239 template<typename Derived>
14240 ExprResult
14241 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14242   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14243   if (SrcExpr.isInvalid())
14244     return ExprError();
14245 
14246   QualType Type = getDerived().TransformType(E->getType());
14247 
14248   return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14249                                  E->getRParenLoc());
14250 }
14251 
14252 template<typename Derived>
14253 ExprResult
14254 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14255   bool ArgumentChanged = false;
14256   SmallVector<Expr*, 8> SubExprs;
14257   SubExprs.reserve(E->getNumSubExprs());
14258   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14259                                   SubExprs, &ArgumentChanged))
14260     return ExprError();
14261 
14262   if (!getDerived().AlwaysRebuild() &&
14263       !ArgumentChanged)
14264     return E;
14265 
14266   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14267                                         E->getOp(), E->getRParenLoc());
14268 }
14269 
14270 //===----------------------------------------------------------------------===//
14271 // Type reconstruction
14272 //===----------------------------------------------------------------------===//
14273 
14274 template<typename Derived>
14275 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14276                                                     SourceLocation Star) {
14277   return SemaRef.BuildPointerType(PointeeType, Star,
14278                                   getDerived().getBaseEntity());
14279 }
14280 
14281 template<typename Derived>
14282 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14283                                                          SourceLocation Star) {
14284   return SemaRef.BuildBlockPointerType(PointeeType, Star,
14285                                        getDerived().getBaseEntity());
14286 }
14287 
14288 template<typename Derived>
14289 QualType
14290 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14291                                              bool WrittenAsLValue,
14292                                              SourceLocation Sigil) {
14293   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14294                                     Sigil, getDerived().getBaseEntity());
14295 }
14296 
14297 template<typename Derived>
14298 QualType
14299 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14300                                                  QualType ClassType,
14301                                                  SourceLocation Sigil) {
14302   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14303                                         getDerived().getBaseEntity());
14304 }
14305 
14306 template<typename Derived>
14307 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14308            const ObjCTypeParamDecl *Decl,
14309            SourceLocation ProtocolLAngleLoc,
14310            ArrayRef<ObjCProtocolDecl *> Protocols,
14311            ArrayRef<SourceLocation> ProtocolLocs,
14312            SourceLocation ProtocolRAngleLoc) {
14313   return SemaRef.BuildObjCTypeParamType(Decl,
14314                                         ProtocolLAngleLoc, Protocols,
14315                                         ProtocolLocs, ProtocolRAngleLoc,
14316                                         /*FailOnError=*/true);
14317 }
14318 
14319 template<typename Derived>
14320 QualType TreeTransform<Derived>::RebuildObjCObjectType(
14321            QualType BaseType,
14322            SourceLocation Loc,
14323            SourceLocation TypeArgsLAngleLoc,
14324            ArrayRef<TypeSourceInfo *> TypeArgs,
14325            SourceLocation TypeArgsRAngleLoc,
14326            SourceLocation ProtocolLAngleLoc,
14327            ArrayRef<ObjCProtocolDecl *> Protocols,
14328            ArrayRef<SourceLocation> ProtocolLocs,
14329            SourceLocation ProtocolRAngleLoc) {
14330   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
14331                                      TypeArgs, TypeArgsRAngleLoc,
14332                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
14333                                      ProtocolRAngleLoc,
14334                                      /*FailOnError=*/true);
14335 }
14336 
14337 template<typename Derived>
14338 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14339            QualType PointeeType,
14340            SourceLocation Star) {
14341   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14342 }
14343 
14344 template<typename Derived>
14345 QualType
14346 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14347                                          ArrayType::ArraySizeModifier SizeMod,
14348                                          const llvm::APInt *Size,
14349                                          Expr *SizeExpr,
14350                                          unsigned IndexTypeQuals,
14351                                          SourceRange BracketsRange) {
14352   if (SizeExpr || !Size)
14353     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14354                                   IndexTypeQuals, BracketsRange,
14355                                   getDerived().getBaseEntity());
14356 
14357   QualType Types[] = {
14358     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14359     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14360     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14361   };
14362   const unsigned NumTypes = llvm::array_lengthof(Types);
14363   QualType SizeType;
14364   for (unsigned I = 0; I != NumTypes; ++I)
14365     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
14366       SizeType = Types[I];
14367       break;
14368     }
14369 
14370   // Note that we can return a VariableArrayType here in the case where
14371   // the element type was a dependent VariableArrayType.
14372   IntegerLiteral *ArraySize
14373       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14374                                /*FIXME*/BracketsRange.getBegin());
14375   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14376                                 IndexTypeQuals, BracketsRange,
14377                                 getDerived().getBaseEntity());
14378 }
14379 
14380 template<typename Derived>
14381 QualType
14382 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14383                                                  ArrayType::ArraySizeModifier SizeMod,
14384                                                  const llvm::APInt &Size,
14385                                                  Expr *SizeExpr,
14386                                                  unsigned IndexTypeQuals,
14387                                                  SourceRange BracketsRange) {
14388   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14389                                         IndexTypeQuals, BracketsRange);
14390 }
14391 
14392 template<typename Derived>
14393 QualType
14394 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14395                                           ArrayType::ArraySizeModifier SizeMod,
14396                                                  unsigned IndexTypeQuals,
14397                                                    SourceRange BracketsRange) {
14398   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14399                                        IndexTypeQuals, BracketsRange);
14400 }
14401 
14402 template<typename Derived>
14403 QualType
14404 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14405                                           ArrayType::ArraySizeModifier SizeMod,
14406                                                  Expr *SizeExpr,
14407                                                  unsigned IndexTypeQuals,
14408                                                  SourceRange BracketsRange) {
14409   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14410                                        SizeExpr,
14411                                        IndexTypeQuals, BracketsRange);
14412 }
14413 
14414 template<typename Derived>
14415 QualType
14416 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14417                                           ArrayType::ArraySizeModifier SizeMod,
14418                                                        Expr *SizeExpr,
14419                                                        unsigned IndexTypeQuals,
14420                                                    SourceRange BracketsRange) {
14421   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14422                                        SizeExpr,
14423                                        IndexTypeQuals, BracketsRange);
14424 }
14425 
14426 template <typename Derived>
14427 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14428     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14429   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14430                                           AttributeLoc);
14431 }
14432 
14433 template <typename Derived>
14434 QualType
14435 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14436                                           unsigned NumElements,
14437                                           VectorType::VectorKind VecKind) {
14438   // FIXME: semantic checking!
14439   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14440 }
14441 
14442 template <typename Derived>
14443 QualType TreeTransform<Derived>::RebuildDependentVectorType(
14444     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14445     VectorType::VectorKind VecKind) {
14446   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14447 }
14448 
14449 template<typename Derived>
14450 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14451                                                       unsigned NumElements,
14452                                                  SourceLocation AttributeLoc) {
14453   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14454                           NumElements, true);
14455   IntegerLiteral *VectorSize
14456     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14457                              AttributeLoc);
14458   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14459 }
14460 
14461 template<typename Derived>
14462 QualType
14463 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14464                                                            Expr *SizeExpr,
14465                                                   SourceLocation AttributeLoc) {
14466   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14467 }
14468 
14469 template <typename Derived>
14470 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14471     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14472   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14473                                                NumColumns);
14474 }
14475 
14476 template <typename Derived>
14477 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14478     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14479     SourceLocation AttributeLoc) {
14480   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14481                                  AttributeLoc);
14482 }
14483 
14484 template<typename Derived>
14485 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14486     QualType T,
14487     MutableArrayRef<QualType> ParamTypes,
14488     const FunctionProtoType::ExtProtoInfo &EPI) {
14489   return SemaRef.BuildFunctionType(T, ParamTypes,
14490                                    getDerived().getBaseLocation(),
14491                                    getDerived().getBaseEntity(),
14492                                    EPI);
14493 }
14494 
14495 template<typename Derived>
14496 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14497   return SemaRef.Context.getFunctionNoProtoType(T);
14498 }
14499 
14500 template<typename Derived>
14501 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14502                                                             Decl *D) {
14503   assert(D && "no decl found");
14504   if (D->isInvalidDecl()) return QualType();
14505 
14506   // FIXME: Doesn't account for ObjCInterfaceDecl!
14507   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14508     // A valid resolved using typename pack expansion decl can have multiple
14509     // UsingDecls, but they must each have exactly one type, and it must be
14510     // the same type in every case. But we must have at least one expansion!
14511     if (UPD->expansions().empty()) {
14512       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14513           << UPD->isCXXClassMember() << UPD;
14514       return QualType();
14515     }
14516 
14517     // We might still have some unresolved types. Try to pick a resolved type
14518     // if we can. The final instantiation will check that the remaining
14519     // unresolved types instantiate to the type we pick.
14520     QualType FallbackT;
14521     QualType T;
14522     for (auto *E : UPD->expansions()) {
14523       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14524       if (ThisT.isNull())
14525         continue;
14526       else if (ThisT->getAs<UnresolvedUsingType>())
14527         FallbackT = ThisT;
14528       else if (T.isNull())
14529         T = ThisT;
14530       else
14531         assert(getSema().Context.hasSameType(ThisT, T) &&
14532                "mismatched resolved types in using pack expansion");
14533     }
14534     return T.isNull() ? FallbackT : T;
14535   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14536     assert(Using->hasTypename() &&
14537            "UnresolvedUsingTypenameDecl transformed to non-typename using");
14538 
14539     // A valid resolved using typename decl points to exactly one type decl.
14540     assert(++Using->shadow_begin() == Using->shadow_end());
14541 
14542     UsingShadowDecl *Shadow = *Using->shadow_begin();
14543     if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
14544       return QualType();
14545     return SemaRef.Context.getUsingType(
14546         Shadow, SemaRef.Context.getTypeDeclType(
14547                     cast<TypeDecl>(Shadow->getTargetDecl())));
14548   } else {
14549     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
14550            "UnresolvedUsingTypenameDecl transformed to non-using decl");
14551     return SemaRef.Context.getTypeDeclType(
14552         cast<UnresolvedUsingTypenameDecl>(D));
14553   }
14554 }
14555 
14556 template <typename Derived>
14557 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
14558                                                        SourceLocation) {
14559   return SemaRef.BuildTypeofExprType(E);
14560 }
14561 
14562 template<typename Derived>
14563 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
14564   return SemaRef.Context.getTypeOfType(Underlying);
14565 }
14566 
14567 template <typename Derived>
14568 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
14569   return SemaRef.BuildDecltypeType(E);
14570 }
14571 
14572 template<typename Derived>
14573 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
14574                                             UnaryTransformType::UTTKind UKind,
14575                                             SourceLocation Loc) {
14576   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
14577 }
14578 
14579 template<typename Derived>
14580 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
14581                                                       TemplateName Template,
14582                                              SourceLocation TemplateNameLoc,
14583                                      TemplateArgumentListInfo &TemplateArgs) {
14584   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
14585 }
14586 
14587 template<typename Derived>
14588 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
14589                                                    SourceLocation KWLoc) {
14590   return SemaRef.BuildAtomicType(ValueType, KWLoc);
14591 }
14592 
14593 template<typename Derived>
14594 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
14595                                                  SourceLocation KWLoc,
14596                                                  bool isReadPipe) {
14597   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
14598                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
14599 }
14600 
14601 template <typename Derived>
14602 QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
14603                                                    unsigned NumBits,
14604                                                    SourceLocation Loc) {
14605   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14606                         NumBits, true);
14607   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
14608                                                 SemaRef.Context.IntTy, Loc);
14609   return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
14610 }
14611 
14612 template <typename Derived>
14613 QualType TreeTransform<Derived>::RebuildDependentBitIntType(
14614     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
14615   return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
14616 }
14617 
14618 template<typename Derived>
14619 TemplateName
14620 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14621                                             bool TemplateKW,
14622                                             TemplateDecl *Template) {
14623   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
14624                                                   Template);
14625 }
14626 
14627 template<typename Derived>
14628 TemplateName
14629 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14630                                             SourceLocation TemplateKWLoc,
14631                                             const IdentifierInfo &Name,
14632                                             SourceLocation NameLoc,
14633                                             QualType ObjectType,
14634                                             NamedDecl *FirstQualifierInScope,
14635                                             bool AllowInjectedClassName) {
14636   UnqualifiedId TemplateName;
14637   TemplateName.setIdentifier(&Name, NameLoc);
14638   Sema::TemplateTy Template;
14639   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
14640                               TemplateName, ParsedType::make(ObjectType),
14641                               /*EnteringContext=*/false, Template,
14642                               AllowInjectedClassName);
14643   return Template.get();
14644 }
14645 
14646 template<typename Derived>
14647 TemplateName
14648 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14649                                             SourceLocation TemplateKWLoc,
14650                                             OverloadedOperatorKind Operator,
14651                                             SourceLocation NameLoc,
14652                                             QualType ObjectType,
14653                                             bool AllowInjectedClassName) {
14654   UnqualifiedId Name;
14655   // FIXME: Bogus location information.
14656   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
14657   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
14658   Sema::TemplateTy Template;
14659   getSema().ActOnTemplateName(
14660       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
14661       /*EnteringContext=*/false, Template, AllowInjectedClassName);
14662   return Template.get();
14663 }
14664 
14665 template<typename Derived>
14666 ExprResult
14667 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
14668                                                    SourceLocation OpLoc,
14669                                                    Expr *OrigCallee,
14670                                                    Expr *First,
14671                                                    Expr *Second) {
14672   Expr *Callee = OrigCallee->IgnoreParenCasts();
14673   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
14674 
14675   if (First->getObjectKind() == OK_ObjCProperty) {
14676     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14677     if (BinaryOperator::isAssignmentOp(Opc))
14678       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
14679                                                  First, Second);
14680     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
14681     if (Result.isInvalid())
14682       return ExprError();
14683     First = Result.get();
14684   }
14685 
14686   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
14687     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
14688     if (Result.isInvalid())
14689       return ExprError();
14690     Second = Result.get();
14691   }
14692 
14693   // Determine whether this should be a builtin operation.
14694   if (Op == OO_Subscript) {
14695     if (!First->getType()->isOverloadableType() &&
14696         !Second->getType()->isOverloadableType())
14697       return getSema().CreateBuiltinArraySubscriptExpr(
14698           First, Callee->getBeginLoc(), Second, OpLoc);
14699   } else if (Op == OO_Arrow) {
14700     // -> is never a builtin operation.
14701     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
14702   } else if (Second == nullptr || isPostIncDec) {
14703     if (!First->getType()->isOverloadableType() ||
14704         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
14705       // The argument is not of overloadable type, or this is an expression
14706       // of the form &Class::member, so try to create a built-in unary
14707       // operation.
14708       UnaryOperatorKind Opc
14709         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14710 
14711       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
14712     }
14713   } else {
14714     if (!First->getType()->isOverloadableType() &&
14715         !Second->getType()->isOverloadableType()) {
14716       // Neither of the arguments is an overloadable type, so try to
14717       // create a built-in binary operation.
14718       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14719       ExprResult Result
14720         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
14721       if (Result.isInvalid())
14722         return ExprError();
14723 
14724       return Result;
14725     }
14726   }
14727 
14728   // Compute the transformed set of functions (and function templates) to be
14729   // used during overload resolution.
14730   UnresolvedSet<16> Functions;
14731   bool RequiresADL;
14732 
14733   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
14734     Functions.append(ULE->decls_begin(), ULE->decls_end());
14735     // If the overload could not be resolved in the template definition
14736     // (because we had a dependent argument), ADL is performed as part of
14737     // template instantiation.
14738     RequiresADL = ULE->requiresADL();
14739   } else {
14740     // If we've resolved this to a particular non-member function, just call
14741     // that function. If we resolved it to a member function,
14742     // CreateOverloaded* will find that function for us.
14743     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
14744     if (!isa<CXXMethodDecl>(ND))
14745       Functions.addDecl(ND);
14746     RequiresADL = false;
14747   }
14748 
14749   // Add any functions found via argument-dependent lookup.
14750   Expr *Args[2] = { First, Second };
14751   unsigned NumArgs = 1 + (Second != nullptr);
14752 
14753   // Create the overloaded operator invocation for unary operators.
14754   if (NumArgs == 1 || isPostIncDec) {
14755     UnaryOperatorKind Opc
14756       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14757     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
14758                                            RequiresADL);
14759   }
14760 
14761   if (Op == OO_Subscript) {
14762     SourceLocation LBrace;
14763     SourceLocation RBrace;
14764 
14765     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
14766       DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
14767       LBrace = NameLoc.getCXXOperatorNameBeginLoc();
14768       RBrace = NameLoc.getCXXOperatorNameEndLoc();
14769     } else {
14770       LBrace = Callee->getBeginLoc();
14771       RBrace = OpLoc;
14772     }
14773 
14774     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
14775                                                       First, Second);
14776   }
14777 
14778   // Create the overloaded operator invocation for binary operators.
14779   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14780   ExprResult Result = SemaRef.CreateOverloadedBinOp(
14781       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
14782   if (Result.isInvalid())
14783     return ExprError();
14784 
14785   return Result;
14786 }
14787 
14788 template<typename Derived>
14789 ExprResult
14790 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
14791                                                      SourceLocation OperatorLoc,
14792                                                        bool isArrow,
14793                                                        CXXScopeSpec &SS,
14794                                                      TypeSourceInfo *ScopeType,
14795                                                        SourceLocation CCLoc,
14796                                                        SourceLocation TildeLoc,
14797                                         PseudoDestructorTypeStorage Destroyed) {
14798   QualType BaseType = Base->getType();
14799   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
14800       (!isArrow && !BaseType->getAs<RecordType>()) ||
14801       (isArrow && BaseType->getAs<PointerType>() &&
14802        !BaseType->castAs<PointerType>()->getPointeeType()
14803                                               ->template getAs<RecordType>())){
14804     // This pseudo-destructor expression is still a pseudo-destructor.
14805     return SemaRef.BuildPseudoDestructorExpr(
14806         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
14807         CCLoc, TildeLoc, Destroyed);
14808   }
14809 
14810   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
14811   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
14812                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
14813   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
14814   NameInfo.setNamedTypeInfo(DestroyedType);
14815 
14816   // The scope type is now known to be a valid nested name specifier
14817   // component. Tack it on to the end of the nested name specifier.
14818   if (ScopeType) {
14819     if (!ScopeType->getType()->getAs<TagType>()) {
14820       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
14821                      diag::err_expected_class_or_namespace)
14822           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
14823       return ExprError();
14824     }
14825     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
14826               CCLoc);
14827   }
14828 
14829   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
14830   return getSema().BuildMemberReferenceExpr(Base, BaseType,
14831                                             OperatorLoc, isArrow,
14832                                             SS, TemplateKWLoc,
14833                                             /*FIXME: FirstQualifier*/ nullptr,
14834                                             NameInfo,
14835                                             /*TemplateArgs*/ nullptr,
14836                                             /*S*/nullptr);
14837 }
14838 
14839 template<typename Derived>
14840 StmtResult
14841 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
14842   SourceLocation Loc = S->getBeginLoc();
14843   CapturedDecl *CD = S->getCapturedDecl();
14844   unsigned NumParams = CD->getNumParams();
14845   unsigned ContextParamPos = CD->getContextParamPosition();
14846   SmallVector<Sema::CapturedParamNameType, 4> Params;
14847   for (unsigned I = 0; I < NumParams; ++I) {
14848     if (I != ContextParamPos) {
14849       Params.push_back(
14850              std::make_pair(
14851                   CD->getParam(I)->getName(),
14852                   getDerived().TransformType(CD->getParam(I)->getType())));
14853     } else {
14854       Params.push_back(std::make_pair(StringRef(), QualType()));
14855     }
14856   }
14857   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
14858                                      S->getCapturedRegionKind(), Params);
14859   StmtResult Body;
14860   {
14861     Sema::CompoundScopeRAII CompoundScope(getSema());
14862     Body = getDerived().TransformStmt(S->getCapturedStmt());
14863   }
14864 
14865   if (Body.isInvalid()) {
14866     getSema().ActOnCapturedRegionError();
14867     return StmtError();
14868   }
14869 
14870   return getSema().ActOnCapturedRegionEnd(Body.get());
14871 }
14872 
14873 } // end namespace clang
14874 
14875 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14876