xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 3c134670993bf525fcd6c4dfef84a3dfc3d4ed1b)
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/OpenMPKinds.h"
32 #include "clang/Sema/Designator.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/Ownership.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaDiagnostic.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include <algorithm>
42 
43 using namespace llvm::omp;
44 
45 namespace clang {
46 using namespace sema;
47 
48 /// A semantic tree transformation that allows one to transform one
49 /// abstract syntax tree into another.
50 ///
51 /// A new tree transformation is defined by creating a new subclass \c X of
52 /// \c TreeTransform<X> and then overriding certain operations to provide
53 /// behavior specific to that transformation. For example, template
54 /// instantiation is implemented as a tree transformation where the
55 /// transformation of TemplateTypeParmType nodes involves substituting the
56 /// template arguments for their corresponding template parameters; a similar
57 /// transformation is performed for non-type template parameters and
58 /// template template parameters.
59 ///
60 /// This tree-transformation template uses static polymorphism to allow
61 /// subclasses to customize any of its operations. Thus, a subclass can
62 /// override any of the transformation or rebuild operators by providing an
63 /// operation with the same signature as the default implementation. The
64 /// overriding function should not be virtual.
65 ///
66 /// Semantic tree transformations are split into two stages, either of which
67 /// can be replaced by a subclass. The "transform" step transforms an AST node
68 /// or the parts of an AST node using the various transformation functions,
69 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
70 /// node of the appropriate kind from the pieces. The default transformation
71 /// routines recursively transform the operands to composite AST nodes (e.g.,
72 /// the pointee type of a PointerType node) and, if any of those operand nodes
73 /// were changed by the transformation, invokes the rebuild operation to create
74 /// a new AST node.
75 ///
76 /// Subclasses can customize the transformation at various levels. The
77 /// most coarse-grained transformations involve replacing TransformType(),
78 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
79 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
80 /// new implementations.
81 ///
82 /// For more fine-grained transformations, subclasses can replace any of the
83 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
84 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
85 /// replacing TransformTemplateTypeParmType() allows template instantiation
86 /// to substitute template arguments for their corresponding template
87 /// parameters. Additionally, subclasses can override the \c RebuildXXX
88 /// functions to control how AST nodes are rebuilt when their operands change.
89 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
90 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
91 /// be able to use more efficient rebuild steps.
92 ///
93 /// There are a handful of other functions that can be overridden, allowing one
94 /// to avoid traversing nodes that don't need any transformation
95 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
96 /// operands have not changed (\c AlwaysRebuild()), and customize the
97 /// default locations and entity names used for type-checking
98 /// (\c getBaseLocation(), \c getBaseEntity()).
99 template<typename Derived>
100 class TreeTransform {
101   /// Private RAII object that helps us forget and then re-remember
102   /// the template argument corresponding to a partially-substituted parameter
103   /// pack.
104   class ForgetPartiallySubstitutedPackRAII {
105     Derived &Self;
106     TemplateArgument Old;
107 
108   public:
109     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
110       Old = Self.ForgetPartiallySubstitutedPack();
111     }
112 
113     ~ForgetPartiallySubstitutedPackRAII() {
114       Self.RememberPartiallySubstitutedPack(Old);
115     }
116   };
117 
118 protected:
119   Sema &SemaRef;
120 
121   /// The set of local declarations that have been transformed, for
122   /// cases where we are forced to build new declarations within the transformer
123   /// rather than in the subclass (e.g., lambda closure types).
124   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
125 
126 public:
127   /// Initializes a new tree transformer.
128   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
129 
130   /// Retrieves a reference to the derived class.
131   Derived &getDerived() { return static_cast<Derived&>(*this); }
132 
133   /// Retrieves a reference to the derived class.
134   const Derived &getDerived() const {
135     return static_cast<const Derived&>(*this);
136   }
137 
138   static inline ExprResult Owned(Expr *E) { return E; }
139   static inline StmtResult Owned(Stmt *S) { return S; }
140 
141   /// Retrieves a reference to the semantic analysis object used for
142   /// this tree transform.
143   Sema &getSema() const { return SemaRef; }
144 
145   /// Whether the transformation should always rebuild AST nodes, even
146   /// if none of the children have changed.
147   ///
148   /// Subclasses may override this function to specify when the transformation
149   /// should rebuild all AST nodes.
150   ///
151   /// We must always rebuild all AST nodes when performing variadic template
152   /// pack expansion, in order to avoid violating the AST invariant that each
153   /// statement node appears at most once in its containing declaration.
154   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
155 
156   /// Whether the transformation is forming an expression or statement that
157   /// replaces the original. In this case, we'll reuse mangling numbers from
158   /// existing lambdas.
159   bool ReplacingOriginal() { return false; }
160 
161   /// Wether CXXConstructExpr can be skipped when they are implicit.
162   /// They will be reconstructed when used if needed.
163   /// This is usefull when the user that cause rebuilding of the
164   /// CXXConstructExpr is outside of the expression at which the TreeTransform
165   /// started.
166   bool AllowSkippingCXXConstructExpr() { return true; }
167 
168   /// Returns the location of the entity being transformed, if that
169   /// information was not available elsewhere in the AST.
170   ///
171   /// By default, returns no source-location information. Subclasses can
172   /// provide an alternative implementation that provides better location
173   /// information.
174   SourceLocation getBaseLocation() { return SourceLocation(); }
175 
176   /// Returns the name of the entity being transformed, if that
177   /// information was not available elsewhere in the AST.
178   ///
179   /// By default, returns an empty name. Subclasses can provide an alternative
180   /// implementation with a more precise name.
181   DeclarationName getBaseEntity() { return DeclarationName(); }
182 
183   /// Sets the "base" location and entity when that
184   /// information is known based on another transformation.
185   ///
186   /// By default, the source location and entity are ignored. Subclasses can
187   /// override this function to provide a customized implementation.
188   void setBase(SourceLocation Loc, DeclarationName Entity) { }
189 
190   /// RAII object that temporarily sets the base location and entity
191   /// used for reporting diagnostics in types.
192   class TemporaryBase {
193     TreeTransform &Self;
194     SourceLocation OldLocation;
195     DeclarationName OldEntity;
196 
197   public:
198     TemporaryBase(TreeTransform &Self, SourceLocation Location,
199                   DeclarationName Entity) : Self(Self) {
200       OldLocation = Self.getDerived().getBaseLocation();
201       OldEntity = Self.getDerived().getBaseEntity();
202 
203       if (Location.isValid())
204         Self.getDerived().setBase(Location, Entity);
205     }
206 
207     ~TemporaryBase() {
208       Self.getDerived().setBase(OldLocation, OldEntity);
209     }
210   };
211 
212   /// Determine whether the given type \p T has already been
213   /// transformed.
214   ///
215   /// Subclasses can provide an alternative implementation of this routine
216   /// to short-circuit evaluation when it is known that a given type will
217   /// not change. For example, template instantiation need not traverse
218   /// non-dependent types.
219   bool AlreadyTransformed(QualType T) {
220     return T.isNull();
221   }
222 
223   /// Transform a template parameter depth level.
224   ///
225   /// During a transformation that transforms template parameters, this maps
226   /// an old template parameter depth to a new depth.
227   unsigned TransformTemplateDepth(unsigned Depth) {
228     return Depth;
229   }
230 
231   /// Determine whether the given call argument should be dropped, e.g.,
232   /// because it is a default argument.
233   ///
234   /// Subclasses can provide an alternative implementation of this routine to
235   /// determine which kinds of call arguments get dropped. By default,
236   /// CXXDefaultArgument nodes are dropped (prior to transformation).
237   bool DropCallArgument(Expr *E) {
238     return E->isDefaultArgument();
239   }
240 
241   /// Determine whether we should expand a pack expansion with the
242   /// given set of parameter packs into separate arguments by repeatedly
243   /// transforming the pattern.
244   ///
245   /// By default, the transformer never tries to expand pack expansions.
246   /// Subclasses can override this routine to provide different behavior.
247   ///
248   /// \param EllipsisLoc The location of the ellipsis that identifies the
249   /// pack expansion.
250   ///
251   /// \param PatternRange The source range that covers the entire pattern of
252   /// the pack expansion.
253   ///
254   /// \param Unexpanded The set of unexpanded parameter packs within the
255   /// pattern.
256   ///
257   /// \param ShouldExpand Will be set to \c true if the transformer should
258   /// expand the corresponding pack expansions into separate arguments. When
259   /// set, \c NumExpansions must also be set.
260   ///
261   /// \param RetainExpansion Whether the caller should add an unexpanded
262   /// pack expansion after all of the expanded arguments. This is used
263   /// when extending explicitly-specified template argument packs per
264   /// C++0x [temp.arg.explicit]p9.
265   ///
266   /// \param NumExpansions The number of separate arguments that will be in
267   /// the expanded form of the corresponding pack expansion. This is both an
268   /// input and an output parameter, which can be set by the caller if the
269   /// number of expansions is known a priori (e.g., due to a prior substitution)
270   /// and will be set by the callee when the number of expansions is known.
271   /// The callee must set this value when \c ShouldExpand is \c true; it may
272   /// set this value in other cases.
273   ///
274   /// \returns true if an error occurred (e.g., because the parameter packs
275   /// are to be instantiated with arguments of different lengths), false
276   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
277   /// must be set.
278   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
279                                SourceRange PatternRange,
280                                ArrayRef<UnexpandedParameterPack> Unexpanded,
281                                bool &ShouldExpand,
282                                bool &RetainExpansion,
283                                Optional<unsigned> &NumExpansions) {
284     ShouldExpand = false;
285     return false;
286   }
287 
288   /// "Forget" about the partially-substituted pack template argument,
289   /// when performing an instantiation that must preserve the parameter pack
290   /// use.
291   ///
292   /// This routine is meant to be overridden by the template instantiator.
293   TemplateArgument ForgetPartiallySubstitutedPack() {
294     return TemplateArgument();
295   }
296 
297   /// "Remember" the partially-substituted pack template argument
298   /// after performing an instantiation that must preserve the parameter pack
299   /// use.
300   ///
301   /// This routine is meant to be overridden by the template instantiator.
302   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
303 
304   /// Note to the derived class when a function parameter pack is
305   /// being expanded.
306   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
307 
308   /// Transforms the given type into another type.
309   ///
310   /// By default, this routine transforms a type by creating a
311   /// TypeSourceInfo for it and delegating to the appropriate
312   /// function.  This is expensive, but we don't mind, because
313   /// this method is deprecated anyway;  all users should be
314   /// switched to storing TypeSourceInfos.
315   ///
316   /// \returns the transformed type.
317   QualType TransformType(QualType T);
318 
319   /// Transforms the given type-with-location into a new
320   /// type-with-location.
321   ///
322   /// By default, this routine transforms a type by delegating to the
323   /// appropriate TransformXXXType to build a new type.  Subclasses
324   /// may override this function (to take over all type
325   /// transformations) or some set of the TransformXXXType functions
326   /// to alter the transformation.
327   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
328 
329   /// Transform the given type-with-location into a new
330   /// type, collecting location information in the given builder
331   /// as necessary.
332   ///
333   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
334 
335   /// Transform a type that is permitted to produce a
336   /// DeducedTemplateSpecializationType.
337   ///
338   /// This is used in the (relatively rare) contexts where it is acceptable
339   /// for transformation to produce a class template type with deduced
340   /// template arguments.
341   /// @{
342   QualType TransformTypeWithDeducedTST(QualType T);
343   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
344   /// @}
345 
346   /// The reason why the value of a statement is not discarded, if any.
347   enum StmtDiscardKind {
348     SDK_Discarded,
349     SDK_NotDiscarded,
350     SDK_StmtExprResult,
351   };
352 
353   /// Transform the given statement.
354   ///
355   /// By default, this routine transforms a statement by delegating to the
356   /// appropriate TransformXXXStmt function to transform a specific kind of
357   /// statement or the TransformExpr() function to transform an expression.
358   /// Subclasses may override this function to transform statements using some
359   /// other mechanism.
360   ///
361   /// \returns the transformed statement.
362   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
363 
364   /// Transform the given statement.
365   ///
366   /// By default, this routine transforms a statement by delegating to the
367   /// appropriate TransformOMPXXXClause function to transform a specific kind
368   /// of clause. Subclasses may override this function to transform statements
369   /// using some other mechanism.
370   ///
371   /// \returns the transformed OpenMP clause.
372   OMPClause *TransformOMPClause(OMPClause *S);
373 
374   /// Transform the given attribute.
375   ///
376   /// By default, this routine transforms a statement by delegating to the
377   /// appropriate TransformXXXAttr function to transform a specific kind
378   /// of attribute. Subclasses may override this function to transform
379   /// attributed statements using some other mechanism.
380   ///
381   /// \returns the transformed attribute
382   const Attr *TransformAttr(const Attr *S);
383 
384 /// Transform the specified attribute.
385 ///
386 /// Subclasses should override the transformation of attributes with a pragma
387 /// spelling to transform expressions stored within the attribute.
388 ///
389 /// \returns the transformed attribute.
390 #define ATTR(X)
391 #define PRAGMA_SPELLING_ATTR(X)                                                \
392   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
393 #include "clang/Basic/AttrList.inc"
394 
395   /// Transform the given expression.
396   ///
397   /// By default, this routine transforms an expression by delegating to the
398   /// appropriate TransformXXXExpr function to build a new expression.
399   /// Subclasses may override this function to transform expressions using some
400   /// other mechanism.
401   ///
402   /// \returns the transformed expression.
403   ExprResult TransformExpr(Expr *E);
404 
405   /// Transform the given initializer.
406   ///
407   /// By default, this routine transforms an initializer by stripping off the
408   /// semantic nodes added by initialization, then passing the result to
409   /// TransformExpr or TransformExprs.
410   ///
411   /// \returns the transformed initializer.
412   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
413 
414   /// Transform the given list of expressions.
415   ///
416   /// This routine transforms a list of expressions by invoking
417   /// \c TransformExpr() for each subexpression. However, it also provides
418   /// support for variadic templates by expanding any pack expansions (if the
419   /// derived class permits such expansion) along the way. When pack expansions
420   /// are present, the number of outputs may not equal the number of inputs.
421   ///
422   /// \param Inputs The set of expressions to be transformed.
423   ///
424   /// \param NumInputs The number of expressions in \c Inputs.
425   ///
426   /// \param IsCall If \c true, then this transform is being performed on
427   /// function-call arguments, and any arguments that should be dropped, will
428   /// be.
429   ///
430   /// \param Outputs The transformed input expressions will be added to this
431   /// vector.
432   ///
433   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
434   /// due to transformation.
435   ///
436   /// \returns true if an error occurred, false otherwise.
437   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
438                       SmallVectorImpl<Expr *> &Outputs,
439                       bool *ArgChanged = nullptr);
440 
441   /// Transform the given declaration, which is referenced from a type
442   /// or expression.
443   ///
444   /// By default, acts as the identity function on declarations, unless the
445   /// transformer has had to transform the declaration itself. Subclasses
446   /// may override this function to provide alternate behavior.
447   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
448     llvm::DenseMap<Decl *, Decl *>::iterator Known
449       = TransformedLocalDecls.find(D);
450     if (Known != TransformedLocalDecls.end())
451       return Known->second;
452 
453     return D;
454   }
455 
456   /// Transform the specified condition.
457   ///
458   /// By default, this transforms the variable and expression and rebuilds
459   /// the condition.
460   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
461                                            Expr *Expr,
462                                            Sema::ConditionKind Kind);
463 
464   /// Transform the attributes associated with the given declaration and
465   /// place them on the new declaration.
466   ///
467   /// By default, this operation does nothing. Subclasses may override this
468   /// behavior to transform attributes.
469   void transformAttrs(Decl *Old, Decl *New) { }
470 
471   /// Note that a local declaration has been transformed by this
472   /// transformer.
473   ///
474   /// Local declarations are typically transformed via a call to
475   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
476   /// the transformer itself has to transform the declarations. This routine
477   /// can be overridden by a subclass that keeps track of such mappings.
478   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
479     assert(New.size() == 1 &&
480            "must override transformedLocalDecl if performing pack expansion");
481     TransformedLocalDecls[Old] = New.front();
482   }
483 
484   /// Transform the definition of the given declaration.
485   ///
486   /// By default, invokes TransformDecl() to transform the declaration.
487   /// Subclasses may override this function to provide alternate behavior.
488   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
489     return getDerived().TransformDecl(Loc, D);
490   }
491 
492   /// Transform the given declaration, which was the first part of a
493   /// nested-name-specifier in a member access expression.
494   ///
495   /// This specific declaration transformation only applies to the first
496   /// identifier in a nested-name-specifier of a member access expression, e.g.,
497   /// the \c T in \c x->T::member
498   ///
499   /// By default, invokes TransformDecl() to transform the declaration.
500   /// Subclasses may override this function to provide alternate behavior.
501   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
502     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
503   }
504 
505   /// Transform the set of declarations in an OverloadExpr.
506   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
507                                   LookupResult &R);
508 
509   /// Transform the given nested-name-specifier with source-location
510   /// information.
511   ///
512   /// By default, transforms all of the types and declarations within the
513   /// nested-name-specifier. Subclasses may override this function to provide
514   /// alternate behavior.
515   NestedNameSpecifierLoc
516   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
517                                   QualType ObjectType = QualType(),
518                                   NamedDecl *FirstQualifierInScope = nullptr);
519 
520   /// Transform the given declaration name.
521   ///
522   /// By default, transforms the types of conversion function, constructor,
523   /// and destructor names and then (if needed) rebuilds the declaration name.
524   /// Identifiers and selectors are returned unmodified. Sublcasses may
525   /// override this function to provide alternate behavior.
526   DeclarationNameInfo
527   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
528 
529   bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
530       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
531   concepts::TypeRequirement *
532   TransformTypeRequirement(concepts::TypeRequirement *Req);
533   concepts::ExprRequirement *
534   TransformExprRequirement(concepts::ExprRequirement *Req);
535   concepts::NestedRequirement *
536   TransformNestedRequirement(concepts::NestedRequirement *Req);
537 
538   /// Transform the given template name.
539   ///
540   /// \param SS The nested-name-specifier that qualifies the template
541   /// name. This nested-name-specifier must already have been transformed.
542   ///
543   /// \param Name The template name to transform.
544   ///
545   /// \param NameLoc The source location of the template name.
546   ///
547   /// \param ObjectType If we're translating a template name within a member
548   /// access expression, this is the type of the object whose member template
549   /// is being referenced.
550   ///
551   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
552   /// also refers to a name within the current (lexical) scope, this is the
553   /// declaration it refers to.
554   ///
555   /// By default, transforms the template name by transforming the declarations
556   /// and nested-name-specifiers that occur within the template name.
557   /// Subclasses may override this function to provide alternate behavior.
558   TemplateName
559   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
560                         SourceLocation NameLoc,
561                         QualType ObjectType = QualType(),
562                         NamedDecl *FirstQualifierInScope = nullptr,
563                         bool AllowInjectedClassName = false);
564 
565   /// Transform the given template argument.
566   ///
567   /// By default, this operation transforms the type, expression, or
568   /// declaration stored within the template argument and constructs a
569   /// new template argument from the transformed result. Subclasses may
570   /// override this function to provide alternate behavior.
571   ///
572   /// Returns true if there was an error.
573   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
574                                  TemplateArgumentLoc &Output,
575                                  bool Uneval = false);
576 
577   /// Transform the given set of template arguments.
578   ///
579   /// By default, this operation transforms all of the template arguments
580   /// in the input set using \c TransformTemplateArgument(), and appends
581   /// the transformed arguments to the output list.
582   ///
583   /// Note that this overload of \c TransformTemplateArguments() is merely
584   /// a convenience function. Subclasses that wish to override this behavior
585   /// should override the iterator-based member template version.
586   ///
587   /// \param Inputs The set of template arguments to be transformed.
588   ///
589   /// \param NumInputs The number of template arguments in \p Inputs.
590   ///
591   /// \param Outputs The set of transformed template arguments output by this
592   /// routine.
593   ///
594   /// Returns true if an error occurred.
595   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
596                                   unsigned NumInputs,
597                                   TemplateArgumentListInfo &Outputs,
598                                   bool Uneval = false) {
599     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
600                                       Uneval);
601   }
602 
603   /// Transform the given set of template arguments.
604   ///
605   /// By default, this operation transforms all of the template arguments
606   /// in the input set using \c TransformTemplateArgument(), and appends
607   /// the transformed arguments to the output list.
608   ///
609   /// \param First An iterator to the first template argument.
610   ///
611   /// \param Last An iterator one step past the last template argument.
612   ///
613   /// \param Outputs The set of transformed template arguments output by this
614   /// routine.
615   ///
616   /// Returns true if an error occurred.
617   template<typename InputIterator>
618   bool TransformTemplateArguments(InputIterator First,
619                                   InputIterator Last,
620                                   TemplateArgumentListInfo &Outputs,
621                                   bool Uneval = false);
622 
623   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
624   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
625                                  TemplateArgumentLoc &ArgLoc);
626 
627   /// Fakes up a TypeSourceInfo for a type.
628   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
629     return SemaRef.Context.getTrivialTypeSourceInfo(T,
630                        getDerived().getBaseLocation());
631   }
632 
633 #define ABSTRACT_TYPELOC(CLASS, PARENT)
634 #define TYPELOC(CLASS, PARENT)                                   \
635   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
636 #include "clang/AST/TypeLocNodes.def"
637 
638   template<typename Fn>
639   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
640                                       FunctionProtoTypeLoc TL,
641                                       CXXRecordDecl *ThisContext,
642                                       Qualifiers ThisTypeQuals,
643                                       Fn TransformExceptionSpec);
644 
645   bool TransformExceptionSpec(SourceLocation Loc,
646                               FunctionProtoType::ExceptionSpecInfo &ESI,
647                               SmallVectorImpl<QualType> &Exceptions,
648                               bool &Changed);
649 
650   StmtResult TransformSEHHandler(Stmt *Handler);
651 
652   QualType
653   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
654                                       TemplateSpecializationTypeLoc TL,
655                                       TemplateName Template);
656 
657   QualType
658   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
659                                       DependentTemplateSpecializationTypeLoc TL,
660                                                TemplateName Template,
661                                                CXXScopeSpec &SS);
662 
663   QualType TransformDependentTemplateSpecializationType(
664       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
665       NestedNameSpecifierLoc QualifierLoc);
666 
667   /// Transforms the parameters of a function type into the
668   /// given vectors.
669   ///
670   /// The result vectors should be kept in sync; null entries in the
671   /// variables vector are acceptable.
672   ///
673   /// Return true on error.
674   bool TransformFunctionTypeParams(
675       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
676       const QualType *ParamTypes,
677       const FunctionProtoType::ExtParameterInfo *ParamInfos,
678       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
679       Sema::ExtParameterInfoBuilder &PInfos);
680 
681   /// Transforms a single function-type parameter.  Return null
682   /// on error.
683   ///
684   /// \param indexAdjustment - A number to add to the parameter's
685   ///   scope index;  can be negative
686   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
687                                           int indexAdjustment,
688                                           Optional<unsigned> NumExpansions,
689                                           bool ExpectParameterPack);
690 
691   /// Transform the body of a lambda-expression.
692   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
693   /// Alternative implementation of TransformLambdaBody that skips transforming
694   /// the body.
695   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
696 
697   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
698 
699   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
700   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
701 
702   TemplateParameterList *TransformTemplateParameterList(
703         TemplateParameterList *TPL) {
704     return TPL;
705   }
706 
707   ExprResult TransformAddressOfOperand(Expr *E);
708 
709   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
710                                                 bool IsAddressOfOperand,
711                                                 TypeSourceInfo **RecoveryTSI);
712 
713   ExprResult TransformParenDependentScopeDeclRefExpr(
714       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
715       TypeSourceInfo **RecoveryTSI);
716 
717   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
718 
719 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
720 // amount of stack usage with clang.
721 #define STMT(Node, Parent)                        \
722   LLVM_ATTRIBUTE_NOINLINE \
723   StmtResult Transform##Node(Node *S);
724 #define VALUESTMT(Node, Parent)                   \
725   LLVM_ATTRIBUTE_NOINLINE \
726   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
727 #define EXPR(Node, Parent)                        \
728   LLVM_ATTRIBUTE_NOINLINE \
729   ExprResult Transform##Node(Node *E);
730 #define ABSTRACT_STMT(Stmt)
731 #include "clang/AST/StmtNodes.inc"
732 
733 #define OMP_CLAUSE_CLASS(Enum, Str, Class)                                           \
734   LLVM_ATTRIBUTE_NOINLINE \
735   OMPClause *Transform ## Class(Class *S);
736 #include "llvm/Frontend/OpenMP/OMPKinds.def"
737 
738   /// Build a new qualified type given its unqualified type and type location.
739   ///
740   /// By default, this routine adds type qualifiers only to types that can
741   /// have qualifiers, and silently suppresses those qualifiers that are not
742   /// permitted. Subclasses may override this routine to provide different
743   /// behavior.
744   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
745 
746   /// Build a new pointer type given its pointee type.
747   ///
748   /// By default, performs semantic analysis when building the pointer type.
749   /// Subclasses may override this routine to provide different behavior.
750   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
751 
752   /// Build a new block pointer type given its pointee type.
753   ///
754   /// By default, performs semantic analysis when building the block pointer
755   /// type. Subclasses may override this routine to provide different behavior.
756   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
757 
758   /// Build a new reference type given the type it references.
759   ///
760   /// By default, performs semantic analysis when building the
761   /// reference type. Subclasses may override this routine to provide
762   /// different behavior.
763   ///
764   /// \param LValue whether the type was written with an lvalue sigil
765   /// or an rvalue sigil.
766   QualType RebuildReferenceType(QualType ReferentType,
767                                 bool LValue,
768                                 SourceLocation Sigil);
769 
770   /// Build a new member pointer type given the pointee type and the
771   /// class type it refers into.
772   ///
773   /// By default, performs semantic analysis when building the member pointer
774   /// type. Subclasses may override this routine to provide different behavior.
775   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
776                                     SourceLocation Sigil);
777 
778   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
779                                     SourceLocation ProtocolLAngleLoc,
780                                     ArrayRef<ObjCProtocolDecl *> Protocols,
781                                     ArrayRef<SourceLocation> ProtocolLocs,
782                                     SourceLocation ProtocolRAngleLoc);
783 
784   /// Build an Objective-C object type.
785   ///
786   /// By default, performs semantic analysis when building the object type.
787   /// Subclasses may override this routine to provide different behavior.
788   QualType RebuildObjCObjectType(QualType BaseType,
789                                  SourceLocation Loc,
790                                  SourceLocation TypeArgsLAngleLoc,
791                                  ArrayRef<TypeSourceInfo *> TypeArgs,
792                                  SourceLocation TypeArgsRAngleLoc,
793                                  SourceLocation ProtocolLAngleLoc,
794                                  ArrayRef<ObjCProtocolDecl *> Protocols,
795                                  ArrayRef<SourceLocation> ProtocolLocs,
796                                  SourceLocation ProtocolRAngleLoc);
797 
798   /// Build a new Objective-C object pointer type given the pointee type.
799   ///
800   /// By default, directly builds the pointer type, with no additional semantic
801   /// analysis.
802   QualType RebuildObjCObjectPointerType(QualType PointeeType,
803                                         SourceLocation Star);
804 
805   /// Build a new array type given the element type, size
806   /// modifier, size of the array (if known), size expression, and index type
807   /// qualifiers.
808   ///
809   /// By default, performs semantic analysis when building the array type.
810   /// Subclasses may override this routine to provide different behavior.
811   /// Also by default, all of the other Rebuild*Array
812   QualType RebuildArrayType(QualType ElementType,
813                             ArrayType::ArraySizeModifier SizeMod,
814                             const llvm::APInt *Size,
815                             Expr *SizeExpr,
816                             unsigned IndexTypeQuals,
817                             SourceRange BracketsRange);
818 
819   /// Build a new constant array type given the element type, size
820   /// modifier, (known) size of the array, and index type qualifiers.
821   ///
822   /// By default, performs semantic analysis when building the array type.
823   /// Subclasses may override this routine to provide different behavior.
824   QualType RebuildConstantArrayType(QualType ElementType,
825                                     ArrayType::ArraySizeModifier SizeMod,
826                                     const llvm::APInt &Size,
827                                     Expr *SizeExpr,
828                                     unsigned IndexTypeQuals,
829                                     SourceRange BracketsRange);
830 
831   /// Build a new incomplete array type given the element type, size
832   /// modifier, and index type qualifiers.
833   ///
834   /// By default, performs semantic analysis when building the array type.
835   /// Subclasses may override this routine to provide different behavior.
836   QualType RebuildIncompleteArrayType(QualType ElementType,
837                                       ArrayType::ArraySizeModifier SizeMod,
838                                       unsigned IndexTypeQuals,
839                                       SourceRange BracketsRange);
840 
841   /// Build a new variable-length array type given the element type,
842   /// size modifier, size expression, and index type qualifiers.
843   ///
844   /// By default, performs semantic analysis when building the array type.
845   /// Subclasses may override this routine to provide different behavior.
846   QualType RebuildVariableArrayType(QualType ElementType,
847                                     ArrayType::ArraySizeModifier SizeMod,
848                                     Expr *SizeExpr,
849                                     unsigned IndexTypeQuals,
850                                     SourceRange BracketsRange);
851 
852   /// Build a new dependent-sized array type given the element type,
853   /// size modifier, size expression, and index type qualifiers.
854   ///
855   /// By default, performs semantic analysis when building the array type.
856   /// Subclasses may override this routine to provide different behavior.
857   QualType RebuildDependentSizedArrayType(QualType ElementType,
858                                           ArrayType::ArraySizeModifier SizeMod,
859                                           Expr *SizeExpr,
860                                           unsigned IndexTypeQuals,
861                                           SourceRange BracketsRange);
862 
863   /// Build a new vector type given the element type and
864   /// number of elements.
865   ///
866   /// By default, performs semantic analysis when building the vector type.
867   /// Subclasses may override this routine to provide different behavior.
868   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
869                              VectorType::VectorKind VecKind);
870 
871   /// Build a new potentially dependently-sized extended vector type
872   /// given the element type and number of elements.
873   ///
874   /// By default, performs semantic analysis when building the vector type.
875   /// Subclasses may override this routine to provide different behavior.
876   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
877                                            SourceLocation AttributeLoc,
878                                            VectorType::VectorKind);
879 
880   /// Build a new extended vector type given the element type and
881   /// number of elements.
882   ///
883   /// By default, performs semantic analysis when building the vector type.
884   /// Subclasses may override this routine to provide different behavior.
885   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
886                                 SourceLocation AttributeLoc);
887 
888   /// Build a new potentially dependently-sized extended vector type
889   /// given the element type and number of elements.
890   ///
891   /// By default, performs semantic analysis when building the vector type.
892   /// Subclasses may override this routine to provide different behavior.
893   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
894                                               Expr *SizeExpr,
895                                               SourceLocation AttributeLoc);
896 
897   /// Build a new matrix type given the element type and dimensions.
898   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
899                                      unsigned NumColumns);
900 
901   /// Build a new matrix type given the type and dependently-defined
902   /// dimensions.
903   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
904                                            Expr *ColumnExpr,
905                                            SourceLocation AttributeLoc);
906 
907   /// Build a new DependentAddressSpaceType or return the pointee
908   /// type variable with the correct address space (retrieved from
909   /// AddrSpaceExpr) applied to it. The former will be returned in cases
910   /// where the address space remains dependent.
911   ///
912   /// By default, performs semantic analysis when building the type with address
913   /// space applied. Subclasses may override this routine to provide different
914   /// behavior.
915   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
916                                             Expr *AddrSpaceExpr,
917                                             SourceLocation AttributeLoc);
918 
919   /// Build a new function type.
920   ///
921   /// By default, performs semantic analysis when building the function type.
922   /// Subclasses may override this routine to provide different behavior.
923   QualType RebuildFunctionProtoType(QualType T,
924                                     MutableArrayRef<QualType> ParamTypes,
925                                     const FunctionProtoType::ExtProtoInfo &EPI);
926 
927   /// Build a new unprototyped function type.
928   QualType RebuildFunctionNoProtoType(QualType ResultType);
929 
930   /// Rebuild an unresolved typename type, given the decl that
931   /// the UnresolvedUsingTypenameDecl was transformed to.
932   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
933 
934   /// Build a new typedef type.
935   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
936     return SemaRef.Context.getTypeDeclType(Typedef);
937   }
938 
939   /// Build a new MacroDefined type.
940   QualType RebuildMacroQualifiedType(QualType T,
941                                      const IdentifierInfo *MacroII) {
942     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
943   }
944 
945   /// Build a new class/struct/union type.
946   QualType RebuildRecordType(RecordDecl *Record) {
947     return SemaRef.Context.getTypeDeclType(Record);
948   }
949 
950   /// Build a new Enum type.
951   QualType RebuildEnumType(EnumDecl *Enum) {
952     return SemaRef.Context.getTypeDeclType(Enum);
953   }
954 
955   /// Build a new typeof(expr) type.
956   ///
957   /// By default, performs semantic analysis when building the typeof type.
958   /// Subclasses may override this routine to provide different behavior.
959   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
960 
961   /// Build a new typeof(type) type.
962   ///
963   /// By default, builds a new TypeOfType with the given underlying type.
964   QualType RebuildTypeOfType(QualType Underlying);
965 
966   /// Build a new unary transform type.
967   QualType RebuildUnaryTransformType(QualType BaseType,
968                                      UnaryTransformType::UTTKind UKind,
969                                      SourceLocation Loc);
970 
971   /// Build a new C++11 decltype type.
972   ///
973   /// By default, performs semantic analysis when building the decltype type.
974   /// Subclasses may override this routine to provide different behavior.
975   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
976 
977   /// Build a new C++11 auto type.
978   ///
979   /// By default, builds a new AutoType with the given deduced type.
980   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
981                            ConceptDecl *TypeConstraintConcept,
982                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
983     // Note, IsDependent is always false here: we implicitly convert an 'auto'
984     // which has been deduced to a dependent type into an undeduced 'auto', so
985     // that we'll retry deduction after the transformation.
986     return SemaRef.Context.getAutoType(Deduced, Keyword,
987                                        /*IsDependent*/ false, /*IsPack=*/false,
988                                        TypeConstraintConcept,
989                                        TypeConstraintArgs);
990   }
991 
992   /// By default, builds a new DeducedTemplateSpecializationType with the given
993   /// deduced type.
994   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
995       QualType Deduced) {
996     return SemaRef.Context.getDeducedTemplateSpecializationType(
997         Template, Deduced, /*IsDependent*/ false);
998   }
999 
1000   /// Build a new template specialization type.
1001   ///
1002   /// By default, performs semantic analysis when building the template
1003   /// specialization type. Subclasses may override this routine to provide
1004   /// different behavior.
1005   QualType RebuildTemplateSpecializationType(TemplateName Template,
1006                                              SourceLocation TemplateLoc,
1007                                              TemplateArgumentListInfo &Args);
1008 
1009   /// Build a new parenthesized type.
1010   ///
1011   /// By default, builds a new ParenType type from the inner type.
1012   /// Subclasses may override this routine to provide different behavior.
1013   QualType RebuildParenType(QualType InnerType) {
1014     return SemaRef.BuildParenType(InnerType);
1015   }
1016 
1017   /// Build a new qualified name type.
1018   ///
1019   /// By default, builds a new ElaboratedType type from the keyword,
1020   /// the nested-name-specifier and the named type.
1021   /// Subclasses may override this routine to provide different behavior.
1022   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1023                                  ElaboratedTypeKeyword Keyword,
1024                                  NestedNameSpecifierLoc QualifierLoc,
1025                                  QualType Named) {
1026     return SemaRef.Context.getElaboratedType(Keyword,
1027                                          QualifierLoc.getNestedNameSpecifier(),
1028                                              Named);
1029   }
1030 
1031   /// Build a new typename type that refers to a template-id.
1032   ///
1033   /// By default, builds a new DependentNameType type from the
1034   /// nested-name-specifier and the given type. Subclasses may override
1035   /// this routine to provide different behavior.
1036   QualType RebuildDependentTemplateSpecializationType(
1037                                           ElaboratedTypeKeyword Keyword,
1038                                           NestedNameSpecifierLoc QualifierLoc,
1039                                           SourceLocation TemplateKWLoc,
1040                                           const IdentifierInfo *Name,
1041                                           SourceLocation NameLoc,
1042                                           TemplateArgumentListInfo &Args,
1043                                           bool AllowInjectedClassName) {
1044     // Rebuild the template name.
1045     // TODO: avoid TemplateName abstraction
1046     CXXScopeSpec SS;
1047     SS.Adopt(QualifierLoc);
1048     TemplateName InstName = getDerived().RebuildTemplateName(
1049         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1050         AllowInjectedClassName);
1051 
1052     if (InstName.isNull())
1053       return QualType();
1054 
1055     // If it's still dependent, make a dependent specialization.
1056     if (InstName.getAsDependentTemplateName())
1057       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1058                                           QualifierLoc.getNestedNameSpecifier(),
1059                                                                     Name,
1060                                                                     Args);
1061 
1062     // Otherwise, make an elaborated type wrapping a non-dependent
1063     // specialization.
1064     QualType T =
1065     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1066     if (T.isNull()) return QualType();
1067 
1068     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1069       return T;
1070 
1071     return SemaRef.Context.getElaboratedType(Keyword,
1072                                        QualifierLoc.getNestedNameSpecifier(),
1073                                              T);
1074   }
1075 
1076   /// Build a new typename type that refers to an identifier.
1077   ///
1078   /// By default, performs semantic analysis when building the typename type
1079   /// (or elaborated type). Subclasses may override this routine to provide
1080   /// different behavior.
1081   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1082                                     SourceLocation KeywordLoc,
1083                                     NestedNameSpecifierLoc QualifierLoc,
1084                                     const IdentifierInfo *Id,
1085                                     SourceLocation IdLoc,
1086                                     bool DeducedTSTContext) {
1087     CXXScopeSpec SS;
1088     SS.Adopt(QualifierLoc);
1089 
1090     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1091       // If the name is still dependent, just build a new dependent name type.
1092       if (!SemaRef.computeDeclContext(SS))
1093         return SemaRef.Context.getDependentNameType(Keyword,
1094                                           QualifierLoc.getNestedNameSpecifier(),
1095                                                     Id);
1096     }
1097 
1098     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1099       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1100                                        *Id, IdLoc, DeducedTSTContext);
1101     }
1102 
1103     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1104 
1105     // We had a dependent elaborated-type-specifier that has been transformed
1106     // into a non-dependent elaborated-type-specifier. Find the tag we're
1107     // referring to.
1108     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1109     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1110     if (!DC)
1111       return QualType();
1112 
1113     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1114       return QualType();
1115 
1116     TagDecl *Tag = nullptr;
1117     SemaRef.LookupQualifiedName(Result, DC);
1118     switch (Result.getResultKind()) {
1119       case LookupResult::NotFound:
1120       case LookupResult::NotFoundInCurrentInstantiation:
1121         break;
1122 
1123       case LookupResult::Found:
1124         Tag = Result.getAsSingle<TagDecl>();
1125         break;
1126 
1127       case LookupResult::FoundOverloaded:
1128       case LookupResult::FoundUnresolvedValue:
1129         llvm_unreachable("Tag lookup cannot find non-tags");
1130 
1131       case LookupResult::Ambiguous:
1132         // Let the LookupResult structure handle ambiguities.
1133         return QualType();
1134     }
1135 
1136     if (!Tag) {
1137       // Check where the name exists but isn't a tag type and use that to emit
1138       // better diagnostics.
1139       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1140       SemaRef.LookupQualifiedName(Result, DC);
1141       switch (Result.getResultKind()) {
1142         case LookupResult::Found:
1143         case LookupResult::FoundOverloaded:
1144         case LookupResult::FoundUnresolvedValue: {
1145           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1146           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1147           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1148                                                                << NTK << Kind;
1149           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1150           break;
1151         }
1152         default:
1153           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1154               << Kind << Id << DC << QualifierLoc.getSourceRange();
1155           break;
1156       }
1157       return QualType();
1158     }
1159 
1160     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1161                                               IdLoc, Id)) {
1162       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1163       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1164       return QualType();
1165     }
1166 
1167     // Build the elaborated-type-specifier type.
1168     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1169     return SemaRef.Context.getElaboratedType(Keyword,
1170                                          QualifierLoc.getNestedNameSpecifier(),
1171                                              T);
1172   }
1173 
1174   /// Build a new pack expansion type.
1175   ///
1176   /// By default, builds a new PackExpansionType type from the given pattern.
1177   /// Subclasses may override this routine to provide different behavior.
1178   QualType RebuildPackExpansionType(QualType Pattern,
1179                                     SourceRange PatternRange,
1180                                     SourceLocation EllipsisLoc,
1181                                     Optional<unsigned> NumExpansions) {
1182     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1183                                         NumExpansions);
1184   }
1185 
1186   /// Build a new atomic type given its value type.
1187   ///
1188   /// By default, performs semantic analysis when building the atomic type.
1189   /// Subclasses may override this routine to provide different behavior.
1190   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1191 
1192   /// Build a new pipe type given its value type.
1193   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1194                            bool isReadPipe);
1195 
1196    /// Build an extended int given its value type.
1197   QualType RebuildExtIntType(bool IsUnsigned, unsigned NumBits,
1198                              SourceLocation Loc);
1199 
1200   /// Build a dependent extended int given its value type.
1201   QualType RebuildDependentExtIntType(bool IsUnsigned, Expr *NumBitsExpr,
1202                                       SourceLocation Loc);
1203 
1204   /// Build a new template name given a nested name specifier, a flag
1205   /// indicating whether the "template" keyword was provided, and the template
1206   /// that the template name refers to.
1207   ///
1208   /// By default, builds the new template name directly. Subclasses may override
1209   /// this routine to provide different behavior.
1210   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1211                                    bool TemplateKW,
1212                                    TemplateDecl *Template);
1213 
1214   /// Build a new template name given a nested name specifier and the
1215   /// name that is referred to as a template.
1216   ///
1217   /// By default, performs semantic analysis to determine whether the name can
1218   /// be resolved to a specific template, then builds the appropriate kind of
1219   /// template name. Subclasses may override this routine to provide different
1220   /// behavior.
1221   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1222                                    SourceLocation TemplateKWLoc,
1223                                    const IdentifierInfo &Name,
1224                                    SourceLocation NameLoc, QualType ObjectType,
1225                                    NamedDecl *FirstQualifierInScope,
1226                                    bool AllowInjectedClassName);
1227 
1228   /// Build a new template name given a nested name specifier and the
1229   /// overloaded operator name that is referred to as a template.
1230   ///
1231   /// By default, performs semantic analysis to determine whether the name can
1232   /// be resolved to a specific template, then builds the appropriate kind of
1233   /// template name. Subclasses may override this routine to provide different
1234   /// behavior.
1235   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1236                                    SourceLocation TemplateKWLoc,
1237                                    OverloadedOperatorKind Operator,
1238                                    SourceLocation NameLoc, QualType ObjectType,
1239                                    bool AllowInjectedClassName);
1240 
1241   /// Build a new template name given a template template parameter pack
1242   /// and the
1243   ///
1244   /// By default, performs semantic analysis to determine whether the name can
1245   /// be resolved to a specific template, then builds the appropriate kind of
1246   /// template name. Subclasses may override this routine to provide different
1247   /// behavior.
1248   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1249                                    const TemplateArgument &ArgPack) {
1250     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1251   }
1252 
1253   /// Build a new compound statement.
1254   ///
1255   /// By default, performs semantic analysis to build the new statement.
1256   /// Subclasses may override this routine to provide different behavior.
1257   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1258                                        MultiStmtArg Statements,
1259                                        SourceLocation RBraceLoc,
1260                                        bool IsStmtExpr) {
1261     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1262                                        IsStmtExpr);
1263   }
1264 
1265   /// Build a new case statement.
1266   ///
1267   /// By default, performs semantic analysis to build the new statement.
1268   /// Subclasses may override this routine to provide different behavior.
1269   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1270                                    Expr *LHS,
1271                                    SourceLocation EllipsisLoc,
1272                                    Expr *RHS,
1273                                    SourceLocation ColonLoc) {
1274     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1275                                    ColonLoc);
1276   }
1277 
1278   /// Attach the body to a new case statement.
1279   ///
1280   /// By default, performs semantic analysis to build the new statement.
1281   /// Subclasses may override this routine to provide different behavior.
1282   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1283     getSema().ActOnCaseStmtBody(S, Body);
1284     return S;
1285   }
1286 
1287   /// Build a new default statement.
1288   ///
1289   /// By default, performs semantic analysis to build the new statement.
1290   /// Subclasses may override this routine to provide different behavior.
1291   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1292                                       SourceLocation ColonLoc,
1293                                       Stmt *SubStmt) {
1294     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1295                                       /*CurScope=*/nullptr);
1296   }
1297 
1298   /// Build a new label statement.
1299   ///
1300   /// By default, performs semantic analysis to build the new statement.
1301   /// Subclasses may override this routine to provide different behavior.
1302   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1303                               SourceLocation ColonLoc, Stmt *SubStmt) {
1304     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1305   }
1306 
1307   /// Build a new label statement.
1308   ///
1309   /// By default, performs semantic analysis to build the new statement.
1310   /// Subclasses may override this routine to provide different behavior.
1311   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1312                                    ArrayRef<const Attr*> Attrs,
1313                                    Stmt *SubStmt) {
1314     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1315   }
1316 
1317   /// Build a new "if" statement.
1318   ///
1319   /// By default, performs semantic analysis to build the new statement.
1320   /// Subclasses may override this routine to provide different behavior.
1321   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1322                            Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1323                            SourceLocation ElseLoc, Stmt *Else) {
1324     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1325                                  ElseLoc, Else);
1326   }
1327 
1328   /// Start building a new switch statement.
1329   ///
1330   /// By default, performs semantic analysis to build the new statement.
1331   /// Subclasses may override this routine to provide different behavior.
1332   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1333                                     Sema::ConditionResult Cond) {
1334     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1335   }
1336 
1337   /// Attach the body to the switch statement.
1338   ///
1339   /// By default, performs semantic analysis to build the new statement.
1340   /// Subclasses may override this routine to provide different behavior.
1341   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1342                                    Stmt *Switch, Stmt *Body) {
1343     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1344   }
1345 
1346   /// Build a new while statement.
1347   ///
1348   /// By default, performs semantic analysis to build the new statement.
1349   /// Subclasses may override this routine to provide different behavior.
1350   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1351                               Sema::ConditionResult Cond,
1352                               SourceLocation RParenLoc, Stmt *Body) {
1353     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1354   }
1355 
1356   /// Build a new do-while statement.
1357   ///
1358   /// By default, performs semantic analysis to build the new statement.
1359   /// Subclasses may override this routine to provide different behavior.
1360   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1361                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1362                            Expr *Cond, SourceLocation RParenLoc) {
1363     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1364                                  Cond, RParenLoc);
1365   }
1366 
1367   /// Build a new for 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 RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1372                             Stmt *Init, Sema::ConditionResult Cond,
1373                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1374                             Stmt *Body) {
1375     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1376                                   Inc, RParenLoc, Body);
1377   }
1378 
1379   /// Build a new goto statement.
1380   ///
1381   /// By default, performs semantic analysis to build the new statement.
1382   /// Subclasses may override this routine to provide different behavior.
1383   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1384                              LabelDecl *Label) {
1385     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1386   }
1387 
1388   /// Build a new indirect goto statement.
1389   ///
1390   /// By default, performs semantic analysis to build the new statement.
1391   /// Subclasses may override this routine to provide different behavior.
1392   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1393                                      SourceLocation StarLoc,
1394                                      Expr *Target) {
1395     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1396   }
1397 
1398   /// Build a new return statement.
1399   ///
1400   /// By default, performs semantic analysis to build the new statement.
1401   /// Subclasses may override this routine to provide different behavior.
1402   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1403     return getSema().BuildReturnStmt(ReturnLoc, Result);
1404   }
1405 
1406   /// Build a new declaration statement.
1407   ///
1408   /// By default, performs semantic analysis to build the new statement.
1409   /// Subclasses may override this routine to provide different behavior.
1410   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1411                              SourceLocation StartLoc, SourceLocation EndLoc) {
1412     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1413     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1414   }
1415 
1416   /// Build a new inline asm statement.
1417   ///
1418   /// By default, performs semantic analysis to build the new statement.
1419   /// Subclasses may override this routine to provide different behavior.
1420   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1421                                bool IsVolatile, unsigned NumOutputs,
1422                                unsigned NumInputs, IdentifierInfo **Names,
1423                                MultiExprArg Constraints, MultiExprArg Exprs,
1424                                Expr *AsmString, MultiExprArg Clobbers,
1425                                unsigned NumLabels,
1426                                SourceLocation RParenLoc) {
1427     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1428                                      NumInputs, Names, Constraints, Exprs,
1429                                      AsmString, Clobbers, NumLabels, RParenLoc);
1430   }
1431 
1432   /// Build a new MS style inline asm statement.
1433   ///
1434   /// By default, performs semantic analysis to build the new statement.
1435   /// Subclasses may override this routine to provide different behavior.
1436   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1437                               ArrayRef<Token> AsmToks,
1438                               StringRef AsmString,
1439                               unsigned NumOutputs, unsigned NumInputs,
1440                               ArrayRef<StringRef> Constraints,
1441                               ArrayRef<StringRef> Clobbers,
1442                               ArrayRef<Expr*> Exprs,
1443                               SourceLocation EndLoc) {
1444     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1445                                     NumOutputs, NumInputs,
1446                                     Constraints, Clobbers, Exprs, EndLoc);
1447   }
1448 
1449   /// Build a new co_return statement.
1450   ///
1451   /// By default, performs semantic analysis to build the new statement.
1452   /// Subclasses may override this routine to provide different behavior.
1453   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1454                                  bool IsImplicit) {
1455     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1456   }
1457 
1458   /// Build a new co_await expression.
1459   ///
1460   /// By default, performs semantic analysis to build the new expression.
1461   /// Subclasses may override this routine to provide different behavior.
1462   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1463                                 bool IsImplicit) {
1464     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1465   }
1466 
1467   /// Build a new co_await expression.
1468   ///
1469   /// By default, performs semantic analysis to build the new expression.
1470   /// Subclasses may override this routine to provide different behavior.
1471   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1472                                          Expr *Result,
1473                                          UnresolvedLookupExpr *Lookup) {
1474     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1475   }
1476 
1477   /// Build a new co_yield expression.
1478   ///
1479   /// By default, performs semantic analysis to build the new expression.
1480   /// Subclasses may override this routine to provide different behavior.
1481   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1482     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1483   }
1484 
1485   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1486     return getSema().BuildCoroutineBodyStmt(Args);
1487   }
1488 
1489   /// Build a new Objective-C \@try statement.
1490   ///
1491   /// By default, performs semantic analysis to build the new statement.
1492   /// Subclasses may override this routine to provide different behavior.
1493   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1494                                         Stmt *TryBody,
1495                                         MultiStmtArg CatchStmts,
1496                                         Stmt *Finally) {
1497     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1498                                         Finally);
1499   }
1500 
1501   /// Rebuild an Objective-C exception declaration.
1502   ///
1503   /// By default, performs semantic analysis to build the new declaration.
1504   /// Subclasses may override this routine to provide different behavior.
1505   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1506                                     TypeSourceInfo *TInfo, QualType T) {
1507     return getSema().BuildObjCExceptionDecl(TInfo, T,
1508                                             ExceptionDecl->getInnerLocStart(),
1509                                             ExceptionDecl->getLocation(),
1510                                             ExceptionDecl->getIdentifier());
1511   }
1512 
1513   /// Build a new Objective-C \@catch statement.
1514   ///
1515   /// By default, performs semantic analysis to build the new statement.
1516   /// Subclasses may override this routine to provide different behavior.
1517   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1518                                           SourceLocation RParenLoc,
1519                                           VarDecl *Var,
1520                                           Stmt *Body) {
1521     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1522                                           Var, Body);
1523   }
1524 
1525   /// Build a new Objective-C \@finally statement.
1526   ///
1527   /// By default, performs semantic analysis to build the new statement.
1528   /// Subclasses may override this routine to provide different behavior.
1529   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1530                                             Stmt *Body) {
1531     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1532   }
1533 
1534   /// Build a new Objective-C \@throw statement.
1535   ///
1536   /// By default, performs semantic analysis to build the new statement.
1537   /// Subclasses may override this routine to provide different behavior.
1538   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1539                                           Expr *Operand) {
1540     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1541   }
1542 
1543   /// Build a new OpenMP executable directive.
1544   ///
1545   /// By default, performs semantic analysis to build the new statement.
1546   /// Subclasses may override this routine to provide different behavior.
1547   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1548                                            DeclarationNameInfo DirName,
1549                                            OpenMPDirectiveKind CancelRegion,
1550                                            ArrayRef<OMPClause *> Clauses,
1551                                            Stmt *AStmt, SourceLocation StartLoc,
1552                                            SourceLocation EndLoc) {
1553     return getSema().ActOnOpenMPExecutableDirective(
1554         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1555   }
1556 
1557   /// Build a new OpenMP 'if' clause.
1558   ///
1559   /// By default, performs semantic analysis to build the new OpenMP clause.
1560   /// Subclasses may override this routine to provide different behavior.
1561   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1562                                 Expr *Condition, SourceLocation StartLoc,
1563                                 SourceLocation LParenLoc,
1564                                 SourceLocation NameModifierLoc,
1565                                 SourceLocation ColonLoc,
1566                                 SourceLocation EndLoc) {
1567     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1568                                          LParenLoc, NameModifierLoc, ColonLoc,
1569                                          EndLoc);
1570   }
1571 
1572   /// Build a new OpenMP 'final' clause.
1573   ///
1574   /// By default, performs semantic analysis to build the new OpenMP clause.
1575   /// Subclasses may override this routine to provide different behavior.
1576   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1577                                    SourceLocation LParenLoc,
1578                                    SourceLocation EndLoc) {
1579     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1580                                             EndLoc);
1581   }
1582 
1583   /// Build a new OpenMP 'num_threads' clause.
1584   ///
1585   /// By default, performs semantic analysis to build the new OpenMP clause.
1586   /// Subclasses may override this routine to provide different behavior.
1587   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1588                                         SourceLocation StartLoc,
1589                                         SourceLocation LParenLoc,
1590                                         SourceLocation EndLoc) {
1591     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1592                                                  LParenLoc, EndLoc);
1593   }
1594 
1595   /// Build a new OpenMP 'safelen' clause.
1596   ///
1597   /// By default, performs semantic analysis to build the new OpenMP clause.
1598   /// Subclasses may override this routine to provide different behavior.
1599   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1600                                      SourceLocation LParenLoc,
1601                                      SourceLocation EndLoc) {
1602     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1603   }
1604 
1605   /// Build a new OpenMP 'simdlen' clause.
1606   ///
1607   /// By default, performs semantic analysis to build the new OpenMP clause.
1608   /// Subclasses may override this routine to provide different behavior.
1609   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1610                                      SourceLocation LParenLoc,
1611                                      SourceLocation EndLoc) {
1612     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1613   }
1614 
1615   /// Build a new OpenMP 'allocator' clause.
1616   ///
1617   /// By default, performs semantic analysis to build the new OpenMP clause.
1618   /// Subclasses may override this routine to provide different behavior.
1619   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1620                                        SourceLocation LParenLoc,
1621                                        SourceLocation EndLoc) {
1622     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1623   }
1624 
1625   /// Build a new OpenMP 'collapse' clause.
1626   ///
1627   /// By default, performs semantic analysis to build the new OpenMP clause.
1628   /// Subclasses may override this routine to provide different behavior.
1629   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1630                                       SourceLocation LParenLoc,
1631                                       SourceLocation EndLoc) {
1632     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1633                                                EndLoc);
1634   }
1635 
1636   /// Build a new OpenMP 'default' clause.
1637   ///
1638   /// By default, performs semantic analysis to build the new OpenMP clause.
1639   /// Subclasses may override this routine to provide different behavior.
1640   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1641                                      SourceLocation StartLoc,
1642                                      SourceLocation LParenLoc,
1643                                      SourceLocation EndLoc) {
1644     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1645                                               StartLoc, LParenLoc, EndLoc);
1646   }
1647 
1648   /// Build a new OpenMP 'proc_bind' clause.
1649   ///
1650   /// By default, performs semantic analysis to build the new OpenMP clause.
1651   /// Subclasses may override this routine to provide different behavior.
1652   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1653                                       SourceLocation KindKwLoc,
1654                                       SourceLocation StartLoc,
1655                                       SourceLocation LParenLoc,
1656                                       SourceLocation EndLoc) {
1657     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1658                                                StartLoc, LParenLoc, EndLoc);
1659   }
1660 
1661   /// Build a new OpenMP 'schedule' clause.
1662   ///
1663   /// By default, performs semantic analysis to build the new OpenMP clause.
1664   /// Subclasses may override this routine to provide different behavior.
1665   OMPClause *RebuildOMPScheduleClause(
1666       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1667       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1668       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1669       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1670     return getSema().ActOnOpenMPScheduleClause(
1671         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1672         CommaLoc, EndLoc);
1673   }
1674 
1675   /// Build a new OpenMP 'ordered' clause.
1676   ///
1677   /// By default, performs semantic analysis to build the new OpenMP clause.
1678   /// Subclasses may override this routine to provide different behavior.
1679   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1680                                      SourceLocation EndLoc,
1681                                      SourceLocation LParenLoc, Expr *Num) {
1682     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1683   }
1684 
1685   /// Build a new OpenMP 'private' clause.
1686   ///
1687   /// By default, performs semantic analysis to build the new OpenMP clause.
1688   /// Subclasses may override this routine to provide different behavior.
1689   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1690                                      SourceLocation StartLoc,
1691                                      SourceLocation LParenLoc,
1692                                      SourceLocation EndLoc) {
1693     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1694                                               EndLoc);
1695   }
1696 
1697   /// Build a new OpenMP 'firstprivate' clause.
1698   ///
1699   /// By default, performs semantic analysis to build the new OpenMP clause.
1700   /// Subclasses may override this routine to provide different behavior.
1701   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1702                                           SourceLocation StartLoc,
1703                                           SourceLocation LParenLoc,
1704                                           SourceLocation EndLoc) {
1705     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1706                                                    EndLoc);
1707   }
1708 
1709   /// Build a new OpenMP 'lastprivate' clause.
1710   ///
1711   /// By default, performs semantic analysis to build the new OpenMP clause.
1712   /// Subclasses may override this routine to provide different behavior.
1713   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1714                                          OpenMPLastprivateModifier LPKind,
1715                                          SourceLocation LPKindLoc,
1716                                          SourceLocation ColonLoc,
1717                                          SourceLocation StartLoc,
1718                                          SourceLocation LParenLoc,
1719                                          SourceLocation EndLoc) {
1720     return getSema().ActOnOpenMPLastprivateClause(
1721         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1722   }
1723 
1724   /// Build a new OpenMP 'shared' clause.
1725   ///
1726   /// By default, performs semantic analysis to build the new OpenMP clause.
1727   /// Subclasses may override this routine to provide different behavior.
1728   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1729                                     SourceLocation StartLoc,
1730                                     SourceLocation LParenLoc,
1731                                     SourceLocation EndLoc) {
1732     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1733                                              EndLoc);
1734   }
1735 
1736   /// Build a new OpenMP 'reduction' clause.
1737   ///
1738   /// By default, performs semantic analysis to build the new statement.
1739   /// Subclasses may override this routine to provide different behavior.
1740   OMPClause *RebuildOMPReductionClause(
1741       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1742       SourceLocation StartLoc, SourceLocation LParenLoc,
1743       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1744       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1745       const DeclarationNameInfo &ReductionId,
1746       ArrayRef<Expr *> UnresolvedReductions) {
1747     return getSema().ActOnOpenMPReductionClause(
1748         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1749         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1750   }
1751 
1752   /// Build a new OpenMP 'task_reduction' clause.
1753   ///
1754   /// By default, performs semantic analysis to build the new statement.
1755   /// Subclasses may override this routine to provide different behavior.
1756   OMPClause *RebuildOMPTaskReductionClause(
1757       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1758       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1759       CXXScopeSpec &ReductionIdScopeSpec,
1760       const DeclarationNameInfo &ReductionId,
1761       ArrayRef<Expr *> UnresolvedReductions) {
1762     return getSema().ActOnOpenMPTaskReductionClause(
1763         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1764         ReductionId, UnresolvedReductions);
1765   }
1766 
1767   /// Build a new OpenMP 'in_reduction' clause.
1768   ///
1769   /// By default, performs semantic analysis to build the new statement.
1770   /// Subclasses may override this routine to provide different behavior.
1771   OMPClause *
1772   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1773                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1774                               SourceLocation EndLoc,
1775                               CXXScopeSpec &ReductionIdScopeSpec,
1776                               const DeclarationNameInfo &ReductionId,
1777                               ArrayRef<Expr *> UnresolvedReductions) {
1778     return getSema().ActOnOpenMPInReductionClause(
1779         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1780         ReductionId, UnresolvedReductions);
1781   }
1782 
1783   /// Build a new OpenMP 'linear' clause.
1784   ///
1785   /// By default, performs semantic analysis to build the new OpenMP clause.
1786   /// Subclasses may override this routine to provide different behavior.
1787   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1788                                     SourceLocation StartLoc,
1789                                     SourceLocation LParenLoc,
1790                                     OpenMPLinearClauseKind Modifier,
1791                                     SourceLocation ModifierLoc,
1792                                     SourceLocation ColonLoc,
1793                                     SourceLocation EndLoc) {
1794     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1795                                              Modifier, ModifierLoc, ColonLoc,
1796                                              EndLoc);
1797   }
1798 
1799   /// Build a new OpenMP 'aligned' clause.
1800   ///
1801   /// By default, performs semantic analysis to build the new OpenMP clause.
1802   /// Subclasses may override this routine to provide different behavior.
1803   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1804                                      SourceLocation StartLoc,
1805                                      SourceLocation LParenLoc,
1806                                      SourceLocation ColonLoc,
1807                                      SourceLocation EndLoc) {
1808     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1809                                               LParenLoc, ColonLoc, EndLoc);
1810   }
1811 
1812   /// Build a new OpenMP 'copyin' clause.
1813   ///
1814   /// By default, performs semantic analysis to build the new OpenMP clause.
1815   /// Subclasses may override this routine to provide different behavior.
1816   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1817                                     SourceLocation StartLoc,
1818                                     SourceLocation LParenLoc,
1819                                     SourceLocation EndLoc) {
1820     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1821                                              EndLoc);
1822   }
1823 
1824   /// Build a new OpenMP 'copyprivate' clause.
1825   ///
1826   /// By default, performs semantic analysis to build the new OpenMP clause.
1827   /// Subclasses may override this routine to provide different behavior.
1828   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1829                                          SourceLocation StartLoc,
1830                                          SourceLocation LParenLoc,
1831                                          SourceLocation EndLoc) {
1832     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1833                                                   EndLoc);
1834   }
1835 
1836   /// Build a new OpenMP 'flush' pseudo clause.
1837   ///
1838   /// By default, performs semantic analysis to build the new OpenMP clause.
1839   /// Subclasses may override this routine to provide different behavior.
1840   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1841                                    SourceLocation StartLoc,
1842                                    SourceLocation LParenLoc,
1843                                    SourceLocation EndLoc) {
1844     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1845                                             EndLoc);
1846   }
1847 
1848   /// Build a new OpenMP 'depobj' pseudo clause.
1849   ///
1850   /// By default, performs semantic analysis to build the new OpenMP clause.
1851   /// Subclasses may override this routine to provide different behavior.
1852   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1853                                     SourceLocation LParenLoc,
1854                                     SourceLocation EndLoc) {
1855     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1856                                              EndLoc);
1857   }
1858 
1859   /// Build a new OpenMP 'depend' pseudo clause.
1860   ///
1861   /// By default, performs semantic analysis to build the new OpenMP clause.
1862   /// Subclasses may override this routine to provide different behavior.
1863   OMPClause *
1864   RebuildOMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
1865                          SourceLocation DepLoc, SourceLocation ColonLoc,
1866                          ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1867                          SourceLocation LParenLoc, SourceLocation EndLoc) {
1868     return getSema().ActOnOpenMPDependClause(DepModifier, DepKind, DepLoc,
1869                                              ColonLoc, VarList, StartLoc,
1870                                              LParenLoc, EndLoc);
1871   }
1872 
1873   /// Build a new OpenMP 'device' clause.
1874   ///
1875   /// By default, performs semantic analysis to build the new statement.
1876   /// Subclasses may override this routine to provide different behavior.
1877   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1878                                     Expr *Device, SourceLocation StartLoc,
1879                                     SourceLocation LParenLoc,
1880                                     SourceLocation ModifierLoc,
1881                                     SourceLocation EndLoc) {
1882     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1883                                              LParenLoc, ModifierLoc, EndLoc);
1884   }
1885 
1886   /// Build a new OpenMP 'map' clause.
1887   ///
1888   /// By default, performs semantic analysis to build the new OpenMP clause.
1889   /// Subclasses may override this routine to provide different behavior.
1890   OMPClause *RebuildOMPMapClause(
1891       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1892       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1893       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1894       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1895       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1896       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1897     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1898                                           MapperIdScopeSpec, MapperId, MapType,
1899                                           IsMapTypeImplicit, MapLoc, ColonLoc,
1900                                           VarList, Locs, UnresolvedMappers);
1901   }
1902 
1903   /// Build a new OpenMP 'allocate' clause.
1904   ///
1905   /// By default, performs semantic analysis to build the new OpenMP clause.
1906   /// Subclasses may override this routine to provide different behavior.
1907   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1908                                       SourceLocation StartLoc,
1909                                       SourceLocation LParenLoc,
1910                                       SourceLocation ColonLoc,
1911                                       SourceLocation EndLoc) {
1912     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1913                                                LParenLoc, ColonLoc, EndLoc);
1914   }
1915 
1916   /// Build a new OpenMP 'num_teams' clause.
1917   ///
1918   /// By default, performs semantic analysis to build the new statement.
1919   /// Subclasses may override this routine to provide different behavior.
1920   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1921                                       SourceLocation LParenLoc,
1922                                       SourceLocation EndLoc) {
1923     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1924                                                EndLoc);
1925   }
1926 
1927   /// Build a new OpenMP 'thread_limit' clause.
1928   ///
1929   /// By default, performs semantic analysis to build the new statement.
1930   /// Subclasses may override this routine to provide different behavior.
1931   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1932                                          SourceLocation StartLoc,
1933                                          SourceLocation LParenLoc,
1934                                          SourceLocation EndLoc) {
1935     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1936                                                   LParenLoc, EndLoc);
1937   }
1938 
1939   /// Build a new OpenMP 'priority' clause.
1940   ///
1941   /// By default, performs semantic analysis to build the new statement.
1942   /// Subclasses may override this routine to provide different behavior.
1943   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1944                                       SourceLocation LParenLoc,
1945                                       SourceLocation EndLoc) {
1946     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1947                                                EndLoc);
1948   }
1949 
1950   /// Build a new OpenMP 'grainsize' clause.
1951   ///
1952   /// By default, performs semantic analysis to build the new statement.
1953   /// Subclasses may override this routine to provide different behavior.
1954   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1955                                        SourceLocation LParenLoc,
1956                                        SourceLocation EndLoc) {
1957     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1958                                                 EndLoc);
1959   }
1960 
1961   /// Build a new OpenMP 'num_tasks' clause.
1962   ///
1963   /// By default, performs semantic analysis to build the new statement.
1964   /// Subclasses may override this routine to provide different behavior.
1965   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1966                                       SourceLocation LParenLoc,
1967                                       SourceLocation EndLoc) {
1968     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1969                                                EndLoc);
1970   }
1971 
1972   /// Build a new OpenMP 'hint' clause.
1973   ///
1974   /// By default, performs semantic analysis to build the new statement.
1975   /// Subclasses may override this routine to provide different behavior.
1976   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1977                                   SourceLocation LParenLoc,
1978                                   SourceLocation EndLoc) {
1979     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1980   }
1981 
1982   /// Build a new OpenMP 'detach' clause.
1983   ///
1984   /// By default, performs semantic analysis to build the new statement.
1985   /// Subclasses may override this routine to provide different behavior.
1986   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
1987                                     SourceLocation LParenLoc,
1988                                     SourceLocation EndLoc) {
1989     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
1990   }
1991 
1992   /// Build a new OpenMP 'dist_schedule' clause.
1993   ///
1994   /// By default, performs semantic analysis to build the new OpenMP clause.
1995   /// Subclasses may override this routine to provide different behavior.
1996   OMPClause *
1997   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1998                                Expr *ChunkSize, SourceLocation StartLoc,
1999                                SourceLocation LParenLoc, SourceLocation KindLoc,
2000                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2001     return getSema().ActOnOpenMPDistScheduleClause(
2002         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2003   }
2004 
2005   /// Build a new OpenMP 'to' clause.
2006   ///
2007   /// By default, performs semantic analysis to build the new statement.
2008   /// Subclasses may override this routine to provide different behavior.
2009   OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
2010                                 CXXScopeSpec &MapperIdScopeSpec,
2011                                 DeclarationNameInfo &MapperId,
2012                                 const OMPVarListLocTy &Locs,
2013                                 ArrayRef<Expr *> UnresolvedMappers) {
2014     return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
2015                                          Locs, UnresolvedMappers);
2016   }
2017 
2018   /// Build a new OpenMP 'from' clause.
2019   ///
2020   /// By default, performs semantic analysis to build the new statement.
2021   /// Subclasses may override this routine to provide different behavior.
2022   OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
2023                                   CXXScopeSpec &MapperIdScopeSpec,
2024                                   DeclarationNameInfo &MapperId,
2025                                   const OMPVarListLocTy &Locs,
2026                                   ArrayRef<Expr *> UnresolvedMappers) {
2027     return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
2028                                            Locs, UnresolvedMappers);
2029   }
2030 
2031   /// Build a new OpenMP 'use_device_ptr' clause.
2032   ///
2033   /// By default, performs semantic analysis to build the new OpenMP clause.
2034   /// Subclasses may override this routine to provide different behavior.
2035   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2036                                           const OMPVarListLocTy &Locs) {
2037     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2038   }
2039 
2040   /// Build a new OpenMP 'use_device_addr' clause.
2041   ///
2042   /// By default, performs semantic analysis to build the new OpenMP clause.
2043   /// Subclasses may override this routine to provide different behavior.
2044   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2045                                            const OMPVarListLocTy &Locs) {
2046     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2047   }
2048 
2049   /// Build a new OpenMP 'is_device_ptr' clause.
2050   ///
2051   /// By default, performs semantic analysis to build the new OpenMP clause.
2052   /// Subclasses may override this routine to provide different behavior.
2053   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2054                                          const OMPVarListLocTy &Locs) {
2055     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2056   }
2057 
2058   /// Build a new OpenMP 'defaultmap' clause.
2059   ///
2060   /// By default, performs semantic analysis to build the new OpenMP clause.
2061   /// Subclasses may override this routine to provide different behavior.
2062   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2063                                         OpenMPDefaultmapClauseKind Kind,
2064                                         SourceLocation StartLoc,
2065                                         SourceLocation LParenLoc,
2066                                         SourceLocation MLoc,
2067                                         SourceLocation KindLoc,
2068                                         SourceLocation EndLoc) {
2069     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2070                                                  MLoc, KindLoc, EndLoc);
2071   }
2072 
2073   /// Build a new OpenMP 'nontemporal' clause.
2074   ///
2075   /// By default, performs semantic analysis to build the new OpenMP clause.
2076   /// Subclasses may override this routine to provide different behavior.
2077   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2078                                          SourceLocation StartLoc,
2079                                          SourceLocation LParenLoc,
2080                                          SourceLocation EndLoc) {
2081     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2082                                                   EndLoc);
2083   }
2084 
2085   /// Build a new OpenMP 'inclusive' clause.
2086   ///
2087   /// By default, performs semantic analysis to build the new OpenMP clause.
2088   /// Subclasses may override this routine to provide different behavior.
2089   OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2090                                        SourceLocation StartLoc,
2091                                        SourceLocation LParenLoc,
2092                                        SourceLocation EndLoc) {
2093     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2094                                                 EndLoc);
2095   }
2096 
2097   /// Build a new OpenMP 'exclusive' clause.
2098   ///
2099   /// By default, performs semantic analysis to build the new OpenMP clause.
2100   /// Subclasses may override this routine to provide different behavior.
2101   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2102                                        SourceLocation StartLoc,
2103                                        SourceLocation LParenLoc,
2104                                        SourceLocation EndLoc) {
2105     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2106                                                 EndLoc);
2107   }
2108 
2109   /// Build a new OpenMP 'uses_allocators' clause.
2110   ///
2111   /// By default, performs semantic analysis to build the new OpenMP clause.
2112   /// Subclasses may override this routine to provide different behavior.
2113   OMPClause *RebuildOMPUsesAllocatorsClause(
2114       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2115       SourceLocation LParenLoc, SourceLocation EndLoc) {
2116     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2117                                                     Data);
2118   }
2119 
2120   /// Build a new OpenMP 'affinity' clause.
2121   ///
2122   /// By default, performs semantic analysis to build the new OpenMP clause.
2123   /// Subclasses may override this routine to provide different behavior.
2124   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2125                                       SourceLocation LParenLoc,
2126                                       SourceLocation ColonLoc,
2127                                       SourceLocation EndLoc, Expr *Modifier,
2128                                       ArrayRef<Expr *> Locators) {
2129     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2130                                                EndLoc, Modifier, Locators);
2131   }
2132 
2133   /// Build a new OpenMP 'order' clause.
2134   ///
2135   /// By default, performs semantic analysis to build the new OpenMP clause.
2136   /// Subclasses may override this routine to provide different behavior.
2137   OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2138                                    SourceLocation KindKwLoc,
2139                                    SourceLocation StartLoc,
2140                                    SourceLocation LParenLoc,
2141                                    SourceLocation EndLoc) {
2142     return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2143                                             LParenLoc, EndLoc);
2144   }
2145 
2146   /// Rebuild the operand to an Objective-C \@synchronized statement.
2147   ///
2148   /// By default, performs semantic analysis to build the new statement.
2149   /// Subclasses may override this routine to provide different behavior.
2150   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2151                                               Expr *object) {
2152     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2153   }
2154 
2155   /// Build a new Objective-C \@synchronized statement.
2156   ///
2157   /// By default, performs semantic analysis to build the new statement.
2158   /// Subclasses may override this routine to provide different behavior.
2159   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2160                                            Expr *Object, Stmt *Body) {
2161     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2162   }
2163 
2164   /// Build a new Objective-C \@autoreleasepool statement.
2165   ///
2166   /// By default, performs semantic analysis to build the new statement.
2167   /// Subclasses may override this routine to provide different behavior.
2168   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2169                                             Stmt *Body) {
2170     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2171   }
2172 
2173   /// Build a new Objective-C fast enumeration statement.
2174   ///
2175   /// By default, performs semantic analysis to build the new statement.
2176   /// Subclasses may override this routine to provide different behavior.
2177   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2178                                           Stmt *Element,
2179                                           Expr *Collection,
2180                                           SourceLocation RParenLoc,
2181                                           Stmt *Body) {
2182     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2183                                                 Element,
2184                                                 Collection,
2185                                                 RParenLoc);
2186     if (ForEachStmt.isInvalid())
2187       return StmtError();
2188 
2189     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2190   }
2191 
2192   /// Build a new C++ exception declaration.
2193   ///
2194   /// By default, performs semantic analysis to build the new decaration.
2195   /// Subclasses may override this routine to provide different behavior.
2196   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2197                                 TypeSourceInfo *Declarator,
2198                                 SourceLocation StartLoc,
2199                                 SourceLocation IdLoc,
2200                                 IdentifierInfo *Id) {
2201     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2202                                                        StartLoc, IdLoc, Id);
2203     if (Var)
2204       getSema().CurContext->addDecl(Var);
2205     return Var;
2206   }
2207 
2208   /// Build a new C++ catch statement.
2209   ///
2210   /// By default, performs semantic analysis to build the new statement.
2211   /// Subclasses may override this routine to provide different behavior.
2212   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2213                                  VarDecl *ExceptionDecl,
2214                                  Stmt *Handler) {
2215     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2216                                                       Handler));
2217   }
2218 
2219   /// Build a new C++ try statement.
2220   ///
2221   /// By default, performs semantic analysis to build the new statement.
2222   /// Subclasses may override this routine to provide different behavior.
2223   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2224                                ArrayRef<Stmt *> Handlers) {
2225     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2226   }
2227 
2228   /// Build a new C++0x range-based for statement.
2229   ///
2230   /// By default, performs semantic analysis to build the new statement.
2231   /// Subclasses may override this routine to provide different behavior.
2232   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2233                                     SourceLocation CoawaitLoc, Stmt *Init,
2234                                     SourceLocation ColonLoc, Stmt *Range,
2235                                     Stmt *Begin, Stmt *End, Expr *Cond,
2236                                     Expr *Inc, Stmt *LoopVar,
2237                                     SourceLocation RParenLoc) {
2238     // If we've just learned that the range is actually an Objective-C
2239     // collection, treat this as an Objective-C fast enumeration loop.
2240     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2241       if (RangeStmt->isSingleDecl()) {
2242         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2243           if (RangeVar->isInvalidDecl())
2244             return StmtError();
2245 
2246           Expr *RangeExpr = RangeVar->getInit();
2247           if (!RangeExpr->isTypeDependent() &&
2248               RangeExpr->getType()->isObjCObjectPointerType()) {
2249             // FIXME: Support init-statements in Objective-C++20 ranged for
2250             // statement.
2251             if (Init) {
2252               return SemaRef.Diag(Init->getBeginLoc(),
2253                                   diag::err_objc_for_range_init_stmt)
2254                          << Init->getSourceRange();
2255             }
2256             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2257                                                         RangeExpr, RParenLoc);
2258           }
2259         }
2260       }
2261     }
2262 
2263     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2264                                           Range, Begin, End, Cond, Inc, LoopVar,
2265                                           RParenLoc, Sema::BFRK_Rebuild);
2266   }
2267 
2268   /// Build a new C++0x range-based for statement.
2269   ///
2270   /// By default, performs semantic analysis to build the new statement.
2271   /// Subclasses may override this routine to provide different behavior.
2272   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2273                                           bool IsIfExists,
2274                                           NestedNameSpecifierLoc QualifierLoc,
2275                                           DeclarationNameInfo NameInfo,
2276                                           Stmt *Nested) {
2277     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2278                                                 QualifierLoc, NameInfo, Nested);
2279   }
2280 
2281   /// Attach body to a C++0x range-based for statement.
2282   ///
2283   /// By default, performs semantic analysis to finish the new statement.
2284   /// Subclasses may override this routine to provide different behavior.
2285   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2286     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2287   }
2288 
2289   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2290                                Stmt *TryBlock, Stmt *Handler) {
2291     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2292   }
2293 
2294   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2295                                   Stmt *Block) {
2296     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2297   }
2298 
2299   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2300     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2301   }
2302 
2303   /// Build a new predefined expression.
2304   ///
2305   /// By default, performs semantic analysis to build the new expression.
2306   /// Subclasses may override this routine to provide different behavior.
2307   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2308                                    PredefinedExpr::IdentKind IK) {
2309     return getSema().BuildPredefinedExpr(Loc, IK);
2310   }
2311 
2312   /// Build a new expression that references a declaration.
2313   ///
2314   /// By default, performs semantic analysis to build the new expression.
2315   /// Subclasses may override this routine to provide different behavior.
2316   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2317                                         LookupResult &R,
2318                                         bool RequiresADL) {
2319     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2320   }
2321 
2322 
2323   /// Build a new expression that references a declaration.
2324   ///
2325   /// By default, performs semantic analysis to build the new expression.
2326   /// Subclasses may override this routine to provide different behavior.
2327   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2328                                 ValueDecl *VD,
2329                                 const DeclarationNameInfo &NameInfo,
2330                                 NamedDecl *Found,
2331                                 TemplateArgumentListInfo *TemplateArgs) {
2332     CXXScopeSpec SS;
2333     SS.Adopt(QualifierLoc);
2334     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2335                                               TemplateArgs);
2336   }
2337 
2338   /// Build a new expression in parentheses.
2339   ///
2340   /// By default, performs semantic analysis to build the new expression.
2341   /// Subclasses may override this routine to provide different behavior.
2342   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2343                                     SourceLocation RParen) {
2344     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2345   }
2346 
2347   /// Build a new pseudo-destructor expression.
2348   ///
2349   /// By default, performs semantic analysis to build the new expression.
2350   /// Subclasses may override this routine to provide different behavior.
2351   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2352                                             SourceLocation OperatorLoc,
2353                                             bool isArrow,
2354                                             CXXScopeSpec &SS,
2355                                             TypeSourceInfo *ScopeType,
2356                                             SourceLocation CCLoc,
2357                                             SourceLocation TildeLoc,
2358                                         PseudoDestructorTypeStorage Destroyed);
2359 
2360   /// Build a new unary operator expression.
2361   ///
2362   /// By default, performs semantic analysis to build the new expression.
2363   /// Subclasses may override this routine to provide different behavior.
2364   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2365                                         UnaryOperatorKind Opc,
2366                                         Expr *SubExpr) {
2367     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2368   }
2369 
2370   /// Build a new builtin offsetof expression.
2371   ///
2372   /// By default, performs semantic analysis to build the new expression.
2373   /// Subclasses may override this routine to provide different behavior.
2374   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2375                                  TypeSourceInfo *Type,
2376                                  ArrayRef<Sema::OffsetOfComponent> Components,
2377                                  SourceLocation RParenLoc) {
2378     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2379                                           RParenLoc);
2380   }
2381 
2382   /// Build a new sizeof, alignof or vec_step expression with a
2383   /// type argument.
2384   ///
2385   /// By default, performs semantic analysis to build the new expression.
2386   /// Subclasses may override this routine to provide different behavior.
2387   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2388                                          SourceLocation OpLoc,
2389                                          UnaryExprOrTypeTrait ExprKind,
2390                                          SourceRange R) {
2391     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2392   }
2393 
2394   /// Build a new sizeof, alignof or vec step expression with an
2395   /// expression argument.
2396   ///
2397   /// By default, performs semantic analysis to build the new expression.
2398   /// Subclasses may override this routine to provide different behavior.
2399   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2400                                          UnaryExprOrTypeTrait ExprKind,
2401                                          SourceRange R) {
2402     ExprResult Result
2403       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2404     if (Result.isInvalid())
2405       return ExprError();
2406 
2407     return Result;
2408   }
2409 
2410   /// Build a new array subscript expression.
2411   ///
2412   /// By default, performs semantic analysis to build the new expression.
2413   /// Subclasses may override this routine to provide different behavior.
2414   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2415                                              SourceLocation LBracketLoc,
2416                                              Expr *RHS,
2417                                              SourceLocation RBracketLoc) {
2418     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2419                                              LBracketLoc, RHS,
2420                                              RBracketLoc);
2421   }
2422 
2423   /// Build a new matrix subscript expression.
2424   ///
2425   /// By default, performs semantic analysis to build the new expression.
2426   /// Subclasses may override this routine to provide different behavior.
2427   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2428                                         Expr *ColumnIdx,
2429                                         SourceLocation RBracketLoc) {
2430     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2431                                                       RBracketLoc);
2432   }
2433 
2434   /// Build a new array section expression.
2435   ///
2436   /// By default, performs semantic analysis to build the new expression.
2437   /// Subclasses may override this routine to provide different behavior.
2438   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2439                                         Expr *LowerBound,
2440                                         SourceLocation ColonLocFirst,
2441                                         SourceLocation ColonLocSecond,
2442                                         Expr *Length, Expr *Stride,
2443                                         SourceLocation RBracketLoc) {
2444     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2445                                               ColonLocFirst, ColonLocSecond,
2446                                               Length, Stride, RBracketLoc);
2447   }
2448 
2449   /// Build a new array shaping expression.
2450   ///
2451   /// By default, performs semantic analysis to build the new expression.
2452   /// Subclasses may override this routine to provide different behavior.
2453   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2454                                         SourceLocation RParenLoc,
2455                                         ArrayRef<Expr *> Dims,
2456                                         ArrayRef<SourceRange> BracketsRanges) {
2457     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2458                                               BracketsRanges);
2459   }
2460 
2461   /// Build a new iterator expression.
2462   ///
2463   /// By default, performs semantic analysis to build the new expression.
2464   /// Subclasses may override this routine to provide different behavior.
2465   ExprResult RebuildOMPIteratorExpr(
2466       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2467       ArrayRef<Sema::OMPIteratorData> Data) {
2468     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2469                                           LLoc, RLoc, Data);
2470   }
2471 
2472   /// Build a new call expression.
2473   ///
2474   /// By default, performs semantic analysis to build the new expression.
2475   /// Subclasses may override this routine to provide different behavior.
2476   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2477                                    MultiExprArg Args,
2478                                    SourceLocation RParenLoc,
2479                                    Expr *ExecConfig = nullptr) {
2480     return getSema().ActOnCallExpr(
2481         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2482   }
2483 
2484   /// Build a new member access expression.
2485   ///
2486   /// By default, performs semantic analysis to build the new expression.
2487   /// Subclasses may override this routine to provide different behavior.
2488   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2489                                bool isArrow,
2490                                NestedNameSpecifierLoc QualifierLoc,
2491                                SourceLocation TemplateKWLoc,
2492                                const DeclarationNameInfo &MemberNameInfo,
2493                                ValueDecl *Member,
2494                                NamedDecl *FoundDecl,
2495                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2496                                NamedDecl *FirstQualifierInScope) {
2497     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2498                                                                       isArrow);
2499     if (!Member->getDeclName()) {
2500       // We have a reference to an unnamed field.  This is always the
2501       // base of an anonymous struct/union member access, i.e. the
2502       // field is always of record type.
2503       assert(Member->getType()->isRecordType() &&
2504              "unnamed member not of record type?");
2505 
2506       BaseResult =
2507         getSema().PerformObjectMemberConversion(BaseResult.get(),
2508                                                 QualifierLoc.getNestedNameSpecifier(),
2509                                                 FoundDecl, Member);
2510       if (BaseResult.isInvalid())
2511         return ExprError();
2512       Base = BaseResult.get();
2513 
2514       CXXScopeSpec EmptySS;
2515       return getSema().BuildFieldReferenceExpr(
2516           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2517           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2518     }
2519 
2520     CXXScopeSpec SS;
2521     SS.Adopt(QualifierLoc);
2522 
2523     Base = BaseResult.get();
2524     QualType BaseType = Base->getType();
2525 
2526     if (isArrow && !BaseType->isPointerType())
2527       return ExprError();
2528 
2529     // FIXME: this involves duplicating earlier analysis in a lot of
2530     // cases; we should avoid this when possible.
2531     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2532     R.addDecl(FoundDecl);
2533     R.resolveKind();
2534 
2535     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2536                                               SS, TemplateKWLoc,
2537                                               FirstQualifierInScope,
2538                                               R, ExplicitTemplateArgs,
2539                                               /*S*/nullptr);
2540   }
2541 
2542   /// Build a new binary operator expression.
2543   ///
2544   /// By default, performs semantic analysis to build the new expression.
2545   /// Subclasses may override this routine to provide different behavior.
2546   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2547                                          BinaryOperatorKind Opc,
2548                                          Expr *LHS, Expr *RHS) {
2549     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2550   }
2551 
2552   /// Build a new rewritten operator expression.
2553   ///
2554   /// By default, performs semantic analysis to build the new expression.
2555   /// Subclasses may override this routine to provide different behavior.
2556   ExprResult RebuildCXXRewrittenBinaryOperator(
2557       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2558       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2559     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2560                                            RHS, /*RequiresADL*/false);
2561   }
2562 
2563   /// Build a new conditional operator expression.
2564   ///
2565   /// By default, performs semantic analysis to build the new expression.
2566   /// Subclasses may override this routine to provide different behavior.
2567   ExprResult RebuildConditionalOperator(Expr *Cond,
2568                                         SourceLocation QuestionLoc,
2569                                         Expr *LHS,
2570                                         SourceLocation ColonLoc,
2571                                         Expr *RHS) {
2572     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2573                                         LHS, RHS);
2574   }
2575 
2576   /// Build a new C-style cast expression.
2577   ///
2578   /// By default, performs semantic analysis to build the new expression.
2579   /// Subclasses may override this routine to provide different behavior.
2580   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2581                                          TypeSourceInfo *TInfo,
2582                                          SourceLocation RParenLoc,
2583                                          Expr *SubExpr) {
2584     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2585                                          SubExpr);
2586   }
2587 
2588   /// Build a new compound literal expression.
2589   ///
2590   /// By default, performs semantic analysis to build the new expression.
2591   /// Subclasses may override this routine to provide different behavior.
2592   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2593                                               TypeSourceInfo *TInfo,
2594                                               SourceLocation RParenLoc,
2595                                               Expr *Init) {
2596     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2597                                               Init);
2598   }
2599 
2600   /// Build a new extended vector element access expression.
2601   ///
2602   /// By default, performs semantic analysis to build the new expression.
2603   /// Subclasses may override this routine to provide different behavior.
2604   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2605                                                SourceLocation OpLoc,
2606                                                SourceLocation AccessorLoc,
2607                                                IdentifierInfo &Accessor) {
2608 
2609     CXXScopeSpec SS;
2610     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2611     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2612                                               OpLoc, /*IsArrow*/ false,
2613                                               SS, SourceLocation(),
2614                                               /*FirstQualifierInScope*/ nullptr,
2615                                               NameInfo,
2616                                               /* TemplateArgs */ nullptr,
2617                                               /*S*/ nullptr);
2618   }
2619 
2620   /// Build a new initializer list 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 RebuildInitList(SourceLocation LBraceLoc,
2625                              MultiExprArg Inits,
2626                              SourceLocation RBraceLoc) {
2627     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2628   }
2629 
2630   /// Build a new designated initializer expression.
2631   ///
2632   /// By default, performs semantic analysis to build the new expression.
2633   /// Subclasses may override this routine to provide different behavior.
2634   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2635                                              MultiExprArg ArrayExprs,
2636                                              SourceLocation EqualOrColonLoc,
2637                                              bool GNUSyntax,
2638                                              Expr *Init) {
2639     ExprResult Result
2640       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2641                                            Init);
2642     if (Result.isInvalid())
2643       return ExprError();
2644 
2645     return Result;
2646   }
2647 
2648   /// Build a new value-initialized expression.
2649   ///
2650   /// By default, builds the implicit value initialization without performing
2651   /// any semantic analysis. Subclasses may override this routine to provide
2652   /// different behavior.
2653   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2654     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2655   }
2656 
2657   /// Build a new \c va_arg expression.
2658   ///
2659   /// By default, performs semantic analysis to build the new expression.
2660   /// Subclasses may override this routine to provide different behavior.
2661   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2662                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2663                                     SourceLocation RParenLoc) {
2664     return getSema().BuildVAArgExpr(BuiltinLoc,
2665                                     SubExpr, TInfo,
2666                                     RParenLoc);
2667   }
2668 
2669   /// Build a new expression list in parentheses.
2670   ///
2671   /// By default, performs semantic analysis to build the new expression.
2672   /// Subclasses may override this routine to provide different behavior.
2673   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2674                                   MultiExprArg SubExprs,
2675                                   SourceLocation RParenLoc) {
2676     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2677   }
2678 
2679   /// Build a new address-of-label expression.
2680   ///
2681   /// By default, performs semantic analysis, using the name of the label
2682   /// rather than attempting to map the label statement itself.
2683   /// Subclasses may override this routine to provide different behavior.
2684   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2685                                   SourceLocation LabelLoc, LabelDecl *Label) {
2686     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2687   }
2688 
2689   /// Build a new GNU statement expression.
2690   ///
2691   /// By default, performs semantic analysis to build the new expression.
2692   /// Subclasses may override this routine to provide different behavior.
2693   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2694                              SourceLocation RParenLoc, unsigned TemplateDepth) {
2695     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2696                                    TemplateDepth);
2697   }
2698 
2699   /// Build a new __builtin_choose_expr expression.
2700   ///
2701   /// By default, performs semantic analysis to build the new expression.
2702   /// Subclasses may override this routine to provide different behavior.
2703   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2704                                      Expr *Cond, Expr *LHS, Expr *RHS,
2705                                      SourceLocation RParenLoc) {
2706     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2707                                    Cond, LHS, RHS,
2708                                    RParenLoc);
2709   }
2710 
2711   /// Build a new generic selection 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 RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2716                                          SourceLocation DefaultLoc,
2717                                          SourceLocation RParenLoc,
2718                                          Expr *ControllingExpr,
2719                                          ArrayRef<TypeSourceInfo *> Types,
2720                                          ArrayRef<Expr *> Exprs) {
2721     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2722                                                 ControllingExpr, Types, Exprs);
2723   }
2724 
2725   /// Build a new overloaded operator call expression.
2726   ///
2727   /// By default, performs semantic analysis to build the new expression.
2728   /// The semantic analysis provides the behavior of template instantiation,
2729   /// copying with transformations that turn what looks like an overloaded
2730   /// operator call into a use of a builtin operator, performing
2731   /// argument-dependent lookup, etc. Subclasses may override this routine to
2732   /// provide different behavior.
2733   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2734                                               SourceLocation OpLoc,
2735                                               Expr *Callee,
2736                                               Expr *First,
2737                                               Expr *Second);
2738 
2739   /// Build a new C++ "named" cast expression, such as static_cast or
2740   /// reinterpret_cast.
2741   ///
2742   /// By default, this routine dispatches to one of the more-specific routines
2743   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2744   /// Subclasses may override this routine to provide different behavior.
2745   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2746                                            Stmt::StmtClass Class,
2747                                            SourceLocation LAngleLoc,
2748                                            TypeSourceInfo *TInfo,
2749                                            SourceLocation RAngleLoc,
2750                                            SourceLocation LParenLoc,
2751                                            Expr *SubExpr,
2752                                            SourceLocation RParenLoc) {
2753     switch (Class) {
2754     case Stmt::CXXStaticCastExprClass:
2755       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2756                                                    RAngleLoc, LParenLoc,
2757                                                    SubExpr, RParenLoc);
2758 
2759     case Stmt::CXXDynamicCastExprClass:
2760       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2761                                                     RAngleLoc, LParenLoc,
2762                                                     SubExpr, RParenLoc);
2763 
2764     case Stmt::CXXReinterpretCastExprClass:
2765       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2766                                                         RAngleLoc, LParenLoc,
2767                                                         SubExpr,
2768                                                         RParenLoc);
2769 
2770     case Stmt::CXXConstCastExprClass:
2771       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2772                                                    RAngleLoc, LParenLoc,
2773                                                    SubExpr, RParenLoc);
2774 
2775     case Stmt::CXXAddrspaceCastExprClass:
2776       return getDerived().RebuildCXXAddrspaceCastExpr(
2777           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
2778 
2779     default:
2780       llvm_unreachable("Invalid C++ named cast");
2781     }
2782   }
2783 
2784   /// Build a new C++ static_cast expression.
2785   ///
2786   /// By default, performs semantic analysis to build the new expression.
2787   /// Subclasses may override this routine to provide different behavior.
2788   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2789                                             SourceLocation LAngleLoc,
2790                                             TypeSourceInfo *TInfo,
2791                                             SourceLocation RAngleLoc,
2792                                             SourceLocation LParenLoc,
2793                                             Expr *SubExpr,
2794                                             SourceLocation RParenLoc) {
2795     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2796                                        TInfo, SubExpr,
2797                                        SourceRange(LAngleLoc, RAngleLoc),
2798                                        SourceRange(LParenLoc, RParenLoc));
2799   }
2800 
2801   /// Build a new C++ dynamic_cast expression.
2802   ///
2803   /// By default, performs semantic analysis to build the new expression.
2804   /// Subclasses may override this routine to provide different behavior.
2805   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2806                                              SourceLocation LAngleLoc,
2807                                              TypeSourceInfo *TInfo,
2808                                              SourceLocation RAngleLoc,
2809                                              SourceLocation LParenLoc,
2810                                              Expr *SubExpr,
2811                                              SourceLocation RParenLoc) {
2812     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2813                                        TInfo, SubExpr,
2814                                        SourceRange(LAngleLoc, RAngleLoc),
2815                                        SourceRange(LParenLoc, RParenLoc));
2816   }
2817 
2818   /// Build a new C++ reinterpret_cast expression.
2819   ///
2820   /// By default, performs semantic analysis to build the new expression.
2821   /// Subclasses may override this routine to provide different behavior.
2822   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2823                                                  SourceLocation LAngleLoc,
2824                                                  TypeSourceInfo *TInfo,
2825                                                  SourceLocation RAngleLoc,
2826                                                  SourceLocation LParenLoc,
2827                                                  Expr *SubExpr,
2828                                                  SourceLocation RParenLoc) {
2829     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2830                                        TInfo, SubExpr,
2831                                        SourceRange(LAngleLoc, RAngleLoc),
2832                                        SourceRange(LParenLoc, RParenLoc));
2833   }
2834 
2835   /// Build a new C++ const_cast expression.
2836   ///
2837   /// By default, performs semantic analysis to build the new expression.
2838   /// Subclasses may override this routine to provide different behavior.
2839   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2840                                            SourceLocation LAngleLoc,
2841                                            TypeSourceInfo *TInfo,
2842                                            SourceLocation RAngleLoc,
2843                                            SourceLocation LParenLoc,
2844                                            Expr *SubExpr,
2845                                            SourceLocation RParenLoc) {
2846     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2847                                        TInfo, SubExpr,
2848                                        SourceRange(LAngleLoc, RAngleLoc),
2849                                        SourceRange(LParenLoc, RParenLoc));
2850   }
2851 
2852   ExprResult
2853   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
2854                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
2855                               SourceLocation LParenLoc, Expr *SubExpr,
2856                               SourceLocation RParenLoc) {
2857     return getSema().BuildCXXNamedCast(
2858         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
2859         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
2860   }
2861 
2862   /// Build a new C++ functional-style cast expression.
2863   ///
2864   /// By default, performs semantic analysis to build the new expression.
2865   /// Subclasses may override this routine to provide different behavior.
2866   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2867                                           SourceLocation LParenLoc,
2868                                           Expr *Sub,
2869                                           SourceLocation RParenLoc,
2870                                           bool ListInitialization) {
2871     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2872                                                MultiExprArg(&Sub, 1), RParenLoc,
2873                                                ListInitialization);
2874   }
2875 
2876   /// Build a new C++ __builtin_bit_cast expression.
2877   ///
2878   /// By default, performs semantic analysis to build the new expression.
2879   /// Subclasses may override this routine to provide different behavior.
2880   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2881                                        TypeSourceInfo *TSI, Expr *Sub,
2882                                        SourceLocation RParenLoc) {
2883     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2884   }
2885 
2886   /// Build a new C++ typeid(type) expression.
2887   ///
2888   /// By default, performs semantic analysis to build the new expression.
2889   /// Subclasses may override this routine to provide different behavior.
2890   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2891                                         SourceLocation TypeidLoc,
2892                                         TypeSourceInfo *Operand,
2893                                         SourceLocation RParenLoc) {
2894     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2895                                     RParenLoc);
2896   }
2897 
2898 
2899   /// Build a new C++ typeid(expr) expression.
2900   ///
2901   /// By default, performs semantic analysis to build the new expression.
2902   /// Subclasses may override this routine to provide different behavior.
2903   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2904                                         SourceLocation TypeidLoc,
2905                                         Expr *Operand,
2906                                         SourceLocation RParenLoc) {
2907     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2908                                     RParenLoc);
2909   }
2910 
2911   /// Build a new C++ __uuidof(type) expression.
2912   ///
2913   /// By default, performs semantic analysis to build the new expression.
2914   /// Subclasses may override this routine to provide different behavior.
2915   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
2916                                   TypeSourceInfo *Operand,
2917                                   SourceLocation RParenLoc) {
2918     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
2919   }
2920 
2921   /// Build a new C++ __uuidof(expr) expression.
2922   ///
2923   /// By default, performs semantic analysis to build the new expression.
2924   /// Subclasses may override this routine to provide different behavior.
2925   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
2926                                   Expr *Operand, SourceLocation RParenLoc) {
2927     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
2928   }
2929 
2930   /// Build a new C++ "this" expression.
2931   ///
2932   /// By default, builds a new "this" expression without performing any
2933   /// semantic analysis. Subclasses may override this routine to provide
2934   /// different behavior.
2935   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2936                                 QualType ThisType,
2937                                 bool isImplicit) {
2938     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2939   }
2940 
2941   /// Build a new C++ throw expression.
2942   ///
2943   /// By default, performs semantic analysis to build the new expression.
2944   /// Subclasses may override this routine to provide different behavior.
2945   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2946                                  bool IsThrownVariableInScope) {
2947     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2948   }
2949 
2950   /// Build a new C++ default-argument expression.
2951   ///
2952   /// By default, builds a new default-argument expression, which does not
2953   /// require any semantic analysis. Subclasses may override this routine to
2954   /// provide different behavior.
2955   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2956     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2957                                      getSema().CurContext);
2958   }
2959 
2960   /// Build a new C++11 default-initialization expression.
2961   ///
2962   /// By default, builds a new default field initialization expression, which
2963   /// does not require any semantic analysis. Subclasses may override this
2964   /// routine to provide different behavior.
2965   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2966                                        FieldDecl *Field) {
2967     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2968                                       getSema().CurContext);
2969   }
2970 
2971   /// Build a new C++ zero-initialization expression.
2972   ///
2973   /// By default, performs semantic analysis to build the new expression.
2974   /// Subclasses may override this routine to provide different behavior.
2975   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2976                                            SourceLocation LParenLoc,
2977                                            SourceLocation RParenLoc) {
2978     return getSema().BuildCXXTypeConstructExpr(
2979         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2980   }
2981 
2982   /// Build a new C++ "new" expression.
2983   ///
2984   /// By default, performs semantic analysis to build the new expression.
2985   /// Subclasses may override this routine to provide different behavior.
2986   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2987                                bool UseGlobal,
2988                                SourceLocation PlacementLParen,
2989                                MultiExprArg PlacementArgs,
2990                                SourceLocation PlacementRParen,
2991                                SourceRange TypeIdParens,
2992                                QualType AllocatedType,
2993                                TypeSourceInfo *AllocatedTypeInfo,
2994                                Optional<Expr *> ArraySize,
2995                                SourceRange DirectInitRange,
2996                                Expr *Initializer) {
2997     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2998                                  PlacementLParen,
2999                                  PlacementArgs,
3000                                  PlacementRParen,
3001                                  TypeIdParens,
3002                                  AllocatedType,
3003                                  AllocatedTypeInfo,
3004                                  ArraySize,
3005                                  DirectInitRange,
3006                                  Initializer);
3007   }
3008 
3009   /// Build a new C++ "delete" expression.
3010   ///
3011   /// By default, performs semantic analysis to build the new expression.
3012   /// Subclasses may override this routine to provide different behavior.
3013   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3014                                         bool IsGlobalDelete,
3015                                         bool IsArrayForm,
3016                                         Expr *Operand) {
3017     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3018                                     Operand);
3019   }
3020 
3021   /// Build a new type trait expression.
3022   ///
3023   /// By default, performs semantic analysis to build the new expression.
3024   /// Subclasses may override this routine to provide different behavior.
3025   ExprResult RebuildTypeTrait(TypeTrait Trait,
3026                               SourceLocation StartLoc,
3027                               ArrayRef<TypeSourceInfo *> Args,
3028                               SourceLocation RParenLoc) {
3029     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3030   }
3031 
3032   /// Build a new array type trait expression.
3033   ///
3034   /// By default, performs semantic analysis to build the new expression.
3035   /// Subclasses may override this routine to provide different behavior.
3036   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3037                                    SourceLocation StartLoc,
3038                                    TypeSourceInfo *TSInfo,
3039                                    Expr *DimExpr,
3040                                    SourceLocation RParenLoc) {
3041     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3042   }
3043 
3044   /// Build a new expression trait expression.
3045   ///
3046   /// By default, performs semantic analysis to build the new expression.
3047   /// Subclasses may override this routine to provide different behavior.
3048   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3049                                    SourceLocation StartLoc,
3050                                    Expr *Queried,
3051                                    SourceLocation RParenLoc) {
3052     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3053   }
3054 
3055   /// Build a new (previously unresolved) declaration reference
3056   /// expression.
3057   ///
3058   /// By default, performs semantic analysis to build the new expression.
3059   /// Subclasses may override this routine to provide different behavior.
3060   ExprResult RebuildDependentScopeDeclRefExpr(
3061                                           NestedNameSpecifierLoc QualifierLoc,
3062                                           SourceLocation TemplateKWLoc,
3063                                        const DeclarationNameInfo &NameInfo,
3064                               const TemplateArgumentListInfo *TemplateArgs,
3065                                           bool IsAddressOfOperand,
3066                                           TypeSourceInfo **RecoveryTSI) {
3067     CXXScopeSpec SS;
3068     SS.Adopt(QualifierLoc);
3069 
3070     if (TemplateArgs || TemplateKWLoc.isValid())
3071       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3072                                                     TemplateArgs);
3073 
3074     return getSema().BuildQualifiedDeclarationNameExpr(
3075         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3076   }
3077 
3078   /// Build a new template-id expression.
3079   ///
3080   /// By default, performs semantic analysis to build the new expression.
3081   /// Subclasses may override this routine to provide different behavior.
3082   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3083                                    SourceLocation TemplateKWLoc,
3084                                    LookupResult &R,
3085                                    bool RequiresADL,
3086                               const TemplateArgumentListInfo *TemplateArgs) {
3087     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3088                                          TemplateArgs);
3089   }
3090 
3091   /// Build a new object-construction expression.
3092   ///
3093   /// By default, performs semantic analysis to build the new expression.
3094   /// Subclasses may override this routine to provide different behavior.
3095   ExprResult RebuildCXXConstructExpr(QualType T,
3096                                      SourceLocation Loc,
3097                                      CXXConstructorDecl *Constructor,
3098                                      bool IsElidable,
3099                                      MultiExprArg Args,
3100                                      bool HadMultipleCandidates,
3101                                      bool ListInitialization,
3102                                      bool StdInitListInitialization,
3103                                      bool RequiresZeroInit,
3104                              CXXConstructExpr::ConstructionKind ConstructKind,
3105                                      SourceRange ParenRange) {
3106     // Reconstruct the constructor we originally found, which might be
3107     // different if this is a call to an inherited constructor.
3108     CXXConstructorDecl *FoundCtor = Constructor;
3109     if (Constructor->isInheritingConstructor())
3110       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3111 
3112     SmallVector<Expr*, 8> ConvertedArgs;
3113     if (getSema().CompleteConstructorCall(FoundCtor, Args, Loc, ConvertedArgs))
3114       return ExprError();
3115 
3116     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3117                                            IsElidable,
3118                                            ConvertedArgs,
3119                                            HadMultipleCandidates,
3120                                            ListInitialization,
3121                                            StdInitListInitialization,
3122                                            RequiresZeroInit, ConstructKind,
3123                                            ParenRange);
3124   }
3125 
3126   /// Build a new implicit construction via inherited constructor
3127   /// expression.
3128   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3129                                              CXXConstructorDecl *Constructor,
3130                                              bool ConstructsVBase,
3131                                              bool InheritedFromVBase) {
3132     return new (getSema().Context) CXXInheritedCtorInitExpr(
3133         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3134   }
3135 
3136   /// Build a new object-construction expression.
3137   ///
3138   /// By default, performs semantic analysis to build the new expression.
3139   /// Subclasses may override this routine to provide different behavior.
3140   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3141                                            SourceLocation LParenOrBraceLoc,
3142                                            MultiExprArg Args,
3143                                            SourceLocation RParenOrBraceLoc,
3144                                            bool ListInitialization) {
3145     return getSema().BuildCXXTypeConstructExpr(
3146         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3147   }
3148 
3149   /// Build a new object-construction expression.
3150   ///
3151   /// By default, performs semantic analysis to build the new expression.
3152   /// Subclasses may override this routine to provide different behavior.
3153   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3154                                                SourceLocation LParenLoc,
3155                                                MultiExprArg Args,
3156                                                SourceLocation RParenLoc,
3157                                                bool ListInitialization) {
3158     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3159                                                RParenLoc, ListInitialization);
3160   }
3161 
3162   /// Build a new member reference expression.
3163   ///
3164   /// By default, performs semantic analysis to build the new expression.
3165   /// Subclasses may override this routine to provide different behavior.
3166   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3167                                                 QualType BaseType,
3168                                                 bool IsArrow,
3169                                                 SourceLocation OperatorLoc,
3170                                           NestedNameSpecifierLoc QualifierLoc,
3171                                                 SourceLocation TemplateKWLoc,
3172                                             NamedDecl *FirstQualifierInScope,
3173                                    const DeclarationNameInfo &MemberNameInfo,
3174                               const TemplateArgumentListInfo *TemplateArgs) {
3175     CXXScopeSpec SS;
3176     SS.Adopt(QualifierLoc);
3177 
3178     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3179                                             OperatorLoc, IsArrow,
3180                                             SS, TemplateKWLoc,
3181                                             FirstQualifierInScope,
3182                                             MemberNameInfo,
3183                                             TemplateArgs, /*S*/nullptr);
3184   }
3185 
3186   /// Build a new member reference expression.
3187   ///
3188   /// By default, performs semantic analysis to build the new expression.
3189   /// Subclasses may override this routine to provide different behavior.
3190   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3191                                          SourceLocation OperatorLoc,
3192                                          bool IsArrow,
3193                                          NestedNameSpecifierLoc QualifierLoc,
3194                                          SourceLocation TemplateKWLoc,
3195                                          NamedDecl *FirstQualifierInScope,
3196                                          LookupResult &R,
3197                                 const TemplateArgumentListInfo *TemplateArgs) {
3198     CXXScopeSpec SS;
3199     SS.Adopt(QualifierLoc);
3200 
3201     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3202                                             OperatorLoc, IsArrow,
3203                                             SS, TemplateKWLoc,
3204                                             FirstQualifierInScope,
3205                                             R, TemplateArgs, /*S*/nullptr);
3206   }
3207 
3208   /// Build a new noexcept expression.
3209   ///
3210   /// By default, performs semantic analysis to build the new expression.
3211   /// Subclasses may override this routine to provide different behavior.
3212   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3213     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3214   }
3215 
3216   /// Build a new expression to compute the length of a parameter pack.
3217   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3218                                    NamedDecl *Pack,
3219                                    SourceLocation PackLoc,
3220                                    SourceLocation RParenLoc,
3221                                    Optional<unsigned> Length,
3222                                    ArrayRef<TemplateArgument> PartialArgs) {
3223     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3224                                   RParenLoc, Length, PartialArgs);
3225   }
3226 
3227   /// Build a new expression representing a call to a source location
3228   ///  builtin.
3229   ///
3230   /// By default, performs semantic analysis to build the new expression.
3231   /// Subclasses may override this routine to provide different behavior.
3232   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3233                                   SourceLocation BuiltinLoc,
3234                                   SourceLocation RPLoc,
3235                                   DeclContext *ParentContext) {
3236     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3237   }
3238 
3239   /// Build a new Objective-C boxed 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 RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3244       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3245       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3246       TemplateArgumentListInfo *TALI) {
3247     CXXScopeSpec SS;
3248     SS.Adopt(NNS);
3249     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3250                                                          ConceptNameInfo,
3251                                                          FoundDecl,
3252                                                          NamedConcept, TALI);
3253     if (Result.isInvalid())
3254       return ExprError();
3255     return Result;
3256   }
3257 
3258   /// \brief Build a new requires expression.
3259   ///
3260   /// By default, performs semantic analysis to build the new expression.
3261   /// Subclasses may override this routine to provide different behavior.
3262   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3263                                  RequiresExprBodyDecl *Body,
3264                                  ArrayRef<ParmVarDecl *> LocalParameters,
3265                                  ArrayRef<concepts::Requirement *> Requirements,
3266                                  SourceLocation ClosingBraceLoc) {
3267     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3268                                 LocalParameters, Requirements, ClosingBraceLoc);
3269   }
3270 
3271   concepts::TypeRequirement *
3272   RebuildTypeRequirement(
3273       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3274     return SemaRef.BuildTypeRequirement(SubstDiag);
3275   }
3276 
3277   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3278     return SemaRef.BuildTypeRequirement(T);
3279   }
3280 
3281   concepts::ExprRequirement *
3282   RebuildExprRequirement(
3283       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3284       SourceLocation NoexceptLoc,
3285       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3286     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3287                                         std::move(Ret));
3288   }
3289 
3290   concepts::ExprRequirement *
3291   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3292                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3293     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3294                                         std::move(Ret));
3295   }
3296 
3297   concepts::NestedRequirement *
3298   RebuildNestedRequirement(
3299       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3300     return SemaRef.BuildNestedRequirement(SubstDiag);
3301   }
3302 
3303   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3304     return SemaRef.BuildNestedRequirement(Constraint);
3305   }
3306 
3307   /// \brief Build a new Objective-C boxed expression.
3308   ///
3309   /// By default, performs semantic analysis to build the new expression.
3310   /// Subclasses may override this routine to provide different behavior.
3311   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3312     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3313   }
3314 
3315   /// Build a new Objective-C array literal.
3316   ///
3317   /// By default, performs semantic analysis to build the new expression.
3318   /// Subclasses may override this routine to provide different behavior.
3319   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3320                                      Expr **Elements, unsigned NumElements) {
3321     return getSema().BuildObjCArrayLiteral(Range,
3322                                            MultiExprArg(Elements, NumElements));
3323   }
3324 
3325   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3326                                          Expr *Base, Expr *Key,
3327                                          ObjCMethodDecl *getterMethod,
3328                                          ObjCMethodDecl *setterMethod) {
3329     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3330                                                    getterMethod, setterMethod);
3331   }
3332 
3333   /// Build a new Objective-C dictionary literal.
3334   ///
3335   /// By default, performs semantic analysis to build the new expression.
3336   /// Subclasses may override this routine to provide different behavior.
3337   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3338                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3339     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3340   }
3341 
3342   /// Build a new Objective-C \@encode expression.
3343   ///
3344   /// By default, performs semantic analysis to build the new expression.
3345   /// Subclasses may override this routine to provide different behavior.
3346   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3347                                          TypeSourceInfo *EncodeTypeInfo,
3348                                          SourceLocation RParenLoc) {
3349     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3350   }
3351 
3352   /// Build a new Objective-C class message.
3353   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3354                                           Selector Sel,
3355                                           ArrayRef<SourceLocation> SelectorLocs,
3356                                           ObjCMethodDecl *Method,
3357                                           SourceLocation LBracLoc,
3358                                           MultiExprArg Args,
3359                                           SourceLocation RBracLoc) {
3360     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3361                                      ReceiverTypeInfo->getType(),
3362                                      /*SuperLoc=*/SourceLocation(),
3363                                      Sel, Method, LBracLoc, SelectorLocs,
3364                                      RBracLoc, Args);
3365   }
3366 
3367   /// Build a new Objective-C instance message.
3368   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3369                                           Selector Sel,
3370                                           ArrayRef<SourceLocation> SelectorLocs,
3371                                           ObjCMethodDecl *Method,
3372                                           SourceLocation LBracLoc,
3373                                           MultiExprArg Args,
3374                                           SourceLocation RBracLoc) {
3375     return SemaRef.BuildInstanceMessage(Receiver,
3376                                         Receiver->getType(),
3377                                         /*SuperLoc=*/SourceLocation(),
3378                                         Sel, Method, LBracLoc, SelectorLocs,
3379                                         RBracLoc, Args);
3380   }
3381 
3382   /// Build a new Objective-C instance/class message to 'super'.
3383   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3384                                     Selector Sel,
3385                                     ArrayRef<SourceLocation> SelectorLocs,
3386                                     QualType SuperType,
3387                                     ObjCMethodDecl *Method,
3388                                     SourceLocation LBracLoc,
3389                                     MultiExprArg Args,
3390                                     SourceLocation RBracLoc) {
3391     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3392                                           SuperType,
3393                                           SuperLoc,
3394                                           Sel, Method, LBracLoc, SelectorLocs,
3395                                           RBracLoc, Args)
3396                                       : SemaRef.BuildClassMessage(nullptr,
3397                                           SuperType,
3398                                           SuperLoc,
3399                                           Sel, Method, LBracLoc, SelectorLocs,
3400                                           RBracLoc, Args);
3401 
3402 
3403   }
3404 
3405   /// Build a new Objective-C ivar reference expression.
3406   ///
3407   /// By default, performs semantic analysis to build the new expression.
3408   /// Subclasses may override this routine to provide different behavior.
3409   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3410                                           SourceLocation IvarLoc,
3411                                           bool IsArrow, bool IsFreeIvar) {
3412     CXXScopeSpec SS;
3413     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3414     ExprResult Result = getSema().BuildMemberReferenceExpr(
3415         BaseArg, BaseArg->getType(),
3416         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3417         /*FirstQualifierInScope=*/nullptr, NameInfo,
3418         /*TemplateArgs=*/nullptr,
3419         /*S=*/nullptr);
3420     if (IsFreeIvar && Result.isUsable())
3421       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3422     return Result;
3423   }
3424 
3425   /// Build a new Objective-C property reference expression.
3426   ///
3427   /// By default, performs semantic analysis to build the new expression.
3428   /// Subclasses may override this routine to provide different behavior.
3429   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3430                                         ObjCPropertyDecl *Property,
3431                                         SourceLocation PropertyLoc) {
3432     CXXScopeSpec SS;
3433     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3434     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3435                                               /*FIXME:*/PropertyLoc,
3436                                               /*IsArrow=*/false,
3437                                               SS, SourceLocation(),
3438                                               /*FirstQualifierInScope=*/nullptr,
3439                                               NameInfo,
3440                                               /*TemplateArgs=*/nullptr,
3441                                               /*S=*/nullptr);
3442   }
3443 
3444   /// Build a new Objective-C property reference expression.
3445   ///
3446   /// By default, performs semantic analysis to build the new expression.
3447   /// Subclasses may override this routine to provide different behavior.
3448   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3449                                         ObjCMethodDecl *Getter,
3450                                         ObjCMethodDecl *Setter,
3451                                         SourceLocation PropertyLoc) {
3452     // Since these expressions can only be value-dependent, we do not
3453     // need to perform semantic analysis again.
3454     return Owned(
3455       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3456                                                   VK_LValue, OK_ObjCProperty,
3457                                                   PropertyLoc, Base));
3458   }
3459 
3460   /// Build a new Objective-C "isa" expression.
3461   ///
3462   /// By default, performs semantic analysis to build the new expression.
3463   /// Subclasses may override this routine to provide different behavior.
3464   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3465                                 SourceLocation OpLoc, bool IsArrow) {
3466     CXXScopeSpec SS;
3467     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3468     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3469                                               OpLoc, IsArrow,
3470                                               SS, SourceLocation(),
3471                                               /*FirstQualifierInScope=*/nullptr,
3472                                               NameInfo,
3473                                               /*TemplateArgs=*/nullptr,
3474                                               /*S=*/nullptr);
3475   }
3476 
3477   /// Build a new shuffle vector expression.
3478   ///
3479   /// By default, performs semantic analysis to build the new expression.
3480   /// Subclasses may override this routine to provide different behavior.
3481   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3482                                       MultiExprArg SubExprs,
3483                                       SourceLocation RParenLoc) {
3484     // Find the declaration for __builtin_shufflevector
3485     const IdentifierInfo &Name
3486       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3487     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3488     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3489     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3490 
3491     // Build a reference to the __builtin_shufflevector builtin
3492     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3493     Expr *Callee = new (SemaRef.Context)
3494         DeclRefExpr(SemaRef.Context, Builtin, false,
3495                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3496     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3497     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3498                                        CK_BuiltinFnToFnPtr).get();
3499 
3500     // Build the CallExpr
3501     ExprResult TheCall = CallExpr::Create(
3502         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3503         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3504 
3505     // Type-check the __builtin_shufflevector expression.
3506     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3507   }
3508 
3509   /// Build a new convert vector expression.
3510   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3511                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3512                                       SourceLocation RParenLoc) {
3513     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3514                                          BuiltinLoc, RParenLoc);
3515   }
3516 
3517   /// Build a new template argument pack expansion.
3518   ///
3519   /// By default, performs semantic analysis to build a new pack expansion
3520   /// for a template argument. Subclasses may override this routine to provide
3521   /// different behavior.
3522   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3523                                            SourceLocation EllipsisLoc,
3524                                            Optional<unsigned> NumExpansions) {
3525     switch (Pattern.getArgument().getKind()) {
3526     case TemplateArgument::Expression: {
3527       ExprResult Result
3528         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3529                                        EllipsisLoc, NumExpansions);
3530       if (Result.isInvalid())
3531         return TemplateArgumentLoc();
3532 
3533       return TemplateArgumentLoc(Result.get(), Result.get());
3534     }
3535 
3536     case TemplateArgument::Template:
3537       return TemplateArgumentLoc(TemplateArgument(
3538                                           Pattern.getArgument().getAsTemplate(),
3539                                                   NumExpansions),
3540                                  Pattern.getTemplateQualifierLoc(),
3541                                  Pattern.getTemplateNameLoc(),
3542                                  EllipsisLoc);
3543 
3544     case TemplateArgument::Null:
3545     case TemplateArgument::Integral:
3546     case TemplateArgument::Declaration:
3547     case TemplateArgument::Pack:
3548     case TemplateArgument::TemplateExpansion:
3549     case TemplateArgument::NullPtr:
3550       llvm_unreachable("Pack expansion pattern has no parameter packs");
3551 
3552     case TemplateArgument::Type:
3553       if (TypeSourceInfo *Expansion
3554             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3555                                            EllipsisLoc,
3556                                            NumExpansions))
3557         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3558                                    Expansion);
3559       break;
3560     }
3561 
3562     return TemplateArgumentLoc();
3563   }
3564 
3565   /// Build a new expression pack expansion.
3566   ///
3567   /// By default, performs semantic analysis to build a new pack expansion
3568   /// for an expression. Subclasses may override this routine to provide
3569   /// different behavior.
3570   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3571                                   Optional<unsigned> NumExpansions) {
3572     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3573   }
3574 
3575   /// Build a new C++1z fold-expression.
3576   ///
3577   /// By default, performs semantic analysis in order to build a new fold
3578   /// expression.
3579   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3580                                 BinaryOperatorKind Operator,
3581                                 SourceLocation EllipsisLoc, Expr *RHS,
3582                                 SourceLocation RParenLoc,
3583                                 Optional<unsigned> NumExpansions) {
3584     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3585                                       RHS, RParenLoc, NumExpansions);
3586   }
3587 
3588   /// Build an empty C++1z fold-expression with the given operator.
3589   ///
3590   /// By default, produces the fallback value for the fold-expression, or
3591   /// produce an error if there is no fallback value.
3592   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3593                                      BinaryOperatorKind Operator) {
3594     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3595   }
3596 
3597   /// Build a new atomic operation expression.
3598   ///
3599   /// By default, performs semantic analysis to build the new expression.
3600   /// Subclasses may override this routine to provide different behavior.
3601   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3602                                AtomicExpr::AtomicOp Op,
3603                                SourceLocation RParenLoc) {
3604     // Use this for all of the locations, since we don't know the difference
3605     // between the call and the expr at this point.
3606     SourceRange Range{BuiltinLoc, RParenLoc};
3607     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3608                                      Sema::AtomicArgumentOrder::AST);
3609   }
3610 
3611   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3612                                  ArrayRef<Expr *> SubExprs) {
3613     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs);
3614   }
3615 
3616 private:
3617   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3618                                      QualType ObjectType,
3619                                      NamedDecl *FirstQualifierInScope,
3620                                      CXXScopeSpec &SS);
3621 
3622   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3623                                              QualType ObjectType,
3624                                              NamedDecl *FirstQualifierInScope,
3625                                              CXXScopeSpec &SS);
3626 
3627   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3628                                             NamedDecl *FirstQualifierInScope,
3629                                             CXXScopeSpec &SS);
3630 
3631   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3632                                       DependentNameTypeLoc TL,
3633                                       bool DeducibleTSTContext);
3634 };
3635 
3636 template <typename Derived>
3637 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3638   if (!S)
3639     return S;
3640 
3641   switch (S->getStmtClass()) {
3642   case Stmt::NoStmtClass: break;
3643 
3644   // Transform individual statement nodes
3645   // Pass SDK into statements that can produce a value
3646 #define STMT(Node, Parent)                                              \
3647   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3648 #define VALUESTMT(Node, Parent)                                         \
3649   case Stmt::Node##Class:                                               \
3650     return getDerived().Transform##Node(cast<Node>(S), SDK);
3651 #define ABSTRACT_STMT(Node)
3652 #define EXPR(Node, Parent)
3653 #include "clang/AST/StmtNodes.inc"
3654 
3655   // Transform expressions by calling TransformExpr.
3656 #define STMT(Node, Parent)
3657 #define ABSTRACT_STMT(Stmt)
3658 #define EXPR(Node, Parent) case Stmt::Node##Class:
3659 #include "clang/AST/StmtNodes.inc"
3660     {
3661       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3662 
3663       if (SDK == SDK_StmtExprResult)
3664         E = getSema().ActOnStmtExprResult(E);
3665       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3666     }
3667   }
3668 
3669   return S;
3670 }
3671 
3672 template<typename Derived>
3673 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3674   if (!S)
3675     return S;
3676 
3677   switch (S->getClauseKind()) {
3678   default: break;
3679   // Transform individual clause nodes
3680 #define OMP_CLAUSE_CLASS(Enum, Str, Class) \
3681   case Enum:                                                                   \
3682     return getDerived().Transform ## Class(cast<Class>(S));
3683 #include "llvm/Frontend/OpenMP/OMPKinds.def"
3684   }
3685 
3686   return S;
3687 }
3688 
3689 
3690 template<typename Derived>
3691 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3692   if (!E)
3693     return E;
3694 
3695   switch (E->getStmtClass()) {
3696     case Stmt::NoStmtClass: break;
3697 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3698 #define ABSTRACT_STMT(Stmt)
3699 #define EXPR(Node, Parent)                                              \
3700     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3701 #include "clang/AST/StmtNodes.inc"
3702   }
3703 
3704   return E;
3705 }
3706 
3707 template<typename Derived>
3708 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3709                                                         bool NotCopyInit) {
3710   // Initializers are instantiated like expressions, except that various outer
3711   // layers are stripped.
3712   if (!Init)
3713     return Init;
3714 
3715   if (auto *FE = dyn_cast<FullExpr>(Init))
3716     Init = FE->getSubExpr();
3717 
3718   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3719     Init = AIL->getCommonExpr();
3720 
3721   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3722     Init = MTE->getSubExpr();
3723 
3724   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3725     Init = Binder->getSubExpr();
3726 
3727   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3728     Init = ICE->getSubExprAsWritten();
3729 
3730   if (CXXStdInitializerListExpr *ILE =
3731           dyn_cast<CXXStdInitializerListExpr>(Init))
3732     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3733 
3734   // If this is copy-initialization, we only need to reconstruct
3735   // InitListExprs. Other forms of copy-initialization will be a no-op if
3736   // the initializer is already the right type.
3737   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3738   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3739     return getDerived().TransformExpr(Init);
3740 
3741   // Revert value-initialization back to empty parens.
3742   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3743     SourceRange Parens = VIE->getSourceRange();
3744     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3745                                              Parens.getEnd());
3746   }
3747 
3748   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3749   if (isa<ImplicitValueInitExpr>(Init))
3750     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3751                                              SourceLocation());
3752 
3753   // Revert initialization by constructor back to a parenthesized or braced list
3754   // of expressions. Any other form of initializer can just be reused directly.
3755   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3756     return getDerived().TransformExpr(Init);
3757 
3758   // If the initialization implicitly converted an initializer list to a
3759   // std::initializer_list object, unwrap the std::initializer_list too.
3760   if (Construct && Construct->isStdInitListInitialization())
3761     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3762 
3763   // Enter a list-init context if this was list initialization.
3764   EnterExpressionEvaluationContext Context(
3765       getSema(), EnterExpressionEvaluationContext::InitList,
3766       Construct->isListInitialization());
3767 
3768   SmallVector<Expr*, 8> NewArgs;
3769   bool ArgChanged = false;
3770   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3771                                   /*IsCall*/true, NewArgs, &ArgChanged))
3772     return ExprError();
3773 
3774   // If this was list initialization, revert to syntactic list form.
3775   if (Construct->isListInitialization())
3776     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3777                                         Construct->getEndLoc());
3778 
3779   // Build a ParenListExpr to represent anything else.
3780   SourceRange Parens = Construct->getParenOrBraceRange();
3781   if (Parens.isInvalid()) {
3782     // This was a variable declaration's initialization for which no initializer
3783     // was specified.
3784     assert(NewArgs.empty() &&
3785            "no parens or braces but have direct init with arguments?");
3786     return ExprEmpty();
3787   }
3788   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3789                                            Parens.getEnd());
3790 }
3791 
3792 template<typename Derived>
3793 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3794                                             unsigned NumInputs,
3795                                             bool IsCall,
3796                                       SmallVectorImpl<Expr *> &Outputs,
3797                                             bool *ArgChanged) {
3798   for (unsigned I = 0; I != NumInputs; ++I) {
3799     // If requested, drop call arguments that need to be dropped.
3800     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3801       if (ArgChanged)
3802         *ArgChanged = true;
3803 
3804       break;
3805     }
3806 
3807     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3808       Expr *Pattern = Expansion->getPattern();
3809 
3810       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3811       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3812       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3813 
3814       // Determine whether the set of unexpanded parameter packs can and should
3815       // be expanded.
3816       bool Expand = true;
3817       bool RetainExpansion = false;
3818       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3819       Optional<unsigned> NumExpansions = OrigNumExpansions;
3820       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3821                                                Pattern->getSourceRange(),
3822                                                Unexpanded,
3823                                                Expand, RetainExpansion,
3824                                                NumExpansions))
3825         return true;
3826 
3827       if (!Expand) {
3828         // The transform has determined that we should perform a simple
3829         // transformation on the pack expansion, producing another pack
3830         // expansion.
3831         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3832         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3833         if (OutPattern.isInvalid())
3834           return true;
3835 
3836         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3837                                                 Expansion->getEllipsisLoc(),
3838                                                            NumExpansions);
3839         if (Out.isInvalid())
3840           return true;
3841 
3842         if (ArgChanged)
3843           *ArgChanged = true;
3844         Outputs.push_back(Out.get());
3845         continue;
3846       }
3847 
3848       // Record right away that the argument was changed.  This needs
3849       // to happen even if the array expands to nothing.
3850       if (ArgChanged) *ArgChanged = true;
3851 
3852       // The transform has determined that we should perform an elementwise
3853       // expansion of the pattern. Do so.
3854       for (unsigned I = 0; I != *NumExpansions; ++I) {
3855         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3856         ExprResult Out = getDerived().TransformExpr(Pattern);
3857         if (Out.isInvalid())
3858           return true;
3859 
3860         if (Out.get()->containsUnexpandedParameterPack()) {
3861           Out = getDerived().RebuildPackExpansion(
3862               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3863           if (Out.isInvalid())
3864             return true;
3865         }
3866 
3867         Outputs.push_back(Out.get());
3868       }
3869 
3870       // If we're supposed to retain a pack expansion, do so by temporarily
3871       // forgetting the partially-substituted parameter pack.
3872       if (RetainExpansion) {
3873         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3874 
3875         ExprResult Out = getDerived().TransformExpr(Pattern);
3876         if (Out.isInvalid())
3877           return true;
3878 
3879         Out = getDerived().RebuildPackExpansion(
3880             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3881         if (Out.isInvalid())
3882           return true;
3883 
3884         Outputs.push_back(Out.get());
3885       }
3886 
3887       continue;
3888     }
3889 
3890     ExprResult Result =
3891       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3892              : getDerived().TransformExpr(Inputs[I]);
3893     if (Result.isInvalid())
3894       return true;
3895 
3896     if (Result.get() != Inputs[I] && ArgChanged)
3897       *ArgChanged = true;
3898 
3899     Outputs.push_back(Result.get());
3900   }
3901 
3902   return false;
3903 }
3904 
3905 template <typename Derived>
3906 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3907     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3908   if (Var) {
3909     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3910         getDerived().TransformDefinition(Var->getLocation(), Var));
3911 
3912     if (!ConditionVar)
3913       return Sema::ConditionError();
3914 
3915     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3916   }
3917 
3918   if (Expr) {
3919     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3920 
3921     if (CondExpr.isInvalid())
3922       return Sema::ConditionError();
3923 
3924     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3925   }
3926 
3927   return Sema::ConditionResult();
3928 }
3929 
3930 template<typename Derived>
3931 NestedNameSpecifierLoc
3932 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3933                                                     NestedNameSpecifierLoc NNS,
3934                                                      QualType ObjectType,
3935                                              NamedDecl *FirstQualifierInScope) {
3936   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3937   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3938        Qualifier = Qualifier.getPrefix())
3939     Qualifiers.push_back(Qualifier);
3940 
3941   CXXScopeSpec SS;
3942   while (!Qualifiers.empty()) {
3943     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3944     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3945 
3946     switch (QNNS->getKind()) {
3947     case NestedNameSpecifier::Identifier: {
3948       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3949                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3950       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3951                                               SS, FirstQualifierInScope, false))
3952         return NestedNameSpecifierLoc();
3953     }
3954       break;
3955 
3956     case NestedNameSpecifier::Namespace: {
3957       NamespaceDecl *NS
3958         = cast_or_null<NamespaceDecl>(
3959                                     getDerived().TransformDecl(
3960                                                           Q.getLocalBeginLoc(),
3961                                                        QNNS->getAsNamespace()));
3962       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3963       break;
3964     }
3965 
3966     case NestedNameSpecifier::NamespaceAlias: {
3967       NamespaceAliasDecl *Alias
3968         = cast_or_null<NamespaceAliasDecl>(
3969                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3970                                                  QNNS->getAsNamespaceAlias()));
3971       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3972                 Q.getLocalEndLoc());
3973       break;
3974     }
3975 
3976     case NestedNameSpecifier::Global:
3977       // There is no meaningful transformation that one could perform on the
3978       // global scope.
3979       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3980       break;
3981 
3982     case NestedNameSpecifier::Super: {
3983       CXXRecordDecl *RD =
3984           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3985               SourceLocation(), QNNS->getAsRecordDecl()));
3986       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3987       break;
3988     }
3989 
3990     case NestedNameSpecifier::TypeSpecWithTemplate:
3991     case NestedNameSpecifier::TypeSpec: {
3992       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3993                                               FirstQualifierInScope, SS);
3994 
3995       if (!TL)
3996         return NestedNameSpecifierLoc();
3997 
3998       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3999           (SemaRef.getLangOpts().CPlusPlus11 &&
4000            TL.getType()->isEnumeralType())) {
4001         assert(!TL.getType().hasLocalQualifiers() &&
4002                "Can't get cv-qualifiers here");
4003         if (TL.getType()->isEnumeralType())
4004           SemaRef.Diag(TL.getBeginLoc(),
4005                        diag::warn_cxx98_compat_enum_nested_name_spec);
4006         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
4007                   Q.getLocalEndLoc());
4008         break;
4009       }
4010       // If the nested-name-specifier is an invalid type def, don't emit an
4011       // error because a previous error should have already been emitted.
4012       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
4013       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4014         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4015           << TL.getType() << SS.getRange();
4016       }
4017       return NestedNameSpecifierLoc();
4018     }
4019     }
4020 
4021     // The qualifier-in-scope and object type only apply to the leftmost entity.
4022     FirstQualifierInScope = nullptr;
4023     ObjectType = QualType();
4024   }
4025 
4026   // Don't rebuild the nested-name-specifier if we don't have to.
4027   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4028       !getDerived().AlwaysRebuild())
4029     return NNS;
4030 
4031   // If we can re-use the source-location data from the original
4032   // nested-name-specifier, do so.
4033   if (SS.location_size() == NNS.getDataLength() &&
4034       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4035     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4036 
4037   // Allocate new nested-name-specifier location information.
4038   return SS.getWithLocInContext(SemaRef.Context);
4039 }
4040 
4041 template<typename Derived>
4042 DeclarationNameInfo
4043 TreeTransform<Derived>
4044 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4045   DeclarationName Name = NameInfo.getName();
4046   if (!Name)
4047     return DeclarationNameInfo();
4048 
4049   switch (Name.getNameKind()) {
4050   case DeclarationName::Identifier:
4051   case DeclarationName::ObjCZeroArgSelector:
4052   case DeclarationName::ObjCOneArgSelector:
4053   case DeclarationName::ObjCMultiArgSelector:
4054   case DeclarationName::CXXOperatorName:
4055   case DeclarationName::CXXLiteralOperatorName:
4056   case DeclarationName::CXXUsingDirective:
4057     return NameInfo;
4058 
4059   case DeclarationName::CXXDeductionGuideName: {
4060     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4061     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4062         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4063     if (!NewTemplate)
4064       return DeclarationNameInfo();
4065 
4066     DeclarationNameInfo NewNameInfo(NameInfo);
4067     NewNameInfo.setName(
4068         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4069     return NewNameInfo;
4070   }
4071 
4072   case DeclarationName::CXXConstructorName:
4073   case DeclarationName::CXXDestructorName:
4074   case DeclarationName::CXXConversionFunctionName: {
4075     TypeSourceInfo *NewTInfo;
4076     CanQualType NewCanTy;
4077     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4078       NewTInfo = getDerived().TransformType(OldTInfo);
4079       if (!NewTInfo)
4080         return DeclarationNameInfo();
4081       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4082     }
4083     else {
4084       NewTInfo = nullptr;
4085       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4086       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4087       if (NewT.isNull())
4088         return DeclarationNameInfo();
4089       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4090     }
4091 
4092     DeclarationName NewName
4093       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4094                                                            NewCanTy);
4095     DeclarationNameInfo NewNameInfo(NameInfo);
4096     NewNameInfo.setName(NewName);
4097     NewNameInfo.setNamedTypeInfo(NewTInfo);
4098     return NewNameInfo;
4099   }
4100   }
4101 
4102   llvm_unreachable("Unknown name kind.");
4103 }
4104 
4105 template<typename Derived>
4106 TemplateName
4107 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4108                                               TemplateName Name,
4109                                               SourceLocation NameLoc,
4110                                               QualType ObjectType,
4111                                               NamedDecl *FirstQualifierInScope,
4112                                               bool AllowInjectedClassName) {
4113   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4114     TemplateDecl *Template = QTN->getTemplateDecl();
4115     assert(Template && "qualified template name must refer to a template");
4116 
4117     TemplateDecl *TransTemplate
4118       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4119                                                               Template));
4120     if (!TransTemplate)
4121       return TemplateName();
4122 
4123     if (!getDerived().AlwaysRebuild() &&
4124         SS.getScopeRep() == QTN->getQualifier() &&
4125         TransTemplate == Template)
4126       return Name;
4127 
4128     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4129                                             TransTemplate);
4130   }
4131 
4132   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4133     if (SS.getScopeRep()) {
4134       // These apply to the scope specifier, not the template.
4135       ObjectType = QualType();
4136       FirstQualifierInScope = nullptr;
4137     }
4138 
4139     if (!getDerived().AlwaysRebuild() &&
4140         SS.getScopeRep() == DTN->getQualifier() &&
4141         ObjectType.isNull())
4142       return Name;
4143 
4144     // FIXME: Preserve the location of the "template" keyword.
4145     SourceLocation TemplateKWLoc = NameLoc;
4146 
4147     if (DTN->isIdentifier()) {
4148       return getDerived().RebuildTemplateName(SS,
4149                                               TemplateKWLoc,
4150                                               *DTN->getIdentifier(),
4151                                               NameLoc,
4152                                               ObjectType,
4153                                               FirstQualifierInScope,
4154                                               AllowInjectedClassName);
4155     }
4156 
4157     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4158                                             DTN->getOperator(), NameLoc,
4159                                             ObjectType, AllowInjectedClassName);
4160   }
4161 
4162   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4163     TemplateDecl *TransTemplate
4164       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4165                                                               Template));
4166     if (!TransTemplate)
4167       return TemplateName();
4168 
4169     if (!getDerived().AlwaysRebuild() &&
4170         TransTemplate == Template)
4171       return Name;
4172 
4173     return TemplateName(TransTemplate);
4174   }
4175 
4176   if (SubstTemplateTemplateParmPackStorage *SubstPack
4177       = Name.getAsSubstTemplateTemplateParmPack()) {
4178     TemplateTemplateParmDecl *TransParam
4179     = cast_or_null<TemplateTemplateParmDecl>(
4180             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
4181     if (!TransParam)
4182       return TemplateName();
4183 
4184     if (!getDerived().AlwaysRebuild() &&
4185         TransParam == SubstPack->getParameterPack())
4186       return Name;
4187 
4188     return getDerived().RebuildTemplateName(TransParam,
4189                                             SubstPack->getArgumentPack());
4190   }
4191 
4192   // These should be getting filtered out before they reach the AST.
4193   llvm_unreachable("overloaded function decl survived to here");
4194 }
4195 
4196 template<typename Derived>
4197 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4198                                          const TemplateArgument &Arg,
4199                                          TemplateArgumentLoc &Output) {
4200   Output = getSema().getTrivialTemplateArgumentLoc(
4201       Arg, QualType(), getDerived().getBaseLocation());
4202 }
4203 
4204 template<typename Derived>
4205 bool TreeTransform<Derived>::TransformTemplateArgument(
4206                                          const TemplateArgumentLoc &Input,
4207                                          TemplateArgumentLoc &Output, bool Uneval) {
4208   const TemplateArgument &Arg = Input.getArgument();
4209   switch (Arg.getKind()) {
4210   case TemplateArgument::Null:
4211   case TemplateArgument::Pack:
4212     llvm_unreachable("Unexpected TemplateArgument");
4213 
4214   case TemplateArgument::Integral:
4215   case TemplateArgument::NullPtr:
4216   case TemplateArgument::Declaration: {
4217     // Transform a resolved template argument straight to a resolved template
4218     // argument. We get here when substituting into an already-substituted
4219     // template type argument during concept satisfaction checking.
4220     QualType T = Arg.getNonTypeTemplateArgumentType();
4221     QualType NewT = getDerived().TransformType(T);
4222     if (NewT.isNull())
4223       return true;
4224 
4225     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4226                        ? Arg.getAsDecl()
4227                        : nullptr;
4228     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4229                               getDerived().getBaseLocation(), D))
4230                         : nullptr;
4231     if (D && !NewD)
4232       return true;
4233 
4234     if (NewT == T && D == NewD)
4235       Output = Input;
4236     else if (Arg.getKind() == TemplateArgument::Integral)
4237       Output = TemplateArgumentLoc(
4238           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4239           TemplateArgumentLocInfo());
4240     else if (Arg.getKind() == TemplateArgument::NullPtr)
4241       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4242                                    TemplateArgumentLocInfo());
4243     else
4244       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4245                                    TemplateArgumentLocInfo());
4246 
4247     return false;
4248   }
4249 
4250   case TemplateArgument::Type: {
4251     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4252     if (!DI)
4253       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4254 
4255     DI = getDerived().TransformType(DI);
4256     if (!DI) return true;
4257 
4258     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4259     return false;
4260   }
4261 
4262   case TemplateArgument::Template: {
4263     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4264     if (QualifierLoc) {
4265       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4266       if (!QualifierLoc)
4267         return true;
4268     }
4269 
4270     CXXScopeSpec SS;
4271     SS.Adopt(QualifierLoc);
4272     TemplateName Template
4273       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
4274                                            Input.getTemplateNameLoc());
4275     if (Template.isNull())
4276       return true;
4277 
4278     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
4279                                  Input.getTemplateNameLoc());
4280     return false;
4281   }
4282 
4283   case TemplateArgument::TemplateExpansion:
4284     llvm_unreachable("Caller should expand pack expansions");
4285 
4286   case TemplateArgument::Expression: {
4287     // Template argument expressions are constant expressions.
4288     EnterExpressionEvaluationContext Unevaluated(
4289         getSema(),
4290         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4291                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4292         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4293         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4294 
4295     Expr *InputExpr = Input.getSourceExpression();
4296     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4297 
4298     ExprResult E = getDerived().TransformExpr(InputExpr);
4299     E = SemaRef.ActOnConstantExpression(E);
4300     if (E.isInvalid()) return true;
4301     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4302     return false;
4303   }
4304   }
4305 
4306   // Work around bogus GCC warning
4307   return true;
4308 }
4309 
4310 /// Iterator adaptor that invents template argument location information
4311 /// for each of the template arguments in its underlying iterator.
4312 template<typename Derived, typename InputIterator>
4313 class TemplateArgumentLocInventIterator {
4314   TreeTransform<Derived> &Self;
4315   InputIterator Iter;
4316 
4317 public:
4318   typedef TemplateArgumentLoc value_type;
4319   typedef TemplateArgumentLoc reference;
4320   typedef typename std::iterator_traits<InputIterator>::difference_type
4321     difference_type;
4322   typedef std::input_iterator_tag iterator_category;
4323 
4324   class pointer {
4325     TemplateArgumentLoc Arg;
4326 
4327   public:
4328     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4329 
4330     const TemplateArgumentLoc *operator->() const { return &Arg; }
4331   };
4332 
4333   TemplateArgumentLocInventIterator() { }
4334 
4335   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4336                                              InputIterator Iter)
4337     : Self(Self), Iter(Iter) { }
4338 
4339   TemplateArgumentLocInventIterator &operator++() {
4340     ++Iter;
4341     return *this;
4342   }
4343 
4344   TemplateArgumentLocInventIterator operator++(int) {
4345     TemplateArgumentLocInventIterator Old(*this);
4346     ++(*this);
4347     return Old;
4348   }
4349 
4350   reference operator*() const {
4351     TemplateArgumentLoc Result;
4352     Self.InventTemplateArgumentLoc(*Iter, Result);
4353     return Result;
4354   }
4355 
4356   pointer operator->() const { return pointer(**this); }
4357 
4358   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4359                          const TemplateArgumentLocInventIterator &Y) {
4360     return X.Iter == Y.Iter;
4361   }
4362 
4363   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4364                          const TemplateArgumentLocInventIterator &Y) {
4365     return X.Iter != Y.Iter;
4366   }
4367 };
4368 
4369 template<typename Derived>
4370 template<typename InputIterator>
4371 bool TreeTransform<Derived>::TransformTemplateArguments(
4372     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4373     bool Uneval) {
4374   for (; First != Last; ++First) {
4375     TemplateArgumentLoc Out;
4376     TemplateArgumentLoc In = *First;
4377 
4378     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4379       // Unpack argument packs, which we translate them into separate
4380       // arguments.
4381       // FIXME: We could do much better if we could guarantee that the
4382       // TemplateArgumentLocInfo for the pack expansion would be usable for
4383       // all of the template arguments in the argument pack.
4384       typedef TemplateArgumentLocInventIterator<Derived,
4385                                                 TemplateArgument::pack_iterator>
4386         PackLocIterator;
4387       if (TransformTemplateArguments(PackLocIterator(*this,
4388                                                  In.getArgument().pack_begin()),
4389                                      PackLocIterator(*this,
4390                                                    In.getArgument().pack_end()),
4391                                      Outputs, Uneval))
4392         return true;
4393 
4394       continue;
4395     }
4396 
4397     if (In.getArgument().isPackExpansion()) {
4398       // We have a pack expansion, for which we will be substituting into
4399       // the pattern.
4400       SourceLocation Ellipsis;
4401       Optional<unsigned> OrigNumExpansions;
4402       TemplateArgumentLoc Pattern
4403         = getSema().getTemplateArgumentPackExpansionPattern(
4404               In, Ellipsis, OrigNumExpansions);
4405 
4406       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4407       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4408       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4409 
4410       // Determine whether the set of unexpanded parameter packs can and should
4411       // be expanded.
4412       bool Expand = true;
4413       bool RetainExpansion = false;
4414       Optional<unsigned> NumExpansions = OrigNumExpansions;
4415       if (getDerived().TryExpandParameterPacks(Ellipsis,
4416                                                Pattern.getSourceRange(),
4417                                                Unexpanded,
4418                                                Expand,
4419                                                RetainExpansion,
4420                                                NumExpansions))
4421         return true;
4422 
4423       if (!Expand) {
4424         // The transform has determined that we should perform a simple
4425         // transformation on the pack expansion, producing another pack
4426         // expansion.
4427         TemplateArgumentLoc OutPattern;
4428         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4429         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4430           return true;
4431 
4432         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4433                                                 NumExpansions);
4434         if (Out.getArgument().isNull())
4435           return true;
4436 
4437         Outputs.addArgument(Out);
4438         continue;
4439       }
4440 
4441       // The transform has determined that we should perform an elementwise
4442       // expansion of the pattern. Do so.
4443       for (unsigned I = 0; I != *NumExpansions; ++I) {
4444         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4445 
4446         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4447           return true;
4448 
4449         if (Out.getArgument().containsUnexpandedParameterPack()) {
4450           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4451                                                   OrigNumExpansions);
4452           if (Out.getArgument().isNull())
4453             return true;
4454         }
4455 
4456         Outputs.addArgument(Out);
4457       }
4458 
4459       // If we're supposed to retain a pack expansion, do so by temporarily
4460       // forgetting the partially-substituted parameter pack.
4461       if (RetainExpansion) {
4462         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4463 
4464         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4465           return true;
4466 
4467         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4468                                                 OrigNumExpansions);
4469         if (Out.getArgument().isNull())
4470           return true;
4471 
4472         Outputs.addArgument(Out);
4473       }
4474 
4475       continue;
4476     }
4477 
4478     // The simple case:
4479     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4480       return true;
4481 
4482     Outputs.addArgument(Out);
4483   }
4484 
4485   return false;
4486 
4487 }
4488 
4489 //===----------------------------------------------------------------------===//
4490 // Type transformation
4491 //===----------------------------------------------------------------------===//
4492 
4493 template<typename Derived>
4494 QualType TreeTransform<Derived>::TransformType(QualType T) {
4495   if (getDerived().AlreadyTransformed(T))
4496     return T;
4497 
4498   // Temporary workaround.  All of these transformations should
4499   // eventually turn into transformations on TypeLocs.
4500   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4501                                                 getDerived().getBaseLocation());
4502 
4503   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4504 
4505   if (!NewDI)
4506     return QualType();
4507 
4508   return NewDI->getType();
4509 }
4510 
4511 template<typename Derived>
4512 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4513   // Refine the base location to the type's location.
4514   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4515                        getDerived().getBaseEntity());
4516   if (getDerived().AlreadyTransformed(DI->getType()))
4517     return DI;
4518 
4519   TypeLocBuilder TLB;
4520 
4521   TypeLoc TL = DI->getTypeLoc();
4522   TLB.reserve(TL.getFullDataSize());
4523 
4524   QualType Result = getDerived().TransformType(TLB, TL);
4525   if (Result.isNull())
4526     return nullptr;
4527 
4528   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4529 }
4530 
4531 template<typename Derived>
4532 QualType
4533 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4534   switch (T.getTypeLocClass()) {
4535 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4536 #define TYPELOC(CLASS, PARENT)                                                 \
4537   case TypeLoc::CLASS:                                                         \
4538     return getDerived().Transform##CLASS##Type(TLB,                            \
4539                                                T.castAs<CLASS##TypeLoc>());
4540 #include "clang/AST/TypeLocNodes.def"
4541   }
4542 
4543   llvm_unreachable("unhandled type loc!");
4544 }
4545 
4546 template<typename Derived>
4547 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4548   if (!isa<DependentNameType>(T))
4549     return TransformType(T);
4550 
4551   if (getDerived().AlreadyTransformed(T))
4552     return T;
4553   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4554                                                 getDerived().getBaseLocation());
4555   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4556   return NewDI ? NewDI->getType() : QualType();
4557 }
4558 
4559 template<typename Derived>
4560 TypeSourceInfo *
4561 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4562   if (!isa<DependentNameType>(DI->getType()))
4563     return TransformType(DI);
4564 
4565   // Refine the base location to the type's location.
4566   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4567                        getDerived().getBaseEntity());
4568   if (getDerived().AlreadyTransformed(DI->getType()))
4569     return DI;
4570 
4571   TypeLocBuilder TLB;
4572 
4573   TypeLoc TL = DI->getTypeLoc();
4574   TLB.reserve(TL.getFullDataSize());
4575 
4576   auto QTL = TL.getAs<QualifiedTypeLoc>();
4577   if (QTL)
4578     TL = QTL.getUnqualifiedLoc();
4579 
4580   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4581 
4582   QualType Result = getDerived().TransformDependentNameType(
4583       TLB, DNTL, /*DeducedTSTContext*/true);
4584   if (Result.isNull())
4585     return nullptr;
4586 
4587   if (QTL) {
4588     Result = getDerived().RebuildQualifiedType(Result, QTL);
4589     if (Result.isNull())
4590       return nullptr;
4591     TLB.TypeWasModifiedSafely(Result);
4592   }
4593 
4594   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4595 }
4596 
4597 template<typename Derived>
4598 QualType
4599 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4600                                                QualifiedTypeLoc T) {
4601   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4602   if (Result.isNull())
4603     return QualType();
4604 
4605   Result = getDerived().RebuildQualifiedType(Result, T);
4606 
4607   if (Result.isNull())
4608     return QualType();
4609 
4610   // RebuildQualifiedType might have updated the type, but not in a way
4611   // that invalidates the TypeLoc. (There's no location information for
4612   // qualifiers.)
4613   TLB.TypeWasModifiedSafely(Result);
4614 
4615   return Result;
4616 }
4617 
4618 template <typename Derived>
4619 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4620                                                       QualifiedTypeLoc TL) {
4621 
4622   SourceLocation Loc = TL.getBeginLoc();
4623   Qualifiers Quals = TL.getType().getLocalQualifiers();
4624 
4625   if (((T.getAddressSpace() != LangAS::Default &&
4626         Quals.getAddressSpace() != LangAS::Default)) &&
4627       T.getAddressSpace() != Quals.getAddressSpace()) {
4628     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4629         << TL.getType() << T;
4630     return QualType();
4631   }
4632 
4633   // C++ [dcl.fct]p7:
4634   //   [When] adding cv-qualifications on top of the function type [...] the
4635   //   cv-qualifiers are ignored.
4636   if (T->isFunctionType()) {
4637     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4638                                                      Quals.getAddressSpace());
4639     return T;
4640   }
4641 
4642   // C++ [dcl.ref]p1:
4643   //   when the cv-qualifiers are introduced through the use of a typedef-name
4644   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4645   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4646   // applied to a reference type.
4647   if (T->isReferenceType()) {
4648     // The only qualifier that applies to a reference type is restrict.
4649     if (!Quals.hasRestrict())
4650       return T;
4651     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4652   }
4653 
4654   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4655   // resulting type.
4656   if (Quals.hasObjCLifetime()) {
4657     if (!T->isObjCLifetimeType() && !T->isDependentType())
4658       Quals.removeObjCLifetime();
4659     else if (T.getObjCLifetime()) {
4660       // Objective-C ARC:
4661       //   A lifetime qualifier applied to a substituted template parameter
4662       //   overrides the lifetime qualifier from the template argument.
4663       const AutoType *AutoTy;
4664       if (const SubstTemplateTypeParmType *SubstTypeParam
4665                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4666         QualType Replacement = SubstTypeParam->getReplacementType();
4667         Qualifiers Qs = Replacement.getQualifiers();
4668         Qs.removeObjCLifetime();
4669         Replacement = SemaRef.Context.getQualifiedType(
4670             Replacement.getUnqualifiedType(), Qs);
4671         T = SemaRef.Context.getSubstTemplateTypeParmType(
4672             SubstTypeParam->getReplacedParameter(), Replacement);
4673       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4674         // 'auto' types behave the same way as template parameters.
4675         QualType Deduced = AutoTy->getDeducedType();
4676         Qualifiers Qs = Deduced.getQualifiers();
4677         Qs.removeObjCLifetime();
4678         Deduced =
4679             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4680         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4681                                         AutoTy->isDependentType(),
4682                                         /*isPack=*/false,
4683                                         AutoTy->getTypeConstraintConcept(),
4684                                         AutoTy->getTypeConstraintArguments());
4685       } else {
4686         // Otherwise, complain about the addition of a qualifier to an
4687         // already-qualified type.
4688         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4689         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4690         Quals.removeObjCLifetime();
4691       }
4692     }
4693   }
4694 
4695   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4696 }
4697 
4698 template<typename Derived>
4699 TypeLoc
4700 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4701                                                    QualType ObjectType,
4702                                                    NamedDecl *UnqualLookup,
4703                                                    CXXScopeSpec &SS) {
4704   if (getDerived().AlreadyTransformed(TL.getType()))
4705     return TL;
4706 
4707   TypeSourceInfo *TSI =
4708       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4709   if (TSI)
4710     return TSI->getTypeLoc();
4711   return TypeLoc();
4712 }
4713 
4714 template<typename Derived>
4715 TypeSourceInfo *
4716 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4717                                                    QualType ObjectType,
4718                                                    NamedDecl *UnqualLookup,
4719                                                    CXXScopeSpec &SS) {
4720   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4721     return TSInfo;
4722 
4723   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4724                                    UnqualLookup, SS);
4725 }
4726 
4727 template <typename Derived>
4728 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4729     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4730     CXXScopeSpec &SS) {
4731   QualType T = TL.getType();
4732   assert(!getDerived().AlreadyTransformed(T));
4733 
4734   TypeLocBuilder TLB;
4735   QualType Result;
4736 
4737   if (isa<TemplateSpecializationType>(T)) {
4738     TemplateSpecializationTypeLoc SpecTL =
4739         TL.castAs<TemplateSpecializationTypeLoc>();
4740 
4741     TemplateName Template = getDerived().TransformTemplateName(
4742         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4743         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4744     if (Template.isNull())
4745       return nullptr;
4746 
4747     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4748                                                               Template);
4749   } else if (isa<DependentTemplateSpecializationType>(T)) {
4750     DependentTemplateSpecializationTypeLoc SpecTL =
4751         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4752 
4753     TemplateName Template
4754       = getDerived().RebuildTemplateName(SS,
4755                                          SpecTL.getTemplateKeywordLoc(),
4756                                          *SpecTL.getTypePtr()->getIdentifier(),
4757                                          SpecTL.getTemplateNameLoc(),
4758                                          ObjectType, UnqualLookup,
4759                                          /*AllowInjectedClassName*/true);
4760     if (Template.isNull())
4761       return nullptr;
4762 
4763     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4764                                                                        SpecTL,
4765                                                                        Template,
4766                                                                        SS);
4767   } else {
4768     // Nothing special needs to be done for these.
4769     Result = getDerived().TransformType(TLB, TL);
4770   }
4771 
4772   if (Result.isNull())
4773     return nullptr;
4774 
4775   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4776 }
4777 
4778 template <class TyLoc> static inline
4779 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4780   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4781   NewT.setNameLoc(T.getNameLoc());
4782   return T.getType();
4783 }
4784 
4785 template<typename Derived>
4786 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4787                                                       BuiltinTypeLoc T) {
4788   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4789   NewT.setBuiltinLoc(T.getBuiltinLoc());
4790   if (T.needsExtraLocalData())
4791     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4792   return T.getType();
4793 }
4794 
4795 template<typename Derived>
4796 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4797                                                       ComplexTypeLoc T) {
4798   // FIXME: recurse?
4799   return TransformTypeSpecType(TLB, T);
4800 }
4801 
4802 template <typename Derived>
4803 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4804                                                        AdjustedTypeLoc TL) {
4805   // Adjustments applied during transformation are handled elsewhere.
4806   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4807 }
4808 
4809 template<typename Derived>
4810 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4811                                                       DecayedTypeLoc TL) {
4812   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4813   if (OriginalType.isNull())
4814     return QualType();
4815 
4816   QualType Result = TL.getType();
4817   if (getDerived().AlwaysRebuild() ||
4818       OriginalType != TL.getOriginalLoc().getType())
4819     Result = SemaRef.Context.getDecayedType(OriginalType);
4820   TLB.push<DecayedTypeLoc>(Result);
4821   // Nothing to set for DecayedTypeLoc.
4822   return Result;
4823 }
4824 
4825 template<typename Derived>
4826 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4827                                                       PointerTypeLoc TL) {
4828   QualType PointeeType
4829     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4830   if (PointeeType.isNull())
4831     return QualType();
4832 
4833   QualType Result = TL.getType();
4834   if (PointeeType->getAs<ObjCObjectType>()) {
4835     // A dependent pointer type 'T *' has is being transformed such
4836     // that an Objective-C class type is being replaced for 'T'. The
4837     // resulting pointer type is an ObjCObjectPointerType, not a
4838     // PointerType.
4839     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4840 
4841     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4842     NewT.setStarLoc(TL.getStarLoc());
4843     return Result;
4844   }
4845 
4846   if (getDerived().AlwaysRebuild() ||
4847       PointeeType != TL.getPointeeLoc().getType()) {
4848     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4849     if (Result.isNull())
4850       return QualType();
4851   }
4852 
4853   // Objective-C ARC can add lifetime qualifiers to the type that we're
4854   // pointing to.
4855   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4856 
4857   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4858   NewT.setSigilLoc(TL.getSigilLoc());
4859   return Result;
4860 }
4861 
4862 template<typename Derived>
4863 QualType
4864 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4865                                                   BlockPointerTypeLoc TL) {
4866   QualType PointeeType
4867     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4868   if (PointeeType.isNull())
4869     return QualType();
4870 
4871   QualType Result = TL.getType();
4872   if (getDerived().AlwaysRebuild() ||
4873       PointeeType != TL.getPointeeLoc().getType()) {
4874     Result = getDerived().RebuildBlockPointerType(PointeeType,
4875                                                   TL.getSigilLoc());
4876     if (Result.isNull())
4877       return QualType();
4878   }
4879 
4880   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4881   NewT.setSigilLoc(TL.getSigilLoc());
4882   return Result;
4883 }
4884 
4885 /// Transforms a reference type.  Note that somewhat paradoxically we
4886 /// don't care whether the type itself is an l-value type or an r-value
4887 /// type;  we only care if the type was *written* as an l-value type
4888 /// or an r-value type.
4889 template<typename Derived>
4890 QualType
4891 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4892                                                ReferenceTypeLoc TL) {
4893   const ReferenceType *T = TL.getTypePtr();
4894 
4895   // Note that this works with the pointee-as-written.
4896   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4897   if (PointeeType.isNull())
4898     return QualType();
4899 
4900   QualType Result = TL.getType();
4901   if (getDerived().AlwaysRebuild() ||
4902       PointeeType != T->getPointeeTypeAsWritten()) {
4903     Result = getDerived().RebuildReferenceType(PointeeType,
4904                                                T->isSpelledAsLValue(),
4905                                                TL.getSigilLoc());
4906     if (Result.isNull())
4907       return QualType();
4908   }
4909 
4910   // Objective-C ARC can add lifetime qualifiers to the type that we're
4911   // referring to.
4912   TLB.TypeWasModifiedSafely(
4913       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
4914 
4915   // r-value references can be rebuilt as l-value references.
4916   ReferenceTypeLoc NewTL;
4917   if (isa<LValueReferenceType>(Result))
4918     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4919   else
4920     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4921   NewTL.setSigilLoc(TL.getSigilLoc());
4922 
4923   return Result;
4924 }
4925 
4926 template<typename Derived>
4927 QualType
4928 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4929                                                  LValueReferenceTypeLoc TL) {
4930   return TransformReferenceType(TLB, TL);
4931 }
4932 
4933 template<typename Derived>
4934 QualType
4935 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4936                                                  RValueReferenceTypeLoc TL) {
4937   return TransformReferenceType(TLB, TL);
4938 }
4939 
4940 template<typename Derived>
4941 QualType
4942 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4943                                                    MemberPointerTypeLoc TL) {
4944   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4945   if (PointeeType.isNull())
4946     return QualType();
4947 
4948   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4949   TypeSourceInfo *NewClsTInfo = nullptr;
4950   if (OldClsTInfo) {
4951     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4952     if (!NewClsTInfo)
4953       return QualType();
4954   }
4955 
4956   const MemberPointerType *T = TL.getTypePtr();
4957   QualType OldClsType = QualType(T->getClass(), 0);
4958   QualType NewClsType;
4959   if (NewClsTInfo)
4960     NewClsType = NewClsTInfo->getType();
4961   else {
4962     NewClsType = getDerived().TransformType(OldClsType);
4963     if (NewClsType.isNull())
4964       return QualType();
4965   }
4966 
4967   QualType Result = TL.getType();
4968   if (getDerived().AlwaysRebuild() ||
4969       PointeeType != T->getPointeeType() ||
4970       NewClsType != OldClsType) {
4971     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4972                                                    TL.getStarLoc());
4973     if (Result.isNull())
4974       return QualType();
4975   }
4976 
4977   // If we had to adjust the pointee type when building a member pointer, make
4978   // sure to push TypeLoc info for it.
4979   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4980   if (MPT && PointeeType != MPT->getPointeeType()) {
4981     assert(isa<AdjustedType>(MPT->getPointeeType()));
4982     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4983   }
4984 
4985   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4986   NewTL.setSigilLoc(TL.getSigilLoc());
4987   NewTL.setClassTInfo(NewClsTInfo);
4988 
4989   return Result;
4990 }
4991 
4992 template<typename Derived>
4993 QualType
4994 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4995                                                    ConstantArrayTypeLoc TL) {
4996   const ConstantArrayType *T = TL.getTypePtr();
4997   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4998   if (ElementType.isNull())
4999     return QualType();
5000 
5001   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5002   Expr *OldSize = TL.getSizeExpr();
5003   if (!OldSize)
5004     OldSize = const_cast<Expr*>(T->getSizeExpr());
5005   Expr *NewSize = nullptr;
5006   if (OldSize) {
5007     EnterExpressionEvaluationContext Unevaluated(
5008         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5009     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5010     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5011   }
5012 
5013   QualType Result = TL.getType();
5014   if (getDerived().AlwaysRebuild() ||
5015       ElementType != T->getElementType() ||
5016       (T->getSizeExpr() && NewSize != OldSize)) {
5017     Result = getDerived().RebuildConstantArrayType(ElementType,
5018                                                    T->getSizeModifier(),
5019                                                    T->getSize(), NewSize,
5020                                              T->getIndexTypeCVRQualifiers(),
5021                                                    TL.getBracketsRange());
5022     if (Result.isNull())
5023       return QualType();
5024   }
5025 
5026   // We might have either a ConstantArrayType or a VariableArrayType now:
5027   // a ConstantArrayType is allowed to have an element type which is a
5028   // VariableArrayType if the type is dependent.  Fortunately, all array
5029   // types have the same location layout.
5030   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5031   NewTL.setLBracketLoc(TL.getLBracketLoc());
5032   NewTL.setRBracketLoc(TL.getRBracketLoc());
5033   NewTL.setSizeExpr(NewSize);
5034 
5035   return Result;
5036 }
5037 
5038 template<typename Derived>
5039 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5040                                               TypeLocBuilder &TLB,
5041                                               IncompleteArrayTypeLoc TL) {
5042   const IncompleteArrayType *T = TL.getTypePtr();
5043   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5044   if (ElementType.isNull())
5045     return QualType();
5046 
5047   QualType Result = TL.getType();
5048   if (getDerived().AlwaysRebuild() ||
5049       ElementType != T->getElementType()) {
5050     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5051                                                      T->getSizeModifier(),
5052                                            T->getIndexTypeCVRQualifiers(),
5053                                                      TL.getBracketsRange());
5054     if (Result.isNull())
5055       return QualType();
5056   }
5057 
5058   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5059   NewTL.setLBracketLoc(TL.getLBracketLoc());
5060   NewTL.setRBracketLoc(TL.getRBracketLoc());
5061   NewTL.setSizeExpr(nullptr);
5062 
5063   return Result;
5064 }
5065 
5066 template<typename Derived>
5067 QualType
5068 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5069                                                    VariableArrayTypeLoc TL) {
5070   const VariableArrayType *T = TL.getTypePtr();
5071   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5072   if (ElementType.isNull())
5073     return QualType();
5074 
5075   ExprResult SizeResult;
5076   {
5077     EnterExpressionEvaluationContext Context(
5078         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5079     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5080   }
5081   if (SizeResult.isInvalid())
5082     return QualType();
5083   SizeResult =
5084       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5085   if (SizeResult.isInvalid())
5086     return QualType();
5087 
5088   Expr *Size = SizeResult.get();
5089 
5090   QualType Result = TL.getType();
5091   if (getDerived().AlwaysRebuild() ||
5092       ElementType != T->getElementType() ||
5093       Size != T->getSizeExpr()) {
5094     Result = getDerived().RebuildVariableArrayType(ElementType,
5095                                                    T->getSizeModifier(),
5096                                                    Size,
5097                                              T->getIndexTypeCVRQualifiers(),
5098                                                    TL.getBracketsRange());
5099     if (Result.isNull())
5100       return QualType();
5101   }
5102 
5103   // We might have constant size array now, but fortunately it has the same
5104   // location layout.
5105   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5106   NewTL.setLBracketLoc(TL.getLBracketLoc());
5107   NewTL.setRBracketLoc(TL.getRBracketLoc());
5108   NewTL.setSizeExpr(Size);
5109 
5110   return Result;
5111 }
5112 
5113 template<typename Derived>
5114 QualType
5115 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5116                                              DependentSizedArrayTypeLoc TL) {
5117   const DependentSizedArrayType *T = TL.getTypePtr();
5118   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5119   if (ElementType.isNull())
5120     return QualType();
5121 
5122   // Array bounds are constant expressions.
5123   EnterExpressionEvaluationContext Unevaluated(
5124       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5125 
5126   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5127   Expr *origSize = TL.getSizeExpr();
5128   if (!origSize) origSize = T->getSizeExpr();
5129 
5130   ExprResult sizeResult
5131     = getDerived().TransformExpr(origSize);
5132   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5133   if (sizeResult.isInvalid())
5134     return QualType();
5135 
5136   Expr *size = sizeResult.get();
5137 
5138   QualType Result = TL.getType();
5139   if (getDerived().AlwaysRebuild() ||
5140       ElementType != T->getElementType() ||
5141       size != origSize) {
5142     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5143                                                          T->getSizeModifier(),
5144                                                          size,
5145                                                 T->getIndexTypeCVRQualifiers(),
5146                                                         TL.getBracketsRange());
5147     if (Result.isNull())
5148       return QualType();
5149   }
5150 
5151   // We might have any sort of array type now, but fortunately they
5152   // all have the same location layout.
5153   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5154   NewTL.setLBracketLoc(TL.getLBracketLoc());
5155   NewTL.setRBracketLoc(TL.getRBracketLoc());
5156   NewTL.setSizeExpr(size);
5157 
5158   return Result;
5159 }
5160 
5161 template <typename Derived>
5162 QualType TreeTransform<Derived>::TransformDependentVectorType(
5163     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5164   const DependentVectorType *T = TL.getTypePtr();
5165   QualType ElementType = getDerived().TransformType(T->getElementType());
5166   if (ElementType.isNull())
5167     return QualType();
5168 
5169   EnterExpressionEvaluationContext Unevaluated(
5170       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5171 
5172   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5173   Size = SemaRef.ActOnConstantExpression(Size);
5174   if (Size.isInvalid())
5175     return QualType();
5176 
5177   QualType Result = TL.getType();
5178   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5179       Size.get() != T->getSizeExpr()) {
5180     Result = getDerived().RebuildDependentVectorType(
5181         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5182     if (Result.isNull())
5183       return QualType();
5184   }
5185 
5186   // Result might be dependent or not.
5187   if (isa<DependentVectorType>(Result)) {
5188     DependentVectorTypeLoc NewTL =
5189         TLB.push<DependentVectorTypeLoc>(Result);
5190     NewTL.setNameLoc(TL.getNameLoc());
5191   } else {
5192     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5193     NewTL.setNameLoc(TL.getNameLoc());
5194   }
5195 
5196   return Result;
5197 }
5198 
5199 template<typename Derived>
5200 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5201                                       TypeLocBuilder &TLB,
5202                                       DependentSizedExtVectorTypeLoc TL) {
5203   const DependentSizedExtVectorType *T = TL.getTypePtr();
5204 
5205   // FIXME: ext vector locs should be nested
5206   QualType ElementType = getDerived().TransformType(T->getElementType());
5207   if (ElementType.isNull())
5208     return QualType();
5209 
5210   // Vector sizes are constant expressions.
5211   EnterExpressionEvaluationContext Unevaluated(
5212       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5213 
5214   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5215   Size = SemaRef.ActOnConstantExpression(Size);
5216   if (Size.isInvalid())
5217     return QualType();
5218 
5219   QualType Result = TL.getType();
5220   if (getDerived().AlwaysRebuild() ||
5221       ElementType != T->getElementType() ||
5222       Size.get() != T->getSizeExpr()) {
5223     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5224                                                              Size.get(),
5225                                                          T->getAttributeLoc());
5226     if (Result.isNull())
5227       return QualType();
5228   }
5229 
5230   // Result might be dependent or not.
5231   if (isa<DependentSizedExtVectorType>(Result)) {
5232     DependentSizedExtVectorTypeLoc NewTL
5233       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5234     NewTL.setNameLoc(TL.getNameLoc());
5235   } else {
5236     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5237     NewTL.setNameLoc(TL.getNameLoc());
5238   }
5239 
5240   return Result;
5241 }
5242 
5243 template <typename Derived>
5244 QualType
5245 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5246                                                     ConstantMatrixTypeLoc TL) {
5247   const ConstantMatrixType *T = TL.getTypePtr();
5248   QualType ElementType = getDerived().TransformType(T->getElementType());
5249   if (ElementType.isNull())
5250     return QualType();
5251 
5252   QualType Result = TL.getType();
5253   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5254     Result = getDerived().RebuildConstantMatrixType(
5255         ElementType, T->getNumRows(), T->getNumColumns());
5256     if (Result.isNull())
5257       return QualType();
5258   }
5259 
5260   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5261   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5262   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5263   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5264   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5265 
5266   return Result;
5267 }
5268 
5269 template <typename Derived>
5270 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5271     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5272   const DependentSizedMatrixType *T = TL.getTypePtr();
5273 
5274   QualType ElementType = getDerived().TransformType(T->getElementType());
5275   if (ElementType.isNull()) {
5276     return QualType();
5277   }
5278 
5279   // Matrix dimensions are constant expressions.
5280   EnterExpressionEvaluationContext Unevaluated(
5281       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5282 
5283   Expr *origRows = TL.getAttrRowOperand();
5284   if (!origRows)
5285     origRows = T->getRowExpr();
5286   Expr *origColumns = TL.getAttrColumnOperand();
5287   if (!origColumns)
5288     origColumns = T->getColumnExpr();
5289 
5290   ExprResult rowResult = getDerived().TransformExpr(origRows);
5291   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5292   if (rowResult.isInvalid())
5293     return QualType();
5294 
5295   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5296   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5297   if (columnResult.isInvalid())
5298     return QualType();
5299 
5300   Expr *rows = rowResult.get();
5301   Expr *columns = columnResult.get();
5302 
5303   QualType Result = TL.getType();
5304   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5305       rows != origRows || columns != origColumns) {
5306     Result = getDerived().RebuildDependentSizedMatrixType(
5307         ElementType, rows, columns, T->getAttributeLoc());
5308 
5309     if (Result.isNull())
5310       return QualType();
5311   }
5312 
5313   // We might have any sort of matrix type now, but fortunately they
5314   // all have the same location layout.
5315   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5316   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5317   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5318   NewTL.setAttrRowOperand(rows);
5319   NewTL.setAttrColumnOperand(columns);
5320   return Result;
5321 }
5322 
5323 template <typename Derived>
5324 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5325     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5326   const DependentAddressSpaceType *T = TL.getTypePtr();
5327 
5328   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5329 
5330   if (pointeeType.isNull())
5331     return QualType();
5332 
5333   // Address spaces are constant expressions.
5334   EnterExpressionEvaluationContext Unevaluated(
5335       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5336 
5337   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5338   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5339   if (AddrSpace.isInvalid())
5340     return QualType();
5341 
5342   QualType Result = TL.getType();
5343   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5344       AddrSpace.get() != T->getAddrSpaceExpr()) {
5345     Result = getDerived().RebuildDependentAddressSpaceType(
5346         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5347     if (Result.isNull())
5348       return QualType();
5349   }
5350 
5351   // Result might be dependent or not.
5352   if (isa<DependentAddressSpaceType>(Result)) {
5353     DependentAddressSpaceTypeLoc NewTL =
5354         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5355 
5356     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5357     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5358     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5359 
5360   } else {
5361     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5362         Result, getDerived().getBaseLocation());
5363     TransformType(TLB, DI->getTypeLoc());
5364   }
5365 
5366   return Result;
5367 }
5368 
5369 template <typename Derived>
5370 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5371                                                      VectorTypeLoc TL) {
5372   const VectorType *T = TL.getTypePtr();
5373   QualType ElementType = getDerived().TransformType(T->getElementType());
5374   if (ElementType.isNull())
5375     return QualType();
5376 
5377   QualType Result = TL.getType();
5378   if (getDerived().AlwaysRebuild() ||
5379       ElementType != T->getElementType()) {
5380     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5381                                             T->getVectorKind());
5382     if (Result.isNull())
5383       return QualType();
5384   }
5385 
5386   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5387   NewTL.setNameLoc(TL.getNameLoc());
5388 
5389   return Result;
5390 }
5391 
5392 template<typename Derived>
5393 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5394                                                         ExtVectorTypeLoc TL) {
5395   const VectorType *T = TL.getTypePtr();
5396   QualType ElementType = getDerived().TransformType(T->getElementType());
5397   if (ElementType.isNull())
5398     return QualType();
5399 
5400   QualType Result = TL.getType();
5401   if (getDerived().AlwaysRebuild() ||
5402       ElementType != T->getElementType()) {
5403     Result = getDerived().RebuildExtVectorType(ElementType,
5404                                                T->getNumElements(),
5405                                                /*FIXME*/ SourceLocation());
5406     if (Result.isNull())
5407       return QualType();
5408   }
5409 
5410   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5411   NewTL.setNameLoc(TL.getNameLoc());
5412 
5413   return Result;
5414 }
5415 
5416 template <typename Derived>
5417 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5418     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5419     bool ExpectParameterPack) {
5420   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5421   TypeSourceInfo *NewDI = nullptr;
5422 
5423   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5424     // If we're substituting into a pack expansion type and we know the
5425     // length we want to expand to, just substitute for the pattern.
5426     TypeLoc OldTL = OldDI->getTypeLoc();
5427     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5428 
5429     TypeLocBuilder TLB;
5430     TypeLoc NewTL = OldDI->getTypeLoc();
5431     TLB.reserve(NewTL.getFullDataSize());
5432 
5433     QualType Result = getDerived().TransformType(TLB,
5434                                                OldExpansionTL.getPatternLoc());
5435     if (Result.isNull())
5436       return nullptr;
5437 
5438     Result = RebuildPackExpansionType(Result,
5439                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5440                                       OldExpansionTL.getEllipsisLoc(),
5441                                       NumExpansions);
5442     if (Result.isNull())
5443       return nullptr;
5444 
5445     PackExpansionTypeLoc NewExpansionTL
5446       = TLB.push<PackExpansionTypeLoc>(Result);
5447     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5448     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5449   } else
5450     NewDI = getDerived().TransformType(OldDI);
5451   if (!NewDI)
5452     return nullptr;
5453 
5454   if (NewDI == OldDI && indexAdjustment == 0)
5455     return OldParm;
5456 
5457   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5458                                              OldParm->getDeclContext(),
5459                                              OldParm->getInnerLocStart(),
5460                                              OldParm->getLocation(),
5461                                              OldParm->getIdentifier(),
5462                                              NewDI->getType(),
5463                                              NewDI,
5464                                              OldParm->getStorageClass(),
5465                                              /* DefArg */ nullptr);
5466   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5467                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5468   return newParm;
5469 }
5470 
5471 template <typename Derived>
5472 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5473     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5474     const QualType *ParamTypes,
5475     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5476     SmallVectorImpl<QualType> &OutParamTypes,
5477     SmallVectorImpl<ParmVarDecl *> *PVars,
5478     Sema::ExtParameterInfoBuilder &PInfos) {
5479   int indexAdjustment = 0;
5480 
5481   unsigned NumParams = Params.size();
5482   for (unsigned i = 0; i != NumParams; ++i) {
5483     if (ParmVarDecl *OldParm = Params[i]) {
5484       assert(OldParm->getFunctionScopeIndex() == i);
5485 
5486       Optional<unsigned> NumExpansions;
5487       ParmVarDecl *NewParm = nullptr;
5488       if (OldParm->isParameterPack()) {
5489         // We have a function parameter pack that may need to be expanded.
5490         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5491 
5492         // Find the parameter packs that could be expanded.
5493         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5494         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5495         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5496         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5497 
5498         // Determine whether we should expand the parameter packs.
5499         bool ShouldExpand = false;
5500         bool RetainExpansion = false;
5501         Optional<unsigned> OrigNumExpansions;
5502         if (Unexpanded.size() > 0) {
5503           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5504           NumExpansions = OrigNumExpansions;
5505           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5506                                                    Pattern.getSourceRange(),
5507                                                    Unexpanded,
5508                                                    ShouldExpand,
5509                                                    RetainExpansion,
5510                                                    NumExpansions)) {
5511             return true;
5512           }
5513         } else {
5514 #ifndef NDEBUG
5515           const AutoType *AT =
5516               Pattern.getType().getTypePtr()->getContainedAutoType();
5517           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5518                  "Could not find parameter packs or undeduced auto type!");
5519 #endif
5520         }
5521 
5522         if (ShouldExpand) {
5523           // Expand the function parameter pack into multiple, separate
5524           // parameters.
5525           getDerived().ExpandingFunctionParameterPack(OldParm);
5526           for (unsigned I = 0; I != *NumExpansions; ++I) {
5527             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5528             ParmVarDecl *NewParm
5529               = getDerived().TransformFunctionTypeParam(OldParm,
5530                                                         indexAdjustment++,
5531                                                         OrigNumExpansions,
5532                                                 /*ExpectParameterPack=*/false);
5533             if (!NewParm)
5534               return true;
5535 
5536             if (ParamInfos)
5537               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5538             OutParamTypes.push_back(NewParm->getType());
5539             if (PVars)
5540               PVars->push_back(NewParm);
5541           }
5542 
5543           // If we're supposed to retain a pack expansion, do so by temporarily
5544           // forgetting the partially-substituted parameter pack.
5545           if (RetainExpansion) {
5546             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5547             ParmVarDecl *NewParm
5548               = getDerived().TransformFunctionTypeParam(OldParm,
5549                                                         indexAdjustment++,
5550                                                         OrigNumExpansions,
5551                                                 /*ExpectParameterPack=*/false);
5552             if (!NewParm)
5553               return true;
5554 
5555             if (ParamInfos)
5556               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5557             OutParamTypes.push_back(NewParm->getType());
5558             if (PVars)
5559               PVars->push_back(NewParm);
5560           }
5561 
5562           // The next parameter should have the same adjustment as the
5563           // last thing we pushed, but we post-incremented indexAdjustment
5564           // on every push.  Also, if we push nothing, the adjustment should
5565           // go down by one.
5566           indexAdjustment--;
5567 
5568           // We're done with the pack expansion.
5569           continue;
5570         }
5571 
5572         // We'll substitute the parameter now without expanding the pack
5573         // expansion.
5574         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5575         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5576                                                           indexAdjustment,
5577                                                           NumExpansions,
5578                                                   /*ExpectParameterPack=*/true);
5579         assert(NewParm->isParameterPack() &&
5580                "Parameter pack no longer a parameter pack after "
5581                "transformation.");
5582       } else {
5583         NewParm = getDerived().TransformFunctionTypeParam(
5584             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5585       }
5586 
5587       if (!NewParm)
5588         return true;
5589 
5590       if (ParamInfos)
5591         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5592       OutParamTypes.push_back(NewParm->getType());
5593       if (PVars)
5594         PVars->push_back(NewParm);
5595       continue;
5596     }
5597 
5598     // Deal with the possibility that we don't have a parameter
5599     // declaration for this parameter.
5600     QualType OldType = ParamTypes[i];
5601     bool IsPackExpansion = false;
5602     Optional<unsigned> NumExpansions;
5603     QualType NewType;
5604     if (const PackExpansionType *Expansion
5605                                        = dyn_cast<PackExpansionType>(OldType)) {
5606       // We have a function parameter pack that may need to be expanded.
5607       QualType Pattern = Expansion->getPattern();
5608       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5609       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5610 
5611       // Determine whether we should expand the parameter packs.
5612       bool ShouldExpand = false;
5613       bool RetainExpansion = false;
5614       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5615                                                Unexpanded,
5616                                                ShouldExpand,
5617                                                RetainExpansion,
5618                                                NumExpansions)) {
5619         return true;
5620       }
5621 
5622       if (ShouldExpand) {
5623         // Expand the function parameter pack into multiple, separate
5624         // parameters.
5625         for (unsigned I = 0; I != *NumExpansions; ++I) {
5626           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5627           QualType NewType = getDerived().TransformType(Pattern);
5628           if (NewType.isNull())
5629             return true;
5630 
5631           if (NewType->containsUnexpandedParameterPack()) {
5632             NewType =
5633                 getSema().getASTContext().getPackExpansionType(NewType, None);
5634 
5635             if (NewType.isNull())
5636               return true;
5637           }
5638 
5639           if (ParamInfos)
5640             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5641           OutParamTypes.push_back(NewType);
5642           if (PVars)
5643             PVars->push_back(nullptr);
5644         }
5645 
5646         // We're done with the pack expansion.
5647         continue;
5648       }
5649 
5650       // If we're supposed to retain a pack expansion, do so by temporarily
5651       // forgetting the partially-substituted parameter pack.
5652       if (RetainExpansion) {
5653         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5654         QualType NewType = getDerived().TransformType(Pattern);
5655         if (NewType.isNull())
5656           return true;
5657 
5658         if (ParamInfos)
5659           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5660         OutParamTypes.push_back(NewType);
5661         if (PVars)
5662           PVars->push_back(nullptr);
5663       }
5664 
5665       // We'll substitute the parameter now without expanding the pack
5666       // expansion.
5667       OldType = Expansion->getPattern();
5668       IsPackExpansion = true;
5669       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5670       NewType = getDerived().TransformType(OldType);
5671     } else {
5672       NewType = getDerived().TransformType(OldType);
5673     }
5674 
5675     if (NewType.isNull())
5676       return true;
5677 
5678     if (IsPackExpansion)
5679       NewType = getSema().Context.getPackExpansionType(NewType,
5680                                                        NumExpansions);
5681 
5682     if (ParamInfos)
5683       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5684     OutParamTypes.push_back(NewType);
5685     if (PVars)
5686       PVars->push_back(nullptr);
5687   }
5688 
5689 #ifndef NDEBUG
5690   if (PVars) {
5691     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5692       if (ParmVarDecl *parm = (*PVars)[i])
5693         assert(parm->getFunctionScopeIndex() == i);
5694   }
5695 #endif
5696 
5697   return false;
5698 }
5699 
5700 template<typename Derived>
5701 QualType
5702 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5703                                                    FunctionProtoTypeLoc TL) {
5704   SmallVector<QualType, 4> ExceptionStorage;
5705   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5706   return getDerived().TransformFunctionProtoType(
5707       TLB, TL, nullptr, Qualifiers(),
5708       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5709         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5710                                             ExceptionStorage, Changed);
5711       });
5712 }
5713 
5714 template<typename Derived> template<typename Fn>
5715 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5716     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5717     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5718 
5719   // Transform the parameters and return type.
5720   //
5721   // We are required to instantiate the params and return type in source order.
5722   // When the function has a trailing return type, we instantiate the
5723   // parameters before the return type,  since the return type can then refer
5724   // to the parameters themselves (via decltype, sizeof, etc.).
5725   //
5726   SmallVector<QualType, 4> ParamTypes;
5727   SmallVector<ParmVarDecl*, 4> ParamDecls;
5728   Sema::ExtParameterInfoBuilder ExtParamInfos;
5729   const FunctionProtoType *T = TL.getTypePtr();
5730 
5731   QualType ResultType;
5732 
5733   if (T->hasTrailingReturn()) {
5734     if (getDerived().TransformFunctionTypeParams(
5735             TL.getBeginLoc(), TL.getParams(),
5736             TL.getTypePtr()->param_type_begin(),
5737             T->getExtParameterInfosOrNull(),
5738             ParamTypes, &ParamDecls, ExtParamInfos))
5739       return QualType();
5740 
5741     {
5742       // C++11 [expr.prim.general]p3:
5743       //   If a declaration declares a member function or member function
5744       //   template of a class X, the expression this is a prvalue of type
5745       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5746       //   and the end of the function-definition, member-declarator, or
5747       //   declarator.
5748       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5749 
5750       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5751       if (ResultType.isNull())
5752         return QualType();
5753     }
5754   }
5755   else {
5756     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5757     if (ResultType.isNull())
5758       return QualType();
5759 
5760     if (getDerived().TransformFunctionTypeParams(
5761             TL.getBeginLoc(), TL.getParams(),
5762             TL.getTypePtr()->param_type_begin(),
5763             T->getExtParameterInfosOrNull(),
5764             ParamTypes, &ParamDecls, ExtParamInfos))
5765       return QualType();
5766   }
5767 
5768   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5769 
5770   bool EPIChanged = false;
5771   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5772     return QualType();
5773 
5774   // Handle extended parameter information.
5775   if (auto NewExtParamInfos =
5776         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5777     if (!EPI.ExtParameterInfos ||
5778         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5779           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5780       EPIChanged = true;
5781     }
5782     EPI.ExtParameterInfos = NewExtParamInfos;
5783   } else if (EPI.ExtParameterInfos) {
5784     EPIChanged = true;
5785     EPI.ExtParameterInfos = nullptr;
5786   }
5787 
5788   QualType Result = TL.getType();
5789   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5790       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5791     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5792     if (Result.isNull())
5793       return QualType();
5794   }
5795 
5796   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5797   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5798   NewTL.setLParenLoc(TL.getLParenLoc());
5799   NewTL.setRParenLoc(TL.getRParenLoc());
5800   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5801   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5802   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5803     NewTL.setParam(i, ParamDecls[i]);
5804 
5805   return Result;
5806 }
5807 
5808 template<typename Derived>
5809 bool TreeTransform<Derived>::TransformExceptionSpec(
5810     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5811     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5812   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5813 
5814   // Instantiate a dynamic noexcept expression, if any.
5815   if (isComputedNoexcept(ESI.Type)) {
5816     EnterExpressionEvaluationContext Unevaluated(
5817         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5818     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5819     if (NoexceptExpr.isInvalid())
5820       return true;
5821 
5822     ExceptionSpecificationType EST = ESI.Type;
5823     NoexceptExpr =
5824         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5825     if (NoexceptExpr.isInvalid())
5826       return true;
5827 
5828     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5829       Changed = true;
5830     ESI.NoexceptExpr = NoexceptExpr.get();
5831     ESI.Type = EST;
5832   }
5833 
5834   if (ESI.Type != EST_Dynamic)
5835     return false;
5836 
5837   // Instantiate a dynamic exception specification's type.
5838   for (QualType T : ESI.Exceptions) {
5839     if (const PackExpansionType *PackExpansion =
5840             T->getAs<PackExpansionType>()) {
5841       Changed = true;
5842 
5843       // We have a pack expansion. Instantiate it.
5844       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5845       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5846                                               Unexpanded);
5847       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5848 
5849       // Determine whether the set of unexpanded parameter packs can and
5850       // should
5851       // be expanded.
5852       bool Expand = false;
5853       bool RetainExpansion = false;
5854       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5855       // FIXME: Track the location of the ellipsis (and track source location
5856       // information for the types in the exception specification in general).
5857       if (getDerived().TryExpandParameterPacks(
5858               Loc, SourceRange(), Unexpanded, Expand,
5859               RetainExpansion, NumExpansions))
5860         return true;
5861 
5862       if (!Expand) {
5863         // We can't expand this pack expansion into separate arguments yet;
5864         // just substitute into the pattern and create a new pack expansion
5865         // type.
5866         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5867         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5868         if (U.isNull())
5869           return true;
5870 
5871         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5872         Exceptions.push_back(U);
5873         continue;
5874       }
5875 
5876       // Substitute into the pack expansion pattern for each slice of the
5877       // pack.
5878       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5879         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5880 
5881         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5882         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5883           return true;
5884 
5885         Exceptions.push_back(U);
5886       }
5887     } else {
5888       QualType U = getDerived().TransformType(T);
5889       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5890         return true;
5891       if (T != U)
5892         Changed = true;
5893 
5894       Exceptions.push_back(U);
5895     }
5896   }
5897 
5898   ESI.Exceptions = Exceptions;
5899   if (ESI.Exceptions.empty())
5900     ESI.Type = EST_DynamicNone;
5901   return false;
5902 }
5903 
5904 template<typename Derived>
5905 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5906                                                  TypeLocBuilder &TLB,
5907                                                  FunctionNoProtoTypeLoc TL) {
5908   const FunctionNoProtoType *T = TL.getTypePtr();
5909   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5910   if (ResultType.isNull())
5911     return QualType();
5912 
5913   QualType Result = TL.getType();
5914   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5915     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5916 
5917   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5918   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5919   NewTL.setLParenLoc(TL.getLParenLoc());
5920   NewTL.setRParenLoc(TL.getRParenLoc());
5921   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5922 
5923   return Result;
5924 }
5925 
5926 template<typename Derived> QualType
5927 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5928                                                  UnresolvedUsingTypeLoc TL) {
5929   const UnresolvedUsingType *T = TL.getTypePtr();
5930   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5931   if (!D)
5932     return QualType();
5933 
5934   QualType Result = TL.getType();
5935   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5936     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5937     if (Result.isNull())
5938       return QualType();
5939   }
5940 
5941   // We might get an arbitrary type spec type back.  We should at
5942   // least always get a type spec type, though.
5943   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5944   NewTL.setNameLoc(TL.getNameLoc());
5945 
5946   return Result;
5947 }
5948 
5949 template<typename Derived>
5950 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5951                                                       TypedefTypeLoc TL) {
5952   const TypedefType *T = TL.getTypePtr();
5953   TypedefNameDecl *Typedef
5954     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5955                                                                T->getDecl()));
5956   if (!Typedef)
5957     return QualType();
5958 
5959   QualType Result = TL.getType();
5960   if (getDerived().AlwaysRebuild() ||
5961       Typedef != T->getDecl()) {
5962     Result = getDerived().RebuildTypedefType(Typedef);
5963     if (Result.isNull())
5964       return QualType();
5965   }
5966 
5967   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5968   NewTL.setNameLoc(TL.getNameLoc());
5969 
5970   return Result;
5971 }
5972 
5973 template<typename Derived>
5974 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5975                                                       TypeOfExprTypeLoc TL) {
5976   // typeof expressions are not potentially evaluated contexts
5977   EnterExpressionEvaluationContext Unevaluated(
5978       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5979       Sema::ReuseLambdaContextDecl);
5980 
5981   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5982   if (E.isInvalid())
5983     return QualType();
5984 
5985   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5986   if (E.isInvalid())
5987     return QualType();
5988 
5989   QualType Result = TL.getType();
5990   if (getDerived().AlwaysRebuild() ||
5991       E.get() != TL.getUnderlyingExpr()) {
5992     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5993     if (Result.isNull())
5994       return QualType();
5995   }
5996   else E.get();
5997 
5998   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5999   NewTL.setTypeofLoc(TL.getTypeofLoc());
6000   NewTL.setLParenLoc(TL.getLParenLoc());
6001   NewTL.setRParenLoc(TL.getRParenLoc());
6002 
6003   return Result;
6004 }
6005 
6006 template<typename Derived>
6007 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6008                                                      TypeOfTypeLoc TL) {
6009   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
6010   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6011   if (!New_Under_TI)
6012     return QualType();
6013 
6014   QualType Result = TL.getType();
6015   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6016     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
6017     if (Result.isNull())
6018       return QualType();
6019   }
6020 
6021   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6022   NewTL.setTypeofLoc(TL.getTypeofLoc());
6023   NewTL.setLParenLoc(TL.getLParenLoc());
6024   NewTL.setRParenLoc(TL.getRParenLoc());
6025   NewTL.setUnderlyingTInfo(New_Under_TI);
6026 
6027   return Result;
6028 }
6029 
6030 template<typename Derived>
6031 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6032                                                        DecltypeTypeLoc TL) {
6033   const DecltypeType *T = TL.getTypePtr();
6034 
6035   // decltype expressions are not potentially evaluated contexts
6036   EnterExpressionEvaluationContext Unevaluated(
6037       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6038       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6039 
6040   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6041   if (E.isInvalid())
6042     return QualType();
6043 
6044   E = getSema().ActOnDecltypeExpression(E.get());
6045   if (E.isInvalid())
6046     return QualType();
6047 
6048   QualType Result = TL.getType();
6049   if (getDerived().AlwaysRebuild() ||
6050       E.get() != T->getUnderlyingExpr()) {
6051     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
6052     if (Result.isNull())
6053       return QualType();
6054   }
6055   else E.get();
6056 
6057   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6058   NewTL.setNameLoc(TL.getNameLoc());
6059 
6060   return Result;
6061 }
6062 
6063 template<typename Derived>
6064 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6065                                                             TypeLocBuilder &TLB,
6066                                                      UnaryTransformTypeLoc TL) {
6067   QualType Result = TL.getType();
6068   if (Result->isDependentType()) {
6069     const UnaryTransformType *T = TL.getTypePtr();
6070     QualType NewBase =
6071       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6072     Result = getDerived().RebuildUnaryTransformType(NewBase,
6073                                                     T->getUTTKind(),
6074                                                     TL.getKWLoc());
6075     if (Result.isNull())
6076       return QualType();
6077   }
6078 
6079   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6080   NewTL.setKWLoc(TL.getKWLoc());
6081   NewTL.setParensRange(TL.getParensRange());
6082   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6083   return Result;
6084 }
6085 
6086 template<typename Derived>
6087 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6088     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6089   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6090 
6091   CXXScopeSpec SS;
6092   TemplateName TemplateName = getDerived().TransformTemplateName(
6093       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6094   if (TemplateName.isNull())
6095     return QualType();
6096 
6097   QualType OldDeduced = T->getDeducedType();
6098   QualType NewDeduced;
6099   if (!OldDeduced.isNull()) {
6100     NewDeduced = getDerived().TransformType(OldDeduced);
6101     if (NewDeduced.isNull())
6102       return QualType();
6103   }
6104 
6105   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6106       TemplateName, NewDeduced);
6107   if (Result.isNull())
6108     return QualType();
6109 
6110   DeducedTemplateSpecializationTypeLoc NewTL =
6111       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6112   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6113 
6114   return Result;
6115 }
6116 
6117 template<typename Derived>
6118 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6119                                                      RecordTypeLoc TL) {
6120   const RecordType *T = TL.getTypePtr();
6121   RecordDecl *Record
6122     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6123                                                           T->getDecl()));
6124   if (!Record)
6125     return QualType();
6126 
6127   QualType Result = TL.getType();
6128   if (getDerived().AlwaysRebuild() ||
6129       Record != T->getDecl()) {
6130     Result = getDerived().RebuildRecordType(Record);
6131     if (Result.isNull())
6132       return QualType();
6133   }
6134 
6135   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6136   NewTL.setNameLoc(TL.getNameLoc());
6137 
6138   return Result;
6139 }
6140 
6141 template<typename Derived>
6142 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6143                                                    EnumTypeLoc TL) {
6144   const EnumType *T = TL.getTypePtr();
6145   EnumDecl *Enum
6146     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6147                                                         T->getDecl()));
6148   if (!Enum)
6149     return QualType();
6150 
6151   QualType Result = TL.getType();
6152   if (getDerived().AlwaysRebuild() ||
6153       Enum != T->getDecl()) {
6154     Result = getDerived().RebuildEnumType(Enum);
6155     if (Result.isNull())
6156       return QualType();
6157   }
6158 
6159   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6160   NewTL.setNameLoc(TL.getNameLoc());
6161 
6162   return Result;
6163 }
6164 
6165 template<typename Derived>
6166 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6167                                          TypeLocBuilder &TLB,
6168                                          InjectedClassNameTypeLoc TL) {
6169   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6170                                        TL.getTypePtr()->getDecl());
6171   if (!D) return QualType();
6172 
6173   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6174   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6175   return T;
6176 }
6177 
6178 template<typename Derived>
6179 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6180                                                 TypeLocBuilder &TLB,
6181                                                 TemplateTypeParmTypeLoc TL) {
6182   return TransformTypeSpecType(TLB, TL);
6183 }
6184 
6185 template<typename Derived>
6186 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6187                                          TypeLocBuilder &TLB,
6188                                          SubstTemplateTypeParmTypeLoc TL) {
6189   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6190 
6191   // Substitute into the replacement type, which itself might involve something
6192   // that needs to be transformed. This only tends to occur with default
6193   // template arguments of template template parameters.
6194   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6195   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6196   if (Replacement.isNull())
6197     return QualType();
6198 
6199   // Always canonicalize the replacement type.
6200   Replacement = SemaRef.Context.getCanonicalType(Replacement);
6201   QualType Result
6202     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
6203                                                    Replacement);
6204 
6205   // Propagate type-source information.
6206   SubstTemplateTypeParmTypeLoc NewTL
6207     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6208   NewTL.setNameLoc(TL.getNameLoc());
6209   return Result;
6210 
6211 }
6212 
6213 template<typename Derived>
6214 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6215                                           TypeLocBuilder &TLB,
6216                                           SubstTemplateTypeParmPackTypeLoc TL) {
6217   return TransformTypeSpecType(TLB, TL);
6218 }
6219 
6220 template<typename Derived>
6221 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6222                                                         TypeLocBuilder &TLB,
6223                                            TemplateSpecializationTypeLoc TL) {
6224   const TemplateSpecializationType *T = TL.getTypePtr();
6225 
6226   // The nested-name-specifier never matters in a TemplateSpecializationType,
6227   // because we can't have a dependent nested-name-specifier anyway.
6228   CXXScopeSpec SS;
6229   TemplateName Template
6230     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6231                                          TL.getTemplateNameLoc());
6232   if (Template.isNull())
6233     return QualType();
6234 
6235   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6236 }
6237 
6238 template<typename Derived>
6239 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6240                                                      AtomicTypeLoc TL) {
6241   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6242   if (ValueType.isNull())
6243     return QualType();
6244 
6245   QualType Result = TL.getType();
6246   if (getDerived().AlwaysRebuild() ||
6247       ValueType != TL.getValueLoc().getType()) {
6248     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6249     if (Result.isNull())
6250       return QualType();
6251   }
6252 
6253   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6254   NewTL.setKWLoc(TL.getKWLoc());
6255   NewTL.setLParenLoc(TL.getLParenLoc());
6256   NewTL.setRParenLoc(TL.getRParenLoc());
6257 
6258   return Result;
6259 }
6260 
6261 template <typename Derived>
6262 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6263                                                    PipeTypeLoc TL) {
6264   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6265   if (ValueType.isNull())
6266     return QualType();
6267 
6268   QualType Result = TL.getType();
6269   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6270     const PipeType *PT = Result->castAs<PipeType>();
6271     bool isReadPipe = PT->isReadOnly();
6272     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6273     if (Result.isNull())
6274       return QualType();
6275   }
6276 
6277   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6278   NewTL.setKWLoc(TL.getKWLoc());
6279 
6280   return Result;
6281 }
6282 
6283 template <typename Derived>
6284 QualType TreeTransform<Derived>::TransformExtIntType(TypeLocBuilder &TLB,
6285                                                      ExtIntTypeLoc TL) {
6286   const ExtIntType *EIT = TL.getTypePtr();
6287   QualType Result = TL.getType();
6288 
6289   if (getDerived().AlwaysRebuild()) {
6290     Result = getDerived().RebuildExtIntType(EIT->isUnsigned(),
6291                                             EIT->getNumBits(), TL.getNameLoc());
6292     if (Result.isNull())
6293       return QualType();
6294   }
6295 
6296   ExtIntTypeLoc NewTL = TLB.push<ExtIntTypeLoc>(Result);
6297   NewTL.setNameLoc(TL.getNameLoc());
6298   return Result;
6299 }
6300 
6301 template <typename Derived>
6302 QualType TreeTransform<Derived>::TransformDependentExtIntType(
6303     TypeLocBuilder &TLB, DependentExtIntTypeLoc TL) {
6304   const DependentExtIntType *EIT = TL.getTypePtr();
6305 
6306   EnterExpressionEvaluationContext Unevaluated(
6307       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6308   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6309   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6310 
6311   if (BitsExpr.isInvalid())
6312     return QualType();
6313 
6314   QualType Result = TL.getType();
6315 
6316   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6317     Result = getDerived().RebuildDependentExtIntType(
6318         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6319 
6320     if (Result.isNull())
6321       return QualType();
6322   }
6323 
6324   if (isa<DependentExtIntType>(Result)) {
6325     DependentExtIntTypeLoc NewTL = TLB.push<DependentExtIntTypeLoc>(Result);
6326     NewTL.setNameLoc(TL.getNameLoc());
6327   } else {
6328     ExtIntTypeLoc NewTL = TLB.push<ExtIntTypeLoc>(Result);
6329     NewTL.setNameLoc(TL.getNameLoc());
6330   }
6331   return Result;
6332 }
6333 
6334   /// Simple iterator that traverses the template arguments in a
6335   /// container that provides a \c getArgLoc() member function.
6336   ///
6337   /// This iterator is intended to be used with the iterator form of
6338   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6339   template<typename ArgLocContainer>
6340   class TemplateArgumentLocContainerIterator {
6341     ArgLocContainer *Container;
6342     unsigned Index;
6343 
6344   public:
6345     typedef TemplateArgumentLoc value_type;
6346     typedef TemplateArgumentLoc reference;
6347     typedef int difference_type;
6348     typedef std::input_iterator_tag iterator_category;
6349 
6350     class pointer {
6351       TemplateArgumentLoc Arg;
6352 
6353     public:
6354       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6355 
6356       const TemplateArgumentLoc *operator->() const {
6357         return &Arg;
6358       }
6359     };
6360 
6361 
6362     TemplateArgumentLocContainerIterator() {}
6363 
6364     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6365                                  unsigned Index)
6366       : Container(&Container), Index(Index) { }
6367 
6368     TemplateArgumentLocContainerIterator &operator++() {
6369       ++Index;
6370       return *this;
6371     }
6372 
6373     TemplateArgumentLocContainerIterator operator++(int) {
6374       TemplateArgumentLocContainerIterator Old(*this);
6375       ++(*this);
6376       return Old;
6377     }
6378 
6379     TemplateArgumentLoc operator*() const {
6380       return Container->getArgLoc(Index);
6381     }
6382 
6383     pointer operator->() const {
6384       return pointer(Container->getArgLoc(Index));
6385     }
6386 
6387     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6388                            const TemplateArgumentLocContainerIterator &Y) {
6389       return X.Container == Y.Container && X.Index == Y.Index;
6390     }
6391 
6392     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6393                            const TemplateArgumentLocContainerIterator &Y) {
6394       return !(X == Y);
6395     }
6396   };
6397 
6398 template<typename Derived>
6399 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6400                                                    AutoTypeLoc TL) {
6401   const AutoType *T = TL.getTypePtr();
6402   QualType OldDeduced = T->getDeducedType();
6403   QualType NewDeduced;
6404   if (!OldDeduced.isNull()) {
6405     NewDeduced = getDerived().TransformType(OldDeduced);
6406     if (NewDeduced.isNull())
6407       return QualType();
6408   }
6409 
6410   ConceptDecl *NewCD = nullptr;
6411   TemplateArgumentListInfo NewTemplateArgs;
6412   NestedNameSpecifierLoc NewNestedNameSpec;
6413   if (TL.getTypePtr()->isConstrained()) {
6414     NewCD = cast_or_null<ConceptDecl>(
6415         getDerived().TransformDecl(
6416             TL.getConceptNameLoc(),
6417             TL.getTypePtr()->getTypeConstraintConcept()));
6418 
6419     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6420     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6421     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6422     if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6423                                                 ArgIterator(TL,
6424                                                             TL.getNumArgs()),
6425                                                 NewTemplateArgs))
6426       return QualType();
6427 
6428     if (TL.getNestedNameSpecifierLoc()) {
6429       NewNestedNameSpec
6430         = getDerived().TransformNestedNameSpecifierLoc(
6431             TL.getNestedNameSpecifierLoc());
6432       if (!NewNestedNameSpec)
6433         return QualType();
6434     }
6435   }
6436 
6437   QualType Result = TL.getType();
6438   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6439       T->isDependentType()) {
6440     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6441     NewArgList.reserve(NewArgList.size());
6442     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6443       NewArgList.push_back(ArgLoc.getArgument());
6444     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6445                                           NewArgList);
6446     if (Result.isNull())
6447       return QualType();
6448   }
6449 
6450   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6451   NewTL.setNameLoc(TL.getNameLoc());
6452   NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6453   NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6454   NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6455   NewTL.setFoundDecl(TL.getFoundDecl());
6456   NewTL.setLAngleLoc(TL.getLAngleLoc());
6457   NewTL.setRAngleLoc(TL.getRAngleLoc());
6458   for (unsigned I = 0; I < TL.getNumArgs(); ++I)
6459     NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6460 
6461   return Result;
6462 }
6463 
6464 template <typename Derived>
6465 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6466                                                         TypeLocBuilder &TLB,
6467                                            TemplateSpecializationTypeLoc TL,
6468                                                       TemplateName Template) {
6469   TemplateArgumentListInfo NewTemplateArgs;
6470   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6471   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6472   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6473     ArgIterator;
6474   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6475                                               ArgIterator(TL, TL.getNumArgs()),
6476                                               NewTemplateArgs))
6477     return QualType();
6478 
6479   // FIXME: maybe don't rebuild if all the template arguments are the same.
6480 
6481   QualType Result =
6482     getDerived().RebuildTemplateSpecializationType(Template,
6483                                                    TL.getTemplateNameLoc(),
6484                                                    NewTemplateArgs);
6485 
6486   if (!Result.isNull()) {
6487     // Specializations of template template parameters are represented as
6488     // TemplateSpecializationTypes, and substitution of type alias templates
6489     // within a dependent context can transform them into
6490     // DependentTemplateSpecializationTypes.
6491     if (isa<DependentTemplateSpecializationType>(Result)) {
6492       DependentTemplateSpecializationTypeLoc NewTL
6493         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6494       NewTL.setElaboratedKeywordLoc(SourceLocation());
6495       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6496       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6497       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6498       NewTL.setLAngleLoc(TL.getLAngleLoc());
6499       NewTL.setRAngleLoc(TL.getRAngleLoc());
6500       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6501         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6502       return Result;
6503     }
6504 
6505     TemplateSpecializationTypeLoc NewTL
6506       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6507     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6508     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6509     NewTL.setLAngleLoc(TL.getLAngleLoc());
6510     NewTL.setRAngleLoc(TL.getRAngleLoc());
6511     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6512       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6513   }
6514 
6515   return Result;
6516 }
6517 
6518 template <typename Derived>
6519 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6520                                      TypeLocBuilder &TLB,
6521                                      DependentTemplateSpecializationTypeLoc TL,
6522                                      TemplateName Template,
6523                                      CXXScopeSpec &SS) {
6524   TemplateArgumentListInfo NewTemplateArgs;
6525   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6526   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6527   typedef TemplateArgumentLocContainerIterator<
6528             DependentTemplateSpecializationTypeLoc> ArgIterator;
6529   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6530                                               ArgIterator(TL, TL.getNumArgs()),
6531                                               NewTemplateArgs))
6532     return QualType();
6533 
6534   // FIXME: maybe don't rebuild if all the template arguments are the same.
6535 
6536   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6537     QualType Result
6538       = getSema().Context.getDependentTemplateSpecializationType(
6539                                                 TL.getTypePtr()->getKeyword(),
6540                                                          DTN->getQualifier(),
6541                                                          DTN->getIdentifier(),
6542                                                                NewTemplateArgs);
6543 
6544     DependentTemplateSpecializationTypeLoc NewTL
6545       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6546     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6547     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6548     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6549     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6550     NewTL.setLAngleLoc(TL.getLAngleLoc());
6551     NewTL.setRAngleLoc(TL.getRAngleLoc());
6552     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6553       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6554     return Result;
6555   }
6556 
6557   QualType Result
6558     = getDerived().RebuildTemplateSpecializationType(Template,
6559                                                      TL.getTemplateNameLoc(),
6560                                                      NewTemplateArgs);
6561 
6562   if (!Result.isNull()) {
6563     /// FIXME: Wrap this in an elaborated-type-specifier?
6564     TemplateSpecializationTypeLoc NewTL
6565       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6566     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6567     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6568     NewTL.setLAngleLoc(TL.getLAngleLoc());
6569     NewTL.setRAngleLoc(TL.getRAngleLoc());
6570     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6571       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6572   }
6573 
6574   return Result;
6575 }
6576 
6577 template<typename Derived>
6578 QualType
6579 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6580                                                 ElaboratedTypeLoc TL) {
6581   const ElaboratedType *T = TL.getTypePtr();
6582 
6583   NestedNameSpecifierLoc QualifierLoc;
6584   // NOTE: the qualifier in an ElaboratedType is optional.
6585   if (TL.getQualifierLoc()) {
6586     QualifierLoc
6587       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6588     if (!QualifierLoc)
6589       return QualType();
6590   }
6591 
6592   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6593   if (NamedT.isNull())
6594     return QualType();
6595 
6596   // C++0x [dcl.type.elab]p2:
6597   //   If the identifier resolves to a typedef-name or the simple-template-id
6598   //   resolves to an alias template specialization, the
6599   //   elaborated-type-specifier is ill-formed.
6600   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6601     if (const TemplateSpecializationType *TST =
6602           NamedT->getAs<TemplateSpecializationType>()) {
6603       TemplateName Template = TST->getTemplateName();
6604       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6605               Template.getAsTemplateDecl())) {
6606         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6607                      diag::err_tag_reference_non_tag)
6608             << TAT << Sema::NTK_TypeAliasTemplate
6609             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6610         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6611       }
6612     }
6613   }
6614 
6615   QualType Result = TL.getType();
6616   if (getDerived().AlwaysRebuild() ||
6617       QualifierLoc != TL.getQualifierLoc() ||
6618       NamedT != T->getNamedType()) {
6619     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6620                                                 T->getKeyword(),
6621                                                 QualifierLoc, NamedT);
6622     if (Result.isNull())
6623       return QualType();
6624   }
6625 
6626   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6627   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6628   NewTL.setQualifierLoc(QualifierLoc);
6629   return Result;
6630 }
6631 
6632 template<typename Derived>
6633 QualType TreeTransform<Derived>::TransformAttributedType(
6634                                                 TypeLocBuilder &TLB,
6635                                                 AttributedTypeLoc TL) {
6636   const AttributedType *oldType = TL.getTypePtr();
6637   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6638   if (modifiedType.isNull())
6639     return QualType();
6640 
6641   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6642   const Attr *oldAttr = TL.getAttr();
6643   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6644   if (oldAttr && !newAttr)
6645     return QualType();
6646 
6647   QualType result = TL.getType();
6648 
6649   // FIXME: dependent operand expressions?
6650   if (getDerived().AlwaysRebuild() ||
6651       modifiedType != oldType->getModifiedType()) {
6652     // TODO: this is really lame; we should really be rebuilding the
6653     // equivalent type from first principles.
6654     QualType equivalentType
6655       = getDerived().TransformType(oldType->getEquivalentType());
6656     if (equivalentType.isNull())
6657       return QualType();
6658 
6659     // Check whether we can add nullability; it is only represented as
6660     // type sugar, and therefore cannot be diagnosed in any other way.
6661     if (auto nullability = oldType->getImmediateNullability()) {
6662       if (!modifiedType->canHaveNullability()) {
6663         SemaRef.Diag(TL.getAttr()->getLocation(),
6664                      diag::err_nullability_nonpointer)
6665             << DiagNullabilityKind(*nullability, false) << modifiedType;
6666         return QualType();
6667       }
6668     }
6669 
6670     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6671                                                modifiedType,
6672                                                equivalentType);
6673   }
6674 
6675   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6676   newTL.setAttr(newAttr);
6677   return result;
6678 }
6679 
6680 template<typename Derived>
6681 QualType
6682 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6683                                            ParenTypeLoc TL) {
6684   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6685   if (Inner.isNull())
6686     return QualType();
6687 
6688   QualType Result = TL.getType();
6689   if (getDerived().AlwaysRebuild() ||
6690       Inner != TL.getInnerLoc().getType()) {
6691     Result = getDerived().RebuildParenType(Inner);
6692     if (Result.isNull())
6693       return QualType();
6694   }
6695 
6696   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6697   NewTL.setLParenLoc(TL.getLParenLoc());
6698   NewTL.setRParenLoc(TL.getRParenLoc());
6699   return Result;
6700 }
6701 
6702 template <typename Derived>
6703 QualType
6704 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6705                                                     MacroQualifiedTypeLoc TL) {
6706   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6707   if (Inner.isNull())
6708     return QualType();
6709 
6710   QualType Result = TL.getType();
6711   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6712     Result =
6713         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6714     if (Result.isNull())
6715       return QualType();
6716   }
6717 
6718   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6719   NewTL.setExpansionLoc(TL.getExpansionLoc());
6720   return Result;
6721 }
6722 
6723 template<typename Derived>
6724 QualType TreeTransform<Derived>::TransformDependentNameType(
6725     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6726   return TransformDependentNameType(TLB, TL, false);
6727 }
6728 
6729 template<typename Derived>
6730 QualType TreeTransform<Derived>::TransformDependentNameType(
6731     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6732   const DependentNameType *T = TL.getTypePtr();
6733 
6734   NestedNameSpecifierLoc QualifierLoc
6735     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6736   if (!QualifierLoc)
6737     return QualType();
6738 
6739   QualType Result
6740     = getDerived().RebuildDependentNameType(T->getKeyword(),
6741                                             TL.getElaboratedKeywordLoc(),
6742                                             QualifierLoc,
6743                                             T->getIdentifier(),
6744                                             TL.getNameLoc(),
6745                                             DeducedTSTContext);
6746   if (Result.isNull())
6747     return QualType();
6748 
6749   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6750     QualType NamedT = ElabT->getNamedType();
6751     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6752 
6753     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6754     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6755     NewTL.setQualifierLoc(QualifierLoc);
6756   } else {
6757     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6758     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6759     NewTL.setQualifierLoc(QualifierLoc);
6760     NewTL.setNameLoc(TL.getNameLoc());
6761   }
6762   return Result;
6763 }
6764 
6765 template<typename Derived>
6766 QualType TreeTransform<Derived>::
6767           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6768                                  DependentTemplateSpecializationTypeLoc TL) {
6769   NestedNameSpecifierLoc QualifierLoc;
6770   if (TL.getQualifierLoc()) {
6771     QualifierLoc
6772       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6773     if (!QualifierLoc)
6774       return QualType();
6775   }
6776 
6777   return getDerived()
6778            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6779 }
6780 
6781 template<typename Derived>
6782 QualType TreeTransform<Derived>::
6783 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6784                                    DependentTemplateSpecializationTypeLoc TL,
6785                                        NestedNameSpecifierLoc QualifierLoc) {
6786   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6787 
6788   TemplateArgumentListInfo NewTemplateArgs;
6789   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6790   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6791 
6792   typedef TemplateArgumentLocContainerIterator<
6793   DependentTemplateSpecializationTypeLoc> ArgIterator;
6794   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6795                                               ArgIterator(TL, TL.getNumArgs()),
6796                                               NewTemplateArgs))
6797     return QualType();
6798 
6799   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6800       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6801       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6802       /*AllowInjectedClassName*/ false);
6803   if (Result.isNull())
6804     return QualType();
6805 
6806   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6807     QualType NamedT = ElabT->getNamedType();
6808 
6809     // Copy information relevant to the template specialization.
6810     TemplateSpecializationTypeLoc NamedTL
6811       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6812     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6813     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6814     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6815     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6816     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6817       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6818 
6819     // Copy information relevant to the elaborated type.
6820     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6821     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6822     NewTL.setQualifierLoc(QualifierLoc);
6823   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6824     DependentTemplateSpecializationTypeLoc SpecTL
6825       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6826     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6827     SpecTL.setQualifierLoc(QualifierLoc);
6828     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6829     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6830     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6831     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6832     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6833       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6834   } else {
6835     TemplateSpecializationTypeLoc SpecTL
6836       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6837     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6838     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6839     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6840     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6841     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6842       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6843   }
6844   return Result;
6845 }
6846 
6847 template<typename Derived>
6848 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6849                                                       PackExpansionTypeLoc TL) {
6850   QualType Pattern
6851     = getDerived().TransformType(TLB, TL.getPatternLoc());
6852   if (Pattern.isNull())
6853     return QualType();
6854 
6855   QualType Result = TL.getType();
6856   if (getDerived().AlwaysRebuild() ||
6857       Pattern != TL.getPatternLoc().getType()) {
6858     Result = getDerived().RebuildPackExpansionType(Pattern,
6859                                            TL.getPatternLoc().getSourceRange(),
6860                                                    TL.getEllipsisLoc(),
6861                                            TL.getTypePtr()->getNumExpansions());
6862     if (Result.isNull())
6863       return QualType();
6864   }
6865 
6866   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6867   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6868   return Result;
6869 }
6870 
6871 template<typename Derived>
6872 QualType
6873 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6874                                                    ObjCInterfaceTypeLoc TL) {
6875   // ObjCInterfaceType is never dependent.
6876   TLB.pushFullCopy(TL);
6877   return TL.getType();
6878 }
6879 
6880 template<typename Derived>
6881 QualType
6882 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6883                                                    ObjCTypeParamTypeLoc TL) {
6884   const ObjCTypeParamType *T = TL.getTypePtr();
6885   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6886       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6887   if (!OTP)
6888     return QualType();
6889 
6890   QualType Result = TL.getType();
6891   if (getDerived().AlwaysRebuild() ||
6892       OTP != T->getDecl()) {
6893     Result = getDerived().RebuildObjCTypeParamType(OTP,
6894                  TL.getProtocolLAngleLoc(),
6895                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6896                                     TL.getNumProtocols()),
6897                  TL.getProtocolLocs(),
6898                  TL.getProtocolRAngleLoc());
6899     if (Result.isNull())
6900       return QualType();
6901   }
6902 
6903   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6904   if (TL.getNumProtocols()) {
6905     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6906     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6907       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6908     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6909   }
6910   return Result;
6911 }
6912 
6913 template<typename Derived>
6914 QualType
6915 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6916                                                 ObjCObjectTypeLoc TL) {
6917   // Transform base type.
6918   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6919   if (BaseType.isNull())
6920     return QualType();
6921 
6922   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6923 
6924   // Transform type arguments.
6925   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6926   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6927     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6928     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6929     QualType TypeArg = TypeArgInfo->getType();
6930     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6931       AnyChanged = true;
6932 
6933       // We have a pack expansion. Instantiate it.
6934       const auto *PackExpansion = PackExpansionLoc.getType()
6935                                     ->castAs<PackExpansionType>();
6936       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6937       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6938                                               Unexpanded);
6939       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6940 
6941       // Determine whether the set of unexpanded parameter packs can
6942       // and should be expanded.
6943       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6944       bool Expand = false;
6945       bool RetainExpansion = false;
6946       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6947       if (getDerived().TryExpandParameterPacks(
6948             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6949             Unexpanded, Expand, RetainExpansion, NumExpansions))
6950         return QualType();
6951 
6952       if (!Expand) {
6953         // We can't expand this pack expansion into separate arguments yet;
6954         // just substitute into the pattern and create a new pack expansion
6955         // type.
6956         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6957 
6958         TypeLocBuilder TypeArgBuilder;
6959         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6960         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6961                                                              PatternLoc);
6962         if (NewPatternType.isNull())
6963           return QualType();
6964 
6965         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6966                                       NewPatternType, NumExpansions);
6967         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6968         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6969         NewTypeArgInfos.push_back(
6970           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6971         continue;
6972       }
6973 
6974       // Substitute into the pack expansion pattern for each slice of the
6975       // pack.
6976       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6977         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6978 
6979         TypeLocBuilder TypeArgBuilder;
6980         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6981 
6982         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6983                                                          PatternLoc);
6984         if (NewTypeArg.isNull())
6985           return QualType();
6986 
6987         NewTypeArgInfos.push_back(
6988           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6989       }
6990 
6991       continue;
6992     }
6993 
6994     TypeLocBuilder TypeArgBuilder;
6995     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6996     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6997     if (NewTypeArg.isNull())
6998       return QualType();
6999 
7000     // If nothing changed, just keep the old TypeSourceInfo.
7001     if (NewTypeArg == TypeArg) {
7002       NewTypeArgInfos.push_back(TypeArgInfo);
7003       continue;
7004     }
7005 
7006     NewTypeArgInfos.push_back(
7007       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7008     AnyChanged = true;
7009   }
7010 
7011   QualType Result = TL.getType();
7012   if (getDerived().AlwaysRebuild() || AnyChanged) {
7013     // Rebuild the type.
7014     Result = getDerived().RebuildObjCObjectType(
7015         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7016         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7017         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7018         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7019 
7020     if (Result.isNull())
7021       return QualType();
7022   }
7023 
7024   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7025   NewT.setHasBaseTypeAsWritten(true);
7026   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7027   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7028     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7029   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7030   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7031   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7032     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7033   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7034   return Result;
7035 }
7036 
7037 template<typename Derived>
7038 QualType
7039 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7040                                                ObjCObjectPointerTypeLoc TL) {
7041   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7042   if (PointeeType.isNull())
7043     return QualType();
7044 
7045   QualType Result = TL.getType();
7046   if (getDerived().AlwaysRebuild() ||
7047       PointeeType != TL.getPointeeLoc().getType()) {
7048     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7049                                                        TL.getStarLoc());
7050     if (Result.isNull())
7051       return QualType();
7052   }
7053 
7054   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7055   NewT.setStarLoc(TL.getStarLoc());
7056   return Result;
7057 }
7058 
7059 //===----------------------------------------------------------------------===//
7060 // Statement transformation
7061 //===----------------------------------------------------------------------===//
7062 template<typename Derived>
7063 StmtResult
7064 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7065   return S;
7066 }
7067 
7068 template<typename Derived>
7069 StmtResult
7070 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7071   return getDerived().TransformCompoundStmt(S, false);
7072 }
7073 
7074 template<typename Derived>
7075 StmtResult
7076 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7077                                               bool IsStmtExpr) {
7078   Sema::CompoundScopeRAII CompoundScope(getSema());
7079 
7080   const Stmt *ExprResult = S->getStmtExprResult();
7081   bool SubStmtInvalid = false;
7082   bool SubStmtChanged = false;
7083   SmallVector<Stmt*, 8> Statements;
7084   for (auto *B : S->body()) {
7085     StmtResult Result = getDerived().TransformStmt(
7086         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7087 
7088     if (Result.isInvalid()) {
7089       // Immediately fail if this was a DeclStmt, since it's very
7090       // likely that this will cause problems for future statements.
7091       if (isa<DeclStmt>(B))
7092         return StmtError();
7093 
7094       // Otherwise, just keep processing substatements and fail later.
7095       SubStmtInvalid = true;
7096       continue;
7097     }
7098 
7099     SubStmtChanged = SubStmtChanged || Result.get() != B;
7100     Statements.push_back(Result.getAs<Stmt>());
7101   }
7102 
7103   if (SubStmtInvalid)
7104     return StmtError();
7105 
7106   if (!getDerived().AlwaysRebuild() &&
7107       !SubStmtChanged)
7108     return S;
7109 
7110   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7111                                           Statements,
7112                                           S->getRBracLoc(),
7113                                           IsStmtExpr);
7114 }
7115 
7116 template<typename Derived>
7117 StmtResult
7118 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7119   ExprResult LHS, RHS;
7120   {
7121     EnterExpressionEvaluationContext Unevaluated(
7122         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7123 
7124     // Transform the left-hand case value.
7125     LHS = getDerived().TransformExpr(S->getLHS());
7126     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7127     if (LHS.isInvalid())
7128       return StmtError();
7129 
7130     // Transform the right-hand case value (for the GNU case-range extension).
7131     RHS = getDerived().TransformExpr(S->getRHS());
7132     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7133     if (RHS.isInvalid())
7134       return StmtError();
7135   }
7136 
7137   // Build the case statement.
7138   // Case statements are always rebuilt so that they will attached to their
7139   // transformed switch statement.
7140   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7141                                                        LHS.get(),
7142                                                        S->getEllipsisLoc(),
7143                                                        RHS.get(),
7144                                                        S->getColonLoc());
7145   if (Case.isInvalid())
7146     return StmtError();
7147 
7148   // Transform the statement following the case
7149   StmtResult SubStmt =
7150       getDerived().TransformStmt(S->getSubStmt());
7151   if (SubStmt.isInvalid())
7152     return StmtError();
7153 
7154   // Attach the body to the case statement
7155   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7156 }
7157 
7158 template <typename Derived>
7159 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7160   // Transform the statement following the default case
7161   StmtResult SubStmt =
7162       getDerived().TransformStmt(S->getSubStmt());
7163   if (SubStmt.isInvalid())
7164     return StmtError();
7165 
7166   // Default statements are always rebuilt
7167   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7168                                          SubStmt.get());
7169 }
7170 
7171 template<typename Derived>
7172 StmtResult
7173 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7174   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7175   if (SubStmt.isInvalid())
7176     return StmtError();
7177 
7178   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7179                                         S->getDecl());
7180   if (!LD)
7181     return StmtError();
7182 
7183   // If we're transforming "in-place" (we're not creating new local
7184   // declarations), assume we're replacing the old label statement
7185   // and clear out the reference to it.
7186   if (LD == S->getDecl())
7187     S->getDecl()->setStmt(nullptr);
7188 
7189   // FIXME: Pass the real colon location in.
7190   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7191                                        cast<LabelDecl>(LD), SourceLocation(),
7192                                        SubStmt.get());
7193 }
7194 
7195 template <typename Derived>
7196 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7197   if (!R)
7198     return R;
7199 
7200   switch (R->getKind()) {
7201 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
7202 #define ATTR(X)
7203 #define PRAGMA_SPELLING_ATTR(X)                                                \
7204   case attr::X:                                                                \
7205     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7206 #include "clang/Basic/AttrList.inc"
7207   default:
7208     return R;
7209   }
7210 }
7211 
7212 template <typename Derived>
7213 StmtResult
7214 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7215                                                 StmtDiscardKind SDK) {
7216   bool AttrsChanged = false;
7217   SmallVector<const Attr *, 1> Attrs;
7218 
7219   // Visit attributes and keep track if any are transformed.
7220   for (const auto *I : S->getAttrs()) {
7221     const Attr *R = getDerived().TransformAttr(I);
7222     AttrsChanged |= (I != R);
7223     Attrs.push_back(R);
7224   }
7225 
7226   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7227   if (SubStmt.isInvalid())
7228     return StmtError();
7229 
7230   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7231     return S;
7232 
7233   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7234                                             SubStmt.get());
7235 }
7236 
7237 template<typename Derived>
7238 StmtResult
7239 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7240   // Transform the initialization statement
7241   StmtResult Init = getDerived().TransformStmt(S->getInit());
7242   if (Init.isInvalid())
7243     return StmtError();
7244 
7245   // Transform the condition
7246   Sema::ConditionResult Cond = getDerived().TransformCondition(
7247       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7248       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7249                        : Sema::ConditionKind::Boolean);
7250   if (Cond.isInvalid())
7251     return StmtError();
7252 
7253   // If this is a constexpr if, determine which arm we should instantiate.
7254   llvm::Optional<bool> ConstexprConditionValue;
7255   if (S->isConstexpr())
7256     ConstexprConditionValue = Cond.getKnownValue();
7257 
7258   // Transform the "then" branch.
7259   StmtResult Then;
7260   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7261     Then = getDerived().TransformStmt(S->getThen());
7262     if (Then.isInvalid())
7263       return StmtError();
7264   } else {
7265     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7266   }
7267 
7268   // Transform the "else" branch.
7269   StmtResult Else;
7270   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7271     Else = getDerived().TransformStmt(S->getElse());
7272     if (Else.isInvalid())
7273       return StmtError();
7274   }
7275 
7276   if (!getDerived().AlwaysRebuild() &&
7277       Init.get() == S->getInit() &&
7278       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7279       Then.get() == S->getThen() &&
7280       Else.get() == S->getElse())
7281     return S;
7282 
7283   return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
7284                                     Init.get(), Then.get(), S->getElseLoc(),
7285                                     Else.get());
7286 }
7287 
7288 template<typename Derived>
7289 StmtResult
7290 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7291   // Transform the initialization statement
7292   StmtResult Init = getDerived().TransformStmt(S->getInit());
7293   if (Init.isInvalid())
7294     return StmtError();
7295 
7296   // Transform the condition.
7297   Sema::ConditionResult Cond = getDerived().TransformCondition(
7298       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7299       Sema::ConditionKind::Switch);
7300   if (Cond.isInvalid())
7301     return StmtError();
7302 
7303   // Rebuild the switch statement.
7304   StmtResult Switch
7305     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
7306   if (Switch.isInvalid())
7307     return StmtError();
7308 
7309   // Transform the body of the switch statement.
7310   StmtResult Body = getDerived().TransformStmt(S->getBody());
7311   if (Body.isInvalid())
7312     return StmtError();
7313 
7314   // Complete the switch statement.
7315   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7316                                             Body.get());
7317 }
7318 
7319 template<typename Derived>
7320 StmtResult
7321 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7322   // Transform the condition
7323   Sema::ConditionResult Cond = getDerived().TransformCondition(
7324       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7325       Sema::ConditionKind::Boolean);
7326   if (Cond.isInvalid())
7327     return StmtError();
7328 
7329   // Transform the body
7330   StmtResult Body = getDerived().TransformStmt(S->getBody());
7331   if (Body.isInvalid())
7332     return StmtError();
7333 
7334   if (!getDerived().AlwaysRebuild() &&
7335       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7336       Body.get() == S->getBody())
7337     return Owned(S);
7338 
7339   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7340                                        Cond, S->getRParenLoc(), Body.get());
7341 }
7342 
7343 template<typename Derived>
7344 StmtResult
7345 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7346   // Transform the body
7347   StmtResult Body = getDerived().TransformStmt(S->getBody());
7348   if (Body.isInvalid())
7349     return StmtError();
7350 
7351   // Transform the condition
7352   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7353   if (Cond.isInvalid())
7354     return StmtError();
7355 
7356   if (!getDerived().AlwaysRebuild() &&
7357       Cond.get() == S->getCond() &&
7358       Body.get() == S->getBody())
7359     return S;
7360 
7361   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7362                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7363                                     S->getRParenLoc());
7364 }
7365 
7366 template<typename Derived>
7367 StmtResult
7368 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7369   if (getSema().getLangOpts().OpenMP)
7370     getSema().startOpenMPLoop();
7371 
7372   // Transform the initialization statement
7373   StmtResult Init = getDerived().TransformStmt(S->getInit());
7374   if (Init.isInvalid())
7375     return StmtError();
7376 
7377   // In OpenMP loop region loop control variable must be captured and be
7378   // private. Perform analysis of first part (if any).
7379   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7380     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7381 
7382   // Transform the condition
7383   Sema::ConditionResult Cond = getDerived().TransformCondition(
7384       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7385       Sema::ConditionKind::Boolean);
7386   if (Cond.isInvalid())
7387     return StmtError();
7388 
7389   // Transform the increment
7390   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7391   if (Inc.isInvalid())
7392     return StmtError();
7393 
7394   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7395   if (S->getInc() && !FullInc.get())
7396     return StmtError();
7397 
7398   // Transform the body
7399   StmtResult Body = getDerived().TransformStmt(S->getBody());
7400   if (Body.isInvalid())
7401     return StmtError();
7402 
7403   if (!getDerived().AlwaysRebuild() &&
7404       Init.get() == S->getInit() &&
7405       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7406       Inc.get() == S->getInc() &&
7407       Body.get() == S->getBody())
7408     return S;
7409 
7410   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7411                                      Init.get(), Cond, FullInc,
7412                                      S->getRParenLoc(), Body.get());
7413 }
7414 
7415 template<typename Derived>
7416 StmtResult
7417 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7418   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7419                                         S->getLabel());
7420   if (!LD)
7421     return StmtError();
7422 
7423   // Goto statements must always be rebuilt, to resolve the label.
7424   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7425                                       cast<LabelDecl>(LD));
7426 }
7427 
7428 template<typename Derived>
7429 StmtResult
7430 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7431   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7432   if (Target.isInvalid())
7433     return StmtError();
7434   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7435 
7436   if (!getDerived().AlwaysRebuild() &&
7437       Target.get() == S->getTarget())
7438     return S;
7439 
7440   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7441                                               Target.get());
7442 }
7443 
7444 template<typename Derived>
7445 StmtResult
7446 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7447   return S;
7448 }
7449 
7450 template<typename Derived>
7451 StmtResult
7452 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7453   return S;
7454 }
7455 
7456 template<typename Derived>
7457 StmtResult
7458 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7459   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7460                                                         /*NotCopyInit*/false);
7461   if (Result.isInvalid())
7462     return StmtError();
7463 
7464   // FIXME: We always rebuild the return statement because there is no way
7465   // to tell whether the return type of the function has changed.
7466   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7467 }
7468 
7469 template<typename Derived>
7470 StmtResult
7471 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7472   bool DeclChanged = false;
7473   SmallVector<Decl *, 4> Decls;
7474   for (auto *D : S->decls()) {
7475     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7476     if (!Transformed)
7477       return StmtError();
7478 
7479     if (Transformed != D)
7480       DeclChanged = true;
7481 
7482     Decls.push_back(Transformed);
7483   }
7484 
7485   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7486     return S;
7487 
7488   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7489 }
7490 
7491 template<typename Derived>
7492 StmtResult
7493 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7494 
7495   SmallVector<Expr*, 8> Constraints;
7496   SmallVector<Expr*, 8> Exprs;
7497   SmallVector<IdentifierInfo *, 4> Names;
7498 
7499   ExprResult AsmString;
7500   SmallVector<Expr*, 8> Clobbers;
7501 
7502   bool ExprsChanged = false;
7503 
7504   // Go through the outputs.
7505   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7506     Names.push_back(S->getOutputIdentifier(I));
7507 
7508     // No need to transform the constraint literal.
7509     Constraints.push_back(S->getOutputConstraintLiteral(I));
7510 
7511     // Transform the output expr.
7512     Expr *OutputExpr = S->getOutputExpr(I);
7513     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7514     if (Result.isInvalid())
7515       return StmtError();
7516 
7517     ExprsChanged |= Result.get() != OutputExpr;
7518 
7519     Exprs.push_back(Result.get());
7520   }
7521 
7522   // Go through the inputs.
7523   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7524     Names.push_back(S->getInputIdentifier(I));
7525 
7526     // No need to transform the constraint literal.
7527     Constraints.push_back(S->getInputConstraintLiteral(I));
7528 
7529     // Transform the input expr.
7530     Expr *InputExpr = S->getInputExpr(I);
7531     ExprResult Result = getDerived().TransformExpr(InputExpr);
7532     if (Result.isInvalid())
7533       return StmtError();
7534 
7535     ExprsChanged |= Result.get() != InputExpr;
7536 
7537     Exprs.push_back(Result.get());
7538   }
7539 
7540   // Go through the Labels.
7541   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7542     Names.push_back(S->getLabelIdentifier(I));
7543 
7544     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7545     if (Result.isInvalid())
7546       return StmtError();
7547     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7548     Exprs.push_back(Result.get());
7549   }
7550   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7551     return S;
7552 
7553   // Go through the clobbers.
7554   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7555     Clobbers.push_back(S->getClobberStringLiteral(I));
7556 
7557   // No need to transform the asm string literal.
7558   AsmString = S->getAsmString();
7559   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7560                                         S->isVolatile(), S->getNumOutputs(),
7561                                         S->getNumInputs(), Names.data(),
7562                                         Constraints, Exprs, AsmString.get(),
7563                                         Clobbers, S->getNumLabels(),
7564                                         S->getRParenLoc());
7565 }
7566 
7567 template<typename Derived>
7568 StmtResult
7569 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7570   ArrayRef<Token> AsmToks =
7571     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7572 
7573   bool HadError = false, HadChange = false;
7574 
7575   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7576   SmallVector<Expr*, 8> TransformedExprs;
7577   TransformedExprs.reserve(SrcExprs.size());
7578   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7579     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7580     if (!Result.isUsable()) {
7581       HadError = true;
7582     } else {
7583       HadChange |= (Result.get() != SrcExprs[i]);
7584       TransformedExprs.push_back(Result.get());
7585     }
7586   }
7587 
7588   if (HadError) return StmtError();
7589   if (!HadChange && !getDerived().AlwaysRebuild())
7590     return Owned(S);
7591 
7592   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7593                                        AsmToks, S->getAsmString(),
7594                                        S->getNumOutputs(), S->getNumInputs(),
7595                                        S->getAllConstraints(), S->getClobbers(),
7596                                        TransformedExprs, S->getEndLoc());
7597 }
7598 
7599 // C++ Coroutines TS
7600 
7601 template<typename Derived>
7602 StmtResult
7603 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7604   auto *ScopeInfo = SemaRef.getCurFunction();
7605   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7606   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7607          ScopeInfo->NeedsCoroutineSuspends &&
7608          ScopeInfo->CoroutineSuspends.first == nullptr &&
7609          ScopeInfo->CoroutineSuspends.second == nullptr &&
7610          "expected clean scope info");
7611 
7612   // Set that we have (possibly-invalid) suspend points before we do anything
7613   // that may fail.
7614   ScopeInfo->setNeedsCoroutineSuspends(false);
7615 
7616   // We re-build the coroutine promise object (and the coroutine parameters its
7617   // type and constructor depend on) based on the types used in our current
7618   // function. We must do so, and set it on the current FunctionScopeInfo,
7619   // before attempting to transform the other parts of the coroutine body
7620   // statement, such as the implicit suspend statements (because those
7621   // statements reference the FunctionScopeInfo::CoroutinePromise).
7622   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7623     return StmtError();
7624   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7625   if (!Promise)
7626     return StmtError();
7627   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7628   ScopeInfo->CoroutinePromise = Promise;
7629 
7630   // Transform the implicit coroutine statements constructed using dependent
7631   // types during the previous parse: initial and final suspensions, the return
7632   // object, and others. We also transform the coroutine function's body.
7633   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7634   if (InitSuspend.isInvalid())
7635     return StmtError();
7636   StmtResult FinalSuspend =
7637       getDerived().TransformStmt(S->getFinalSuspendStmt());
7638   if (FinalSuspend.isInvalid() ||
7639       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
7640     return StmtError();
7641   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7642   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7643 
7644   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7645   if (BodyRes.isInvalid())
7646     return StmtError();
7647 
7648   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7649   if (Builder.isInvalid())
7650     return StmtError();
7651 
7652   Expr *ReturnObject = S->getReturnValueInit();
7653   assert(ReturnObject && "the return object is expected to be valid");
7654   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7655                                                      /*NoCopyInit*/ false);
7656   if (Res.isInvalid())
7657     return StmtError();
7658   Builder.ReturnValue = Res.get();
7659 
7660   // If during the previous parse the coroutine still had a dependent promise
7661   // statement, we may need to build some implicit coroutine statements
7662   // (such as exception and fallthrough handlers) for the first time.
7663   if (S->hasDependentPromiseType()) {
7664     // We can only build these statements, however, if the current promise type
7665     // is not dependent.
7666     if (!Promise->getType()->isDependentType()) {
7667       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7668              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7669              "these nodes should not have been built yet");
7670       if (!Builder.buildDependentStatements())
7671         return StmtError();
7672     }
7673   } else {
7674     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7675       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7676       if (Res.isInvalid())
7677         return StmtError();
7678       Builder.OnFallthrough = Res.get();
7679     }
7680 
7681     if (auto *OnException = S->getExceptionHandler()) {
7682       StmtResult Res = getDerived().TransformStmt(OnException);
7683       if (Res.isInvalid())
7684         return StmtError();
7685       Builder.OnException = Res.get();
7686     }
7687 
7688     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7689       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7690       if (Res.isInvalid())
7691         return StmtError();
7692       Builder.ReturnStmtOnAllocFailure = Res.get();
7693     }
7694 
7695     // Transform any additional statements we may have already built
7696     assert(S->getAllocate() && S->getDeallocate() &&
7697            "allocation and deallocation calls must already be built");
7698     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7699     if (AllocRes.isInvalid())
7700       return StmtError();
7701     Builder.Allocate = AllocRes.get();
7702 
7703     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7704     if (DeallocRes.isInvalid())
7705       return StmtError();
7706     Builder.Deallocate = DeallocRes.get();
7707 
7708     assert(S->getResultDecl() && "ResultDecl must already be built");
7709     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7710     if (ResultDecl.isInvalid())
7711       return StmtError();
7712     Builder.ResultDecl = ResultDecl.get();
7713 
7714     if (auto *ReturnStmt = S->getReturnStmt()) {
7715       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7716       if (Res.isInvalid())
7717         return StmtError();
7718       Builder.ReturnStmt = Res.get();
7719     }
7720   }
7721 
7722   return getDerived().RebuildCoroutineBodyStmt(Builder);
7723 }
7724 
7725 template<typename Derived>
7726 StmtResult
7727 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7728   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7729                                                         /*NotCopyInit*/false);
7730   if (Result.isInvalid())
7731     return StmtError();
7732 
7733   // Always rebuild; we don't know if this needs to be injected into a new
7734   // context or if the promise type has changed.
7735   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7736                                           S->isImplicit());
7737 }
7738 
7739 template<typename Derived>
7740 ExprResult
7741 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7742   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7743                                                         /*NotCopyInit*/false);
7744   if (Result.isInvalid())
7745     return ExprError();
7746 
7747   // Always rebuild; we don't know if this needs to be injected into a new
7748   // context or if the promise type has changed.
7749   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7750                                          E->isImplicit());
7751 }
7752 
7753 template <typename Derived>
7754 ExprResult
7755 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7756   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7757                                                         /*NotCopyInit*/ false);
7758   if (OperandResult.isInvalid())
7759     return ExprError();
7760 
7761   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7762           E->getOperatorCoawaitLookup());
7763 
7764   if (LookupResult.isInvalid())
7765     return ExprError();
7766 
7767   // Always rebuild; we don't know if this needs to be injected into a new
7768   // context or if the promise type has changed.
7769   return getDerived().RebuildDependentCoawaitExpr(
7770       E->getKeywordLoc(), OperandResult.get(),
7771       cast<UnresolvedLookupExpr>(LookupResult.get()));
7772 }
7773 
7774 template<typename Derived>
7775 ExprResult
7776 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7777   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7778                                                         /*NotCopyInit*/false);
7779   if (Result.isInvalid())
7780     return ExprError();
7781 
7782   // Always rebuild; we don't know if this needs to be injected into a new
7783   // context or if the promise type has changed.
7784   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7785 }
7786 
7787 // Objective-C Statements.
7788 
7789 template<typename Derived>
7790 StmtResult
7791 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7792   // Transform the body of the @try.
7793   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7794   if (TryBody.isInvalid())
7795     return StmtError();
7796 
7797   // Transform the @catch statements (if present).
7798   bool AnyCatchChanged = false;
7799   SmallVector<Stmt*, 8> CatchStmts;
7800   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7801     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7802     if (Catch.isInvalid())
7803       return StmtError();
7804     if (Catch.get() != S->getCatchStmt(I))
7805       AnyCatchChanged = true;
7806     CatchStmts.push_back(Catch.get());
7807   }
7808 
7809   // Transform the @finally statement (if present).
7810   StmtResult Finally;
7811   if (S->getFinallyStmt()) {
7812     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7813     if (Finally.isInvalid())
7814       return StmtError();
7815   }
7816 
7817   // If nothing changed, just retain this statement.
7818   if (!getDerived().AlwaysRebuild() &&
7819       TryBody.get() == S->getTryBody() &&
7820       !AnyCatchChanged &&
7821       Finally.get() == S->getFinallyStmt())
7822     return S;
7823 
7824   // Build a new statement.
7825   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7826                                            CatchStmts, Finally.get());
7827 }
7828 
7829 template<typename Derived>
7830 StmtResult
7831 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7832   // Transform the @catch parameter, if there is one.
7833   VarDecl *Var = nullptr;
7834   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7835     TypeSourceInfo *TSInfo = nullptr;
7836     if (FromVar->getTypeSourceInfo()) {
7837       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7838       if (!TSInfo)
7839         return StmtError();
7840     }
7841 
7842     QualType T;
7843     if (TSInfo)
7844       T = TSInfo->getType();
7845     else {
7846       T = getDerived().TransformType(FromVar->getType());
7847       if (T.isNull())
7848         return StmtError();
7849     }
7850 
7851     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7852     if (!Var)
7853       return StmtError();
7854   }
7855 
7856   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7857   if (Body.isInvalid())
7858     return StmtError();
7859 
7860   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7861                                              S->getRParenLoc(),
7862                                              Var, Body.get());
7863 }
7864 
7865 template<typename Derived>
7866 StmtResult
7867 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7868   // Transform the body.
7869   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7870   if (Body.isInvalid())
7871     return StmtError();
7872 
7873   // If nothing changed, just retain this statement.
7874   if (!getDerived().AlwaysRebuild() &&
7875       Body.get() == S->getFinallyBody())
7876     return S;
7877 
7878   // Build a new statement.
7879   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7880                                                Body.get());
7881 }
7882 
7883 template<typename Derived>
7884 StmtResult
7885 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7886   ExprResult Operand;
7887   if (S->getThrowExpr()) {
7888     Operand = getDerived().TransformExpr(S->getThrowExpr());
7889     if (Operand.isInvalid())
7890       return StmtError();
7891   }
7892 
7893   if (!getDerived().AlwaysRebuild() &&
7894       Operand.get() == S->getThrowExpr())
7895     return S;
7896 
7897   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7898 }
7899 
7900 template<typename Derived>
7901 StmtResult
7902 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7903                                                   ObjCAtSynchronizedStmt *S) {
7904   // Transform the object we are locking.
7905   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7906   if (Object.isInvalid())
7907     return StmtError();
7908   Object =
7909     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7910                                                   Object.get());
7911   if (Object.isInvalid())
7912     return StmtError();
7913 
7914   // Transform the body.
7915   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7916   if (Body.isInvalid())
7917     return StmtError();
7918 
7919   // If nothing change, just retain the current statement.
7920   if (!getDerived().AlwaysRebuild() &&
7921       Object.get() == S->getSynchExpr() &&
7922       Body.get() == S->getSynchBody())
7923     return S;
7924 
7925   // Build a new statement.
7926   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7927                                                     Object.get(), Body.get());
7928 }
7929 
7930 template<typename Derived>
7931 StmtResult
7932 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7933                                               ObjCAutoreleasePoolStmt *S) {
7934   // Transform the body.
7935   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7936   if (Body.isInvalid())
7937     return StmtError();
7938 
7939   // If nothing changed, just retain this statement.
7940   if (!getDerived().AlwaysRebuild() &&
7941       Body.get() == S->getSubStmt())
7942     return S;
7943 
7944   // Build a new statement.
7945   return getDerived().RebuildObjCAutoreleasePoolStmt(
7946                         S->getAtLoc(), Body.get());
7947 }
7948 
7949 template<typename Derived>
7950 StmtResult
7951 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7952                                                   ObjCForCollectionStmt *S) {
7953   // Transform the element statement.
7954   StmtResult Element =
7955       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7956   if (Element.isInvalid())
7957     return StmtError();
7958 
7959   // Transform the collection expression.
7960   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7961   if (Collection.isInvalid())
7962     return StmtError();
7963 
7964   // Transform the body.
7965   StmtResult Body = getDerived().TransformStmt(S->getBody());
7966   if (Body.isInvalid())
7967     return StmtError();
7968 
7969   // If nothing changed, just retain this statement.
7970   if (!getDerived().AlwaysRebuild() &&
7971       Element.get() == S->getElement() &&
7972       Collection.get() == S->getCollection() &&
7973       Body.get() == S->getBody())
7974     return S;
7975 
7976   // Build a new statement.
7977   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7978                                                    Element.get(),
7979                                                    Collection.get(),
7980                                                    S->getRParenLoc(),
7981                                                    Body.get());
7982 }
7983 
7984 template <typename Derived>
7985 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7986   // Transform the exception declaration, if any.
7987   VarDecl *Var = nullptr;
7988   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7989     TypeSourceInfo *T =
7990         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7991     if (!T)
7992       return StmtError();
7993 
7994     Var = getDerived().RebuildExceptionDecl(
7995         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7996         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7997     if (!Var || Var->isInvalidDecl())
7998       return StmtError();
7999   }
8000 
8001   // Transform the actual exception handler.
8002   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8003   if (Handler.isInvalid())
8004     return StmtError();
8005 
8006   if (!getDerived().AlwaysRebuild() && !Var &&
8007       Handler.get() == S->getHandlerBlock())
8008     return S;
8009 
8010   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8011 }
8012 
8013 template <typename Derived>
8014 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8015   // Transform the try block itself.
8016   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8017   if (TryBlock.isInvalid())
8018     return StmtError();
8019 
8020   // Transform the handlers.
8021   bool HandlerChanged = false;
8022   SmallVector<Stmt *, 8> Handlers;
8023   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8024     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8025     if (Handler.isInvalid())
8026       return StmtError();
8027 
8028     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8029     Handlers.push_back(Handler.getAs<Stmt>());
8030   }
8031 
8032   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8033       !HandlerChanged)
8034     return S;
8035 
8036   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8037                                         Handlers);
8038 }
8039 
8040 template<typename Derived>
8041 StmtResult
8042 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8043   StmtResult Init =
8044       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8045   if (Init.isInvalid())
8046     return StmtError();
8047 
8048   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8049   if (Range.isInvalid())
8050     return StmtError();
8051 
8052   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8053   if (Begin.isInvalid())
8054     return StmtError();
8055   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8056   if (End.isInvalid())
8057     return StmtError();
8058 
8059   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8060   if (Cond.isInvalid())
8061     return StmtError();
8062   if (Cond.get())
8063     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8064   if (Cond.isInvalid())
8065     return StmtError();
8066   if (Cond.get())
8067     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8068 
8069   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8070   if (Inc.isInvalid())
8071     return StmtError();
8072   if (Inc.get())
8073     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8074 
8075   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8076   if (LoopVar.isInvalid())
8077     return StmtError();
8078 
8079   StmtResult NewStmt = S;
8080   if (getDerived().AlwaysRebuild() ||
8081       Init.get() != S->getInit() ||
8082       Range.get() != S->getRangeStmt() ||
8083       Begin.get() != S->getBeginStmt() ||
8084       End.get() != S->getEndStmt() ||
8085       Cond.get() != S->getCond() ||
8086       Inc.get() != S->getInc() ||
8087       LoopVar.get() != S->getLoopVarStmt()) {
8088     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8089                                                   S->getCoawaitLoc(), Init.get(),
8090                                                   S->getColonLoc(), Range.get(),
8091                                                   Begin.get(), End.get(),
8092                                                   Cond.get(),
8093                                                   Inc.get(), LoopVar.get(),
8094                                                   S->getRParenLoc());
8095     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8096       // Might not have attached any initializer to the loop variable.
8097       getSema().ActOnInitializerError(
8098           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8099       return StmtError();
8100     }
8101   }
8102 
8103   StmtResult Body = getDerived().TransformStmt(S->getBody());
8104   if (Body.isInvalid())
8105     return StmtError();
8106 
8107   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8108   // it now so we have a new statement to attach the body to.
8109   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8110     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8111                                                   S->getCoawaitLoc(), Init.get(),
8112                                                   S->getColonLoc(), Range.get(),
8113                                                   Begin.get(), End.get(),
8114                                                   Cond.get(),
8115                                                   Inc.get(), LoopVar.get(),
8116                                                   S->getRParenLoc());
8117     if (NewStmt.isInvalid())
8118       return StmtError();
8119   }
8120 
8121   if (NewStmt.get() == S)
8122     return S;
8123 
8124   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8125 }
8126 
8127 template<typename Derived>
8128 StmtResult
8129 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8130                                                     MSDependentExistsStmt *S) {
8131   // Transform the nested-name-specifier, if any.
8132   NestedNameSpecifierLoc QualifierLoc;
8133   if (S->getQualifierLoc()) {
8134     QualifierLoc
8135       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8136     if (!QualifierLoc)
8137       return StmtError();
8138   }
8139 
8140   // Transform the declaration name.
8141   DeclarationNameInfo NameInfo = S->getNameInfo();
8142   if (NameInfo.getName()) {
8143     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8144     if (!NameInfo.getName())
8145       return StmtError();
8146   }
8147 
8148   // Check whether anything changed.
8149   if (!getDerived().AlwaysRebuild() &&
8150       QualifierLoc == S->getQualifierLoc() &&
8151       NameInfo.getName() == S->getNameInfo().getName())
8152     return S;
8153 
8154   // Determine whether this name exists, if we can.
8155   CXXScopeSpec SS;
8156   SS.Adopt(QualifierLoc);
8157   bool Dependent = false;
8158   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8159   case Sema::IER_Exists:
8160     if (S->isIfExists())
8161       break;
8162 
8163     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8164 
8165   case Sema::IER_DoesNotExist:
8166     if (S->isIfNotExists())
8167       break;
8168 
8169     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8170 
8171   case Sema::IER_Dependent:
8172     Dependent = true;
8173     break;
8174 
8175   case Sema::IER_Error:
8176     return StmtError();
8177   }
8178 
8179   // We need to continue with the instantiation, so do so now.
8180   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8181   if (SubStmt.isInvalid())
8182     return StmtError();
8183 
8184   // If we have resolved the name, just transform to the substatement.
8185   if (!Dependent)
8186     return SubStmt;
8187 
8188   // The name is still dependent, so build a dependent expression again.
8189   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8190                                                    S->isIfExists(),
8191                                                    QualifierLoc,
8192                                                    NameInfo,
8193                                                    SubStmt.get());
8194 }
8195 
8196 template<typename Derived>
8197 ExprResult
8198 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8199   NestedNameSpecifierLoc QualifierLoc;
8200   if (E->getQualifierLoc()) {
8201     QualifierLoc
8202     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8203     if (!QualifierLoc)
8204       return ExprError();
8205   }
8206 
8207   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8208     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8209   if (!PD)
8210     return ExprError();
8211 
8212   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8213   if (Base.isInvalid())
8214     return ExprError();
8215 
8216   return new (SemaRef.getASTContext())
8217       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8218                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8219                         QualifierLoc, E->getMemberLoc());
8220 }
8221 
8222 template <typename Derived>
8223 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8224     MSPropertySubscriptExpr *E) {
8225   auto BaseRes = getDerived().TransformExpr(E->getBase());
8226   if (BaseRes.isInvalid())
8227     return ExprError();
8228   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8229   if (IdxRes.isInvalid())
8230     return ExprError();
8231 
8232   if (!getDerived().AlwaysRebuild() &&
8233       BaseRes.get() == E->getBase() &&
8234       IdxRes.get() == E->getIdx())
8235     return E;
8236 
8237   return getDerived().RebuildArraySubscriptExpr(
8238       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8239 }
8240 
8241 template <typename Derived>
8242 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8243   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8244   if (TryBlock.isInvalid())
8245     return StmtError();
8246 
8247   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8248   if (Handler.isInvalid())
8249     return StmtError();
8250 
8251   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8252       Handler.get() == S->getHandler())
8253     return S;
8254 
8255   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8256                                         TryBlock.get(), Handler.get());
8257 }
8258 
8259 template <typename Derived>
8260 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8261   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8262   if (Block.isInvalid())
8263     return StmtError();
8264 
8265   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8266 }
8267 
8268 template <typename Derived>
8269 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8270   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8271   if (FilterExpr.isInvalid())
8272     return StmtError();
8273 
8274   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8275   if (Block.isInvalid())
8276     return StmtError();
8277 
8278   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8279                                            Block.get());
8280 }
8281 
8282 template <typename Derived>
8283 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8284   if (isa<SEHFinallyStmt>(Handler))
8285     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8286   else
8287     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8288 }
8289 
8290 template<typename Derived>
8291 StmtResult
8292 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8293   return S;
8294 }
8295 
8296 //===----------------------------------------------------------------------===//
8297 // OpenMP directive transformation
8298 //===----------------------------------------------------------------------===//
8299 template <typename Derived>
8300 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8301     OMPExecutableDirective *D) {
8302 
8303   // Transform the clauses
8304   llvm::SmallVector<OMPClause *, 16> TClauses;
8305   ArrayRef<OMPClause *> Clauses = D->clauses();
8306   TClauses.reserve(Clauses.size());
8307   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8308        I != E; ++I) {
8309     if (*I) {
8310       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8311       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8312       getDerived().getSema().EndOpenMPClause();
8313       if (Clause)
8314         TClauses.push_back(Clause);
8315     } else {
8316       TClauses.push_back(nullptr);
8317     }
8318   }
8319   StmtResult AssociatedStmt;
8320   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8321     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8322                                                   /*CurScope=*/nullptr);
8323     StmtResult Body;
8324     {
8325       Sema::CompoundScopeRAII CompoundScope(getSema());
8326       Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
8327       Body = getDerived().TransformStmt(CS);
8328     }
8329     AssociatedStmt =
8330         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8331     if (AssociatedStmt.isInvalid()) {
8332       return StmtError();
8333     }
8334   }
8335   if (TClauses.size() != Clauses.size()) {
8336     return StmtError();
8337   }
8338 
8339   // Transform directive name for 'omp critical' directive.
8340   DeclarationNameInfo DirName;
8341   if (D->getDirectiveKind() == OMPD_critical) {
8342     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8343     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8344   }
8345   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8346   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8347     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8348   } else if (D->getDirectiveKind() == OMPD_cancel) {
8349     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8350   }
8351 
8352   return getDerived().RebuildOMPExecutableDirective(
8353       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8354       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8355 }
8356 
8357 template <typename Derived>
8358 StmtResult
8359 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8360   DeclarationNameInfo DirName;
8361   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8362                                              D->getBeginLoc());
8363   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8364   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8365   return Res;
8366 }
8367 
8368 template <typename Derived>
8369 StmtResult
8370 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8371   DeclarationNameInfo DirName;
8372   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8373                                              D->getBeginLoc());
8374   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8375   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8376   return Res;
8377 }
8378 
8379 template <typename Derived>
8380 StmtResult
8381 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8382   DeclarationNameInfo DirName;
8383   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8384                                              D->getBeginLoc());
8385   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8386   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8387   return Res;
8388 }
8389 
8390 template <typename Derived>
8391 StmtResult
8392 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8393   DeclarationNameInfo DirName;
8394   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8395                                              D->getBeginLoc());
8396   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8397   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8398   return Res;
8399 }
8400 
8401 template <typename Derived>
8402 StmtResult
8403 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8404   DeclarationNameInfo DirName;
8405   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8406                                              D->getBeginLoc());
8407   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8408   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8409   return Res;
8410 }
8411 
8412 template <typename Derived>
8413 StmtResult
8414 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8415   DeclarationNameInfo DirName;
8416   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8417                                              D->getBeginLoc());
8418   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8419   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8420   return Res;
8421 }
8422 
8423 template <typename Derived>
8424 StmtResult
8425 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8426   DeclarationNameInfo DirName;
8427   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8428                                              D->getBeginLoc());
8429   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8430   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8431   return Res;
8432 }
8433 
8434 template <typename Derived>
8435 StmtResult
8436 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8437   DeclarationNameInfo DirName;
8438   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8439                                              D->getBeginLoc());
8440   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8441   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8442   return Res;
8443 }
8444 
8445 template <typename Derived>
8446 StmtResult
8447 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8448   getDerived().getSema().StartOpenMPDSABlock(
8449       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8450   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8451   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8452   return Res;
8453 }
8454 
8455 template <typename Derived>
8456 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8457     OMPParallelForDirective *D) {
8458   DeclarationNameInfo DirName;
8459   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8460                                              nullptr, D->getBeginLoc());
8461   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8462   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8463   return Res;
8464 }
8465 
8466 template <typename Derived>
8467 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8468     OMPParallelForSimdDirective *D) {
8469   DeclarationNameInfo DirName;
8470   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8471                                              nullptr, D->getBeginLoc());
8472   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8473   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8474   return Res;
8475 }
8476 
8477 template <typename Derived>
8478 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8479     OMPParallelMasterDirective *D) {
8480   DeclarationNameInfo DirName;
8481   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8482                                              nullptr, D->getBeginLoc());
8483   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8484   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8485   return Res;
8486 }
8487 
8488 template <typename Derived>
8489 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8490     OMPParallelSectionsDirective *D) {
8491   DeclarationNameInfo DirName;
8492   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8493                                              nullptr, D->getBeginLoc());
8494   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8495   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8496   return Res;
8497 }
8498 
8499 template <typename Derived>
8500 StmtResult
8501 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8502   DeclarationNameInfo DirName;
8503   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8504                                              D->getBeginLoc());
8505   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8506   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8507   return Res;
8508 }
8509 
8510 template <typename Derived>
8511 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8512     OMPTaskyieldDirective *D) {
8513   DeclarationNameInfo DirName;
8514   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8515                                              D->getBeginLoc());
8516   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8517   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8518   return Res;
8519 }
8520 
8521 template <typename Derived>
8522 StmtResult
8523 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8524   DeclarationNameInfo DirName;
8525   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8526                                              D->getBeginLoc());
8527   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8528   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8529   return Res;
8530 }
8531 
8532 template <typename Derived>
8533 StmtResult
8534 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8535   DeclarationNameInfo DirName;
8536   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8537                                              D->getBeginLoc());
8538   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8539   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8540   return Res;
8541 }
8542 
8543 template <typename Derived>
8544 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8545     OMPTaskgroupDirective *D) {
8546   DeclarationNameInfo DirName;
8547   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8548                                              D->getBeginLoc());
8549   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8550   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8551   return Res;
8552 }
8553 
8554 template <typename Derived>
8555 StmtResult
8556 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8557   DeclarationNameInfo DirName;
8558   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8559                                              D->getBeginLoc());
8560   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8561   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8562   return Res;
8563 }
8564 
8565 template <typename Derived>
8566 StmtResult
8567 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
8568   DeclarationNameInfo DirName;
8569   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
8570                                              D->getBeginLoc());
8571   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8572   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8573   return Res;
8574 }
8575 
8576 template <typename Derived>
8577 StmtResult
8578 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
8579   DeclarationNameInfo DirName;
8580   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
8581                                              D->getBeginLoc());
8582   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8583   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8584   return Res;
8585 }
8586 
8587 template <typename Derived>
8588 StmtResult
8589 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8590   DeclarationNameInfo DirName;
8591   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8592                                              D->getBeginLoc());
8593   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8594   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8595   return Res;
8596 }
8597 
8598 template <typename Derived>
8599 StmtResult
8600 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8601   DeclarationNameInfo DirName;
8602   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8603                                              D->getBeginLoc());
8604   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8605   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8606   return Res;
8607 }
8608 
8609 template <typename Derived>
8610 StmtResult
8611 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8612   DeclarationNameInfo DirName;
8613   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8614                                              D->getBeginLoc());
8615   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8616   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8617   return Res;
8618 }
8619 
8620 template <typename Derived>
8621 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8622     OMPTargetDataDirective *D) {
8623   DeclarationNameInfo DirName;
8624   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8625                                              D->getBeginLoc());
8626   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8627   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8628   return Res;
8629 }
8630 
8631 template <typename Derived>
8632 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8633     OMPTargetEnterDataDirective *D) {
8634   DeclarationNameInfo DirName;
8635   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8636                                              nullptr, D->getBeginLoc());
8637   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8638   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8639   return Res;
8640 }
8641 
8642 template <typename Derived>
8643 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8644     OMPTargetExitDataDirective *D) {
8645   DeclarationNameInfo DirName;
8646   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8647                                              nullptr, D->getBeginLoc());
8648   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8649   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8650   return Res;
8651 }
8652 
8653 template <typename Derived>
8654 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8655     OMPTargetParallelDirective *D) {
8656   DeclarationNameInfo DirName;
8657   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8658                                              nullptr, D->getBeginLoc());
8659   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8660   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8661   return Res;
8662 }
8663 
8664 template <typename Derived>
8665 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8666     OMPTargetParallelForDirective *D) {
8667   DeclarationNameInfo DirName;
8668   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8669                                              nullptr, D->getBeginLoc());
8670   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8671   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8672   return Res;
8673 }
8674 
8675 template <typename Derived>
8676 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8677     OMPTargetUpdateDirective *D) {
8678   DeclarationNameInfo DirName;
8679   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8680                                              nullptr, D->getBeginLoc());
8681   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8682   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8683   return Res;
8684 }
8685 
8686 template <typename Derived>
8687 StmtResult
8688 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8689   DeclarationNameInfo DirName;
8690   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8691                                              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>::TransformOMPCancellationPointDirective(
8699     OMPCancellationPointDirective *D) {
8700   DeclarationNameInfo DirName;
8701   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, 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
8710 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8711   DeclarationNameInfo DirName;
8712   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8713                                              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
8721 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8722   DeclarationNameInfo DirName;
8723   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8724                                              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>::TransformOMPTaskLoopSimdDirective(
8732     OMPTaskLoopSimdDirective *D) {
8733   DeclarationNameInfo DirName;
8734   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, 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 TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8743     OMPMasterTaskLoopDirective *D) {
8744   DeclarationNameInfo DirName;
8745   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8746                                              nullptr, 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>::TransformOMPMasterTaskLoopSimdDirective(
8754     OMPMasterTaskLoopSimdDirective *D) {
8755   DeclarationNameInfo DirName;
8756   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8757                                              nullptr, 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 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8765     OMPParallelMasterTaskLoopDirective *D) {
8766   DeclarationNameInfo DirName;
8767   getDerived().getSema().StartOpenMPDSABlock(
8768       OMPD_parallel_master_taskloop, DirName, nullptr, 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>::TransformOMPParallelMasterTaskLoopSimdDirective(
8777     OMPParallelMasterTaskLoopSimdDirective *D) {
8778   DeclarationNameInfo DirName;
8779   getDerived().getSema().StartOpenMPDSABlock(
8780       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
8781   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8782   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8783   return Res;
8784 }
8785 
8786 template <typename Derived>
8787 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8788     OMPDistributeDirective *D) {
8789   DeclarationNameInfo DirName;
8790   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8791                                              D->getBeginLoc());
8792   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8793   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8794   return Res;
8795 }
8796 
8797 template <typename Derived>
8798 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8799     OMPDistributeParallelForDirective *D) {
8800   DeclarationNameInfo DirName;
8801   getDerived().getSema().StartOpenMPDSABlock(
8802       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8803   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8804   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8805   return Res;
8806 }
8807 
8808 template <typename Derived>
8809 StmtResult
8810 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8811     OMPDistributeParallelForSimdDirective *D) {
8812   DeclarationNameInfo DirName;
8813   getDerived().getSema().StartOpenMPDSABlock(
8814       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8815   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8816   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8817   return Res;
8818 }
8819 
8820 template <typename Derived>
8821 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8822     OMPDistributeSimdDirective *D) {
8823   DeclarationNameInfo DirName;
8824   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8825                                              nullptr, D->getBeginLoc());
8826   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8827   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8828   return Res;
8829 }
8830 
8831 template <typename Derived>
8832 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8833     OMPTargetParallelForSimdDirective *D) {
8834   DeclarationNameInfo DirName;
8835   getDerived().getSema().StartOpenMPDSABlock(
8836       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8837   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8838   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8839   return Res;
8840 }
8841 
8842 template <typename Derived>
8843 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8844     OMPTargetSimdDirective *D) {
8845   DeclarationNameInfo DirName;
8846   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8847                                              D->getBeginLoc());
8848   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8849   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8850   return Res;
8851 }
8852 
8853 template <typename Derived>
8854 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8855     OMPTeamsDistributeDirective *D) {
8856   DeclarationNameInfo DirName;
8857   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8858                                              nullptr, D->getBeginLoc());
8859   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8860   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8861   return Res;
8862 }
8863 
8864 template <typename Derived>
8865 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8866     OMPTeamsDistributeSimdDirective *D) {
8867   DeclarationNameInfo DirName;
8868   getDerived().getSema().StartOpenMPDSABlock(
8869       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8870   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8871   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8872   return Res;
8873 }
8874 
8875 template <typename Derived>
8876 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8877     OMPTeamsDistributeParallelForSimdDirective *D) {
8878   DeclarationNameInfo DirName;
8879   getDerived().getSema().StartOpenMPDSABlock(
8880       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8881       D->getBeginLoc());
8882   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8883   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8884   return Res;
8885 }
8886 
8887 template <typename Derived>
8888 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8889     OMPTeamsDistributeParallelForDirective *D) {
8890   DeclarationNameInfo DirName;
8891   getDerived().getSema().StartOpenMPDSABlock(
8892       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8893   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8894   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8895   return Res;
8896 }
8897 
8898 template <typename Derived>
8899 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8900     OMPTargetTeamsDirective *D) {
8901   DeclarationNameInfo DirName;
8902   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8903                                              nullptr, D->getBeginLoc());
8904   auto Res = getDerived().TransformOMPExecutableDirective(D);
8905   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8906   return Res;
8907 }
8908 
8909 template <typename Derived>
8910 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8911     OMPTargetTeamsDistributeDirective *D) {
8912   DeclarationNameInfo DirName;
8913   getDerived().getSema().StartOpenMPDSABlock(
8914       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8915   auto Res = getDerived().TransformOMPExecutableDirective(D);
8916   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8917   return Res;
8918 }
8919 
8920 template <typename Derived>
8921 StmtResult
8922 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8923     OMPTargetTeamsDistributeParallelForDirective *D) {
8924   DeclarationNameInfo DirName;
8925   getDerived().getSema().StartOpenMPDSABlock(
8926       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8927       D->getBeginLoc());
8928   auto Res = getDerived().TransformOMPExecutableDirective(D);
8929   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8930   return Res;
8931 }
8932 
8933 template <typename Derived>
8934 StmtResult TreeTransform<Derived>::
8935     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8936         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8937   DeclarationNameInfo DirName;
8938   getDerived().getSema().StartOpenMPDSABlock(
8939       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8940       D->getBeginLoc());
8941   auto Res = getDerived().TransformOMPExecutableDirective(D);
8942   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8943   return Res;
8944 }
8945 
8946 template <typename Derived>
8947 StmtResult
8948 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8949     OMPTargetTeamsDistributeSimdDirective *D) {
8950   DeclarationNameInfo DirName;
8951   getDerived().getSema().StartOpenMPDSABlock(
8952       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8953   auto Res = getDerived().TransformOMPExecutableDirective(D);
8954   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8955   return Res;
8956 }
8957 
8958 
8959 //===----------------------------------------------------------------------===//
8960 // OpenMP clause transformation
8961 //===----------------------------------------------------------------------===//
8962 template <typename Derived>
8963 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8964   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8965   if (Cond.isInvalid())
8966     return nullptr;
8967   return getDerived().RebuildOMPIfClause(
8968       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8969       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8970 }
8971 
8972 template <typename Derived>
8973 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8974   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8975   if (Cond.isInvalid())
8976     return nullptr;
8977   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8978                                             C->getLParenLoc(), C->getEndLoc());
8979 }
8980 
8981 template <typename Derived>
8982 OMPClause *
8983 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8984   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8985   if (NumThreads.isInvalid())
8986     return nullptr;
8987   return getDerived().RebuildOMPNumThreadsClause(
8988       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8989 }
8990 
8991 template <typename Derived>
8992 OMPClause *
8993 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8994   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8995   if (E.isInvalid())
8996     return nullptr;
8997   return getDerived().RebuildOMPSafelenClause(
8998       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8999 }
9000 
9001 template <typename Derived>
9002 OMPClause *
9003 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9004   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9005   if (E.isInvalid())
9006     return nullptr;
9007   return getDerived().RebuildOMPAllocatorClause(
9008       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9009 }
9010 
9011 template <typename Derived>
9012 OMPClause *
9013 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9014   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9015   if (E.isInvalid())
9016     return nullptr;
9017   return getDerived().RebuildOMPSimdlenClause(
9018       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9019 }
9020 
9021 template <typename Derived>
9022 OMPClause *
9023 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9024   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9025   if (E.isInvalid())
9026     return nullptr;
9027   return getDerived().RebuildOMPCollapseClause(
9028       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9029 }
9030 
9031 template <typename Derived>
9032 OMPClause *
9033 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9034   return getDerived().RebuildOMPDefaultClause(
9035       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9036       C->getLParenLoc(), C->getEndLoc());
9037 }
9038 
9039 template <typename Derived>
9040 OMPClause *
9041 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9042   return getDerived().RebuildOMPProcBindClause(
9043       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9044       C->getLParenLoc(), C->getEndLoc());
9045 }
9046 
9047 template <typename Derived>
9048 OMPClause *
9049 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9050   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9051   if (E.isInvalid())
9052     return nullptr;
9053   return getDerived().RebuildOMPScheduleClause(
9054       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9055       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9056       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9057       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9058 }
9059 
9060 template <typename Derived>
9061 OMPClause *
9062 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9063   ExprResult E;
9064   if (auto *Num = C->getNumForLoops()) {
9065     E = getDerived().TransformExpr(Num);
9066     if (E.isInvalid())
9067       return nullptr;
9068   }
9069   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9070                                               C->getLParenLoc(), E.get());
9071 }
9072 
9073 template <typename Derived>
9074 OMPClause *
9075 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9076   ExprResult E;
9077   if (Expr *Evt = C->getEventHandler()) {
9078     E = getDerived().TransformExpr(Evt);
9079     if (E.isInvalid())
9080       return nullptr;
9081   }
9082   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9083                                              C->getLParenLoc(), C->getEndLoc());
9084 }
9085 
9086 template <typename Derived>
9087 OMPClause *
9088 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9089   // No need to rebuild this clause, no template-dependent parameters.
9090   return C;
9091 }
9092 
9093 template <typename Derived>
9094 OMPClause *
9095 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9096   // No need to rebuild this clause, no template-dependent parameters.
9097   return C;
9098 }
9099 
9100 template <typename Derived>
9101 OMPClause *
9102 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9103   // No need to rebuild this clause, no template-dependent parameters.
9104   return C;
9105 }
9106 
9107 template <typename Derived>
9108 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9109   // No need to rebuild this clause, no template-dependent parameters.
9110   return C;
9111 }
9112 
9113 template <typename Derived>
9114 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9115   // No need to rebuild this clause, no template-dependent parameters.
9116   return C;
9117 }
9118 
9119 template <typename Derived>
9120 OMPClause *
9121 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9122   // No need to rebuild this clause, no template-dependent parameters.
9123   return C;
9124 }
9125 
9126 template <typename Derived>
9127 OMPClause *
9128 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9129   // No need to rebuild this clause, no template-dependent parameters.
9130   return C;
9131 }
9132 
9133 template <typename Derived>
9134 OMPClause *
9135 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9136   // No need to rebuild this clause, no template-dependent parameters.
9137   return C;
9138 }
9139 
9140 template <typename Derived>
9141 OMPClause *
9142 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9143   // No need to rebuild this clause, no template-dependent parameters.
9144   return C;
9145 }
9146 
9147 template <typename Derived>
9148 OMPClause *
9149 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9150   // No need to rebuild this clause, no template-dependent parameters.
9151   return C;
9152 }
9153 
9154 template <typename Derived>
9155 OMPClause *
9156 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9157   // No need to rebuild this clause, no template-dependent parameters.
9158   return C;
9159 }
9160 
9161 template <typename Derived>
9162 OMPClause *
9163 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9164   // No need to rebuild this clause, no template-dependent parameters.
9165   return C;
9166 }
9167 
9168 template <typename Derived>
9169 OMPClause *
9170 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9171   // No need to rebuild this clause, no template-dependent parameters.
9172   return C;
9173 }
9174 
9175 template <typename Derived>
9176 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9177   // No need to rebuild this clause, no template-dependent parameters.
9178   return C;
9179 }
9180 
9181 template <typename Derived>
9182 OMPClause *
9183 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9184   // No need to rebuild this clause, no template-dependent parameters.
9185   return C;
9186 }
9187 
9188 template <typename Derived>
9189 OMPClause *
9190 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9191   // No need to rebuild this clause, no template-dependent parameters.
9192   return C;
9193 }
9194 
9195 template <typename Derived>
9196 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9197     OMPUnifiedAddressClause *C) {
9198   llvm_unreachable("unified_address clause cannot appear in dependent context");
9199 }
9200 
9201 template <typename Derived>
9202 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9203     OMPUnifiedSharedMemoryClause *C) {
9204   llvm_unreachable(
9205       "unified_shared_memory clause cannot appear in dependent context");
9206 }
9207 
9208 template <typename Derived>
9209 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9210     OMPReverseOffloadClause *C) {
9211   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
9212 }
9213 
9214 template <typename Derived>
9215 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9216     OMPDynamicAllocatorsClause *C) {
9217   llvm_unreachable(
9218       "dynamic_allocators clause cannot appear in dependent context");
9219 }
9220 
9221 template <typename Derived>
9222 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9223     OMPAtomicDefaultMemOrderClause *C) {
9224   llvm_unreachable(
9225       "atomic_default_mem_order clause cannot appear in dependent context");
9226 }
9227 
9228 template <typename Derived>
9229 OMPClause *
9230 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9231   llvm::SmallVector<Expr *, 16> Vars;
9232   Vars.reserve(C->varlist_size());
9233   for (auto *VE : C->varlists()) {
9234     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9235     if (EVar.isInvalid())
9236       return nullptr;
9237     Vars.push_back(EVar.get());
9238   }
9239   return getDerived().RebuildOMPPrivateClause(
9240       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9241 }
9242 
9243 template <typename Derived>
9244 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
9245     OMPFirstprivateClause *C) {
9246   llvm::SmallVector<Expr *, 16> Vars;
9247   Vars.reserve(C->varlist_size());
9248   for (auto *VE : C->varlists()) {
9249     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9250     if (EVar.isInvalid())
9251       return nullptr;
9252     Vars.push_back(EVar.get());
9253   }
9254   return getDerived().RebuildOMPFirstprivateClause(
9255       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9256 }
9257 
9258 template <typename Derived>
9259 OMPClause *
9260 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
9261   llvm::SmallVector<Expr *, 16> Vars;
9262   Vars.reserve(C->varlist_size());
9263   for (auto *VE : C->varlists()) {
9264     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9265     if (EVar.isInvalid())
9266       return nullptr;
9267     Vars.push_back(EVar.get());
9268   }
9269   return getDerived().RebuildOMPLastprivateClause(
9270       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
9271       C->getLParenLoc(), C->getEndLoc());
9272 }
9273 
9274 template <typename Derived>
9275 OMPClause *
9276 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
9277   llvm::SmallVector<Expr *, 16> Vars;
9278   Vars.reserve(C->varlist_size());
9279   for (auto *VE : C->varlists()) {
9280     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9281     if (EVar.isInvalid())
9282       return nullptr;
9283     Vars.push_back(EVar.get());
9284   }
9285   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
9286                                              C->getLParenLoc(), C->getEndLoc());
9287 }
9288 
9289 template <typename Derived>
9290 OMPClause *
9291 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
9292   llvm::SmallVector<Expr *, 16> Vars;
9293   Vars.reserve(C->varlist_size());
9294   for (auto *VE : C->varlists()) {
9295     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9296     if (EVar.isInvalid())
9297       return nullptr;
9298     Vars.push_back(EVar.get());
9299   }
9300   CXXScopeSpec ReductionIdScopeSpec;
9301   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9302 
9303   DeclarationNameInfo NameInfo = C->getNameInfo();
9304   if (NameInfo.getName()) {
9305     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9306     if (!NameInfo.getName())
9307       return nullptr;
9308   }
9309   // Build a list of all UDR decls with the same names ranged by the Scopes.
9310   // The Scope boundary is a duplication of the previous decl.
9311   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9312   for (auto *E : C->reduction_ops()) {
9313     // Transform all the decls.
9314     if (E) {
9315       auto *ULE = cast<UnresolvedLookupExpr>(E);
9316       UnresolvedSet<8> Decls;
9317       for (auto *D : ULE->decls()) {
9318         NamedDecl *InstD =
9319             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9320         Decls.addDecl(InstD, InstD->getAccess());
9321       }
9322       UnresolvedReductions.push_back(
9323        UnresolvedLookupExpr::Create(
9324           SemaRef.Context, /*NamingClass=*/nullptr,
9325           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
9326           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
9327           Decls.begin(), Decls.end()));
9328     } else
9329       UnresolvedReductions.push_back(nullptr);
9330   }
9331   return getDerived().RebuildOMPReductionClause(
9332       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
9333       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
9334       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9335 }
9336 
9337 template <typename Derived>
9338 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
9339     OMPTaskReductionClause *C) {
9340   llvm::SmallVector<Expr *, 16> Vars;
9341   Vars.reserve(C->varlist_size());
9342   for (auto *VE : C->varlists()) {
9343     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9344     if (EVar.isInvalid())
9345       return nullptr;
9346     Vars.push_back(EVar.get());
9347   }
9348   CXXScopeSpec ReductionIdScopeSpec;
9349   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9350 
9351   DeclarationNameInfo NameInfo = C->getNameInfo();
9352   if (NameInfo.getName()) {
9353     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9354     if (!NameInfo.getName())
9355       return nullptr;
9356   }
9357   // Build a list of all UDR decls with the same names ranged by the Scopes.
9358   // The Scope boundary is a duplication of the previous decl.
9359   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9360   for (auto *E : C->reduction_ops()) {
9361     // Transform all the decls.
9362     if (E) {
9363       auto *ULE = cast<UnresolvedLookupExpr>(E);
9364       UnresolvedSet<8> Decls;
9365       for (auto *D : ULE->decls()) {
9366         NamedDecl *InstD =
9367             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9368         Decls.addDecl(InstD, InstD->getAccess());
9369       }
9370       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9371           SemaRef.Context, /*NamingClass=*/nullptr,
9372           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9373           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9374     } else
9375       UnresolvedReductions.push_back(nullptr);
9376   }
9377   return getDerived().RebuildOMPTaskReductionClause(
9378       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9379       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9380 }
9381 
9382 template <typename Derived>
9383 OMPClause *
9384 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
9385   llvm::SmallVector<Expr *, 16> Vars;
9386   Vars.reserve(C->varlist_size());
9387   for (auto *VE : C->varlists()) {
9388     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9389     if (EVar.isInvalid())
9390       return nullptr;
9391     Vars.push_back(EVar.get());
9392   }
9393   CXXScopeSpec ReductionIdScopeSpec;
9394   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9395 
9396   DeclarationNameInfo NameInfo = C->getNameInfo();
9397   if (NameInfo.getName()) {
9398     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9399     if (!NameInfo.getName())
9400       return nullptr;
9401   }
9402   // Build a list of all UDR decls with the same names ranged by the Scopes.
9403   // The Scope boundary is a duplication of the previous decl.
9404   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9405   for (auto *E : C->reduction_ops()) {
9406     // Transform all the decls.
9407     if (E) {
9408       auto *ULE = cast<UnresolvedLookupExpr>(E);
9409       UnresolvedSet<8> Decls;
9410       for (auto *D : ULE->decls()) {
9411         NamedDecl *InstD =
9412             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9413         Decls.addDecl(InstD, InstD->getAccess());
9414       }
9415       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9416           SemaRef.Context, /*NamingClass=*/nullptr,
9417           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9418           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9419     } else
9420       UnresolvedReductions.push_back(nullptr);
9421   }
9422   return getDerived().RebuildOMPInReductionClause(
9423       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9424       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9425 }
9426 
9427 template <typename Derived>
9428 OMPClause *
9429 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
9430   llvm::SmallVector<Expr *, 16> Vars;
9431   Vars.reserve(C->varlist_size());
9432   for (auto *VE : C->varlists()) {
9433     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9434     if (EVar.isInvalid())
9435       return nullptr;
9436     Vars.push_back(EVar.get());
9437   }
9438   ExprResult Step = getDerived().TransformExpr(C->getStep());
9439   if (Step.isInvalid())
9440     return nullptr;
9441   return getDerived().RebuildOMPLinearClause(
9442       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
9443       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
9444 }
9445 
9446 template <typename Derived>
9447 OMPClause *
9448 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
9449   llvm::SmallVector<Expr *, 16> Vars;
9450   Vars.reserve(C->varlist_size());
9451   for (auto *VE : C->varlists()) {
9452     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9453     if (EVar.isInvalid())
9454       return nullptr;
9455     Vars.push_back(EVar.get());
9456   }
9457   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
9458   if (Alignment.isInvalid())
9459     return nullptr;
9460   return getDerived().RebuildOMPAlignedClause(
9461       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
9462       C->getColonLoc(), C->getEndLoc());
9463 }
9464 
9465 template <typename Derived>
9466 OMPClause *
9467 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
9468   llvm::SmallVector<Expr *, 16> Vars;
9469   Vars.reserve(C->varlist_size());
9470   for (auto *VE : C->varlists()) {
9471     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9472     if (EVar.isInvalid())
9473       return nullptr;
9474     Vars.push_back(EVar.get());
9475   }
9476   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
9477                                              C->getLParenLoc(), C->getEndLoc());
9478 }
9479 
9480 template <typename Derived>
9481 OMPClause *
9482 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
9483   llvm::SmallVector<Expr *, 16> Vars;
9484   Vars.reserve(C->varlist_size());
9485   for (auto *VE : C->varlists()) {
9486     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9487     if (EVar.isInvalid())
9488       return nullptr;
9489     Vars.push_back(EVar.get());
9490   }
9491   return getDerived().RebuildOMPCopyprivateClause(
9492       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9493 }
9494 
9495 template <typename Derived>
9496 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
9497   llvm::SmallVector<Expr *, 16> Vars;
9498   Vars.reserve(C->varlist_size());
9499   for (auto *VE : C->varlists()) {
9500     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9501     if (EVar.isInvalid())
9502       return nullptr;
9503     Vars.push_back(EVar.get());
9504   }
9505   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9506                                             C->getLParenLoc(), C->getEndLoc());
9507 }
9508 
9509 template <typename Derived>
9510 OMPClause *
9511 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
9512   ExprResult E = getDerived().TransformExpr(C->getDepobj());
9513   if (E.isInvalid())
9514     return nullptr;
9515   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
9516                                              C->getLParenLoc(), C->getEndLoc());
9517 }
9518 
9519 template <typename Derived>
9520 OMPClause *
9521 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9522   llvm::SmallVector<Expr *, 16> Vars;
9523   Expr *DepModifier = C->getModifier();
9524   if (DepModifier) {
9525     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
9526     if (DepModRes.isInvalid())
9527       return nullptr;
9528     DepModifier = DepModRes.get();
9529   }
9530   Vars.reserve(C->varlist_size());
9531   for (auto *VE : C->varlists()) {
9532     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9533     if (EVar.isInvalid())
9534       return nullptr;
9535     Vars.push_back(EVar.get());
9536   }
9537   return getDerived().RebuildOMPDependClause(
9538       DepModifier, C->getDependencyKind(), C->getDependencyLoc(),
9539       C->getColonLoc(), Vars, C->getBeginLoc(), C->getLParenLoc(),
9540       C->getEndLoc());
9541 }
9542 
9543 template <typename Derived>
9544 OMPClause *
9545 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9546   ExprResult E = getDerived().TransformExpr(C->getDevice());
9547   if (E.isInvalid())
9548     return nullptr;
9549   return getDerived().RebuildOMPDeviceClause(
9550       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9551       C->getModifierLoc(), C->getEndLoc());
9552 }
9553 
9554 template <typename Derived, class T>
9555 bool transformOMPMappableExprListClause(
9556     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9557     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9558     DeclarationNameInfo &MapperIdInfo,
9559     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9560   // Transform expressions in the list.
9561   Vars.reserve(C->varlist_size());
9562   for (auto *VE : C->varlists()) {
9563     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9564     if (EVar.isInvalid())
9565       return true;
9566     Vars.push_back(EVar.get());
9567   }
9568   // Transform mapper scope specifier and identifier.
9569   NestedNameSpecifierLoc QualifierLoc;
9570   if (C->getMapperQualifierLoc()) {
9571     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9572         C->getMapperQualifierLoc());
9573     if (!QualifierLoc)
9574       return true;
9575   }
9576   MapperIdScopeSpec.Adopt(QualifierLoc);
9577   MapperIdInfo = C->getMapperIdInfo();
9578   if (MapperIdInfo.getName()) {
9579     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9580     if (!MapperIdInfo.getName())
9581       return true;
9582   }
9583   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9584   // the previous user-defined mapper lookup in dependent environment.
9585   for (auto *E : C->mapperlists()) {
9586     // Transform all the decls.
9587     if (E) {
9588       auto *ULE = cast<UnresolvedLookupExpr>(E);
9589       UnresolvedSet<8> Decls;
9590       for (auto *D : ULE->decls()) {
9591         NamedDecl *InstD =
9592             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9593         Decls.addDecl(InstD, InstD->getAccess());
9594       }
9595       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9596           TT.getSema().Context, /*NamingClass=*/nullptr,
9597           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9598           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9599           Decls.end()));
9600     } else {
9601       UnresolvedMappers.push_back(nullptr);
9602     }
9603   }
9604   return false;
9605 }
9606 
9607 template <typename Derived>
9608 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9609   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9610   llvm::SmallVector<Expr *, 16> Vars;
9611   CXXScopeSpec MapperIdScopeSpec;
9612   DeclarationNameInfo MapperIdInfo;
9613   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9614   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9615           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9616     return nullptr;
9617   return getDerived().RebuildOMPMapClause(
9618       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9619       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9620       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9621 }
9622 
9623 template <typename Derived>
9624 OMPClause *
9625 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9626   Expr *Allocator = C->getAllocator();
9627   if (Allocator) {
9628     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9629     if (AllocatorRes.isInvalid())
9630       return nullptr;
9631     Allocator = AllocatorRes.get();
9632   }
9633   llvm::SmallVector<Expr *, 16> Vars;
9634   Vars.reserve(C->varlist_size());
9635   for (auto *VE : C->varlists()) {
9636     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9637     if (EVar.isInvalid())
9638       return nullptr;
9639     Vars.push_back(EVar.get());
9640   }
9641   return getDerived().RebuildOMPAllocateClause(
9642       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9643       C->getEndLoc());
9644 }
9645 
9646 template <typename Derived>
9647 OMPClause *
9648 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9649   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9650   if (E.isInvalid())
9651     return nullptr;
9652   return getDerived().RebuildOMPNumTeamsClause(
9653       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9654 }
9655 
9656 template <typename Derived>
9657 OMPClause *
9658 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9659   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9660   if (E.isInvalid())
9661     return nullptr;
9662   return getDerived().RebuildOMPThreadLimitClause(
9663       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9664 }
9665 
9666 template <typename Derived>
9667 OMPClause *
9668 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9669   ExprResult E = getDerived().TransformExpr(C->getPriority());
9670   if (E.isInvalid())
9671     return nullptr;
9672   return getDerived().RebuildOMPPriorityClause(
9673       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9674 }
9675 
9676 template <typename Derived>
9677 OMPClause *
9678 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9679   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9680   if (E.isInvalid())
9681     return nullptr;
9682   return getDerived().RebuildOMPGrainsizeClause(
9683       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9684 }
9685 
9686 template <typename Derived>
9687 OMPClause *
9688 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9689   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9690   if (E.isInvalid())
9691     return nullptr;
9692   return getDerived().RebuildOMPNumTasksClause(
9693       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9694 }
9695 
9696 template <typename Derived>
9697 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9698   ExprResult E = getDerived().TransformExpr(C->getHint());
9699   if (E.isInvalid())
9700     return nullptr;
9701   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9702                                            C->getLParenLoc(), C->getEndLoc());
9703 }
9704 
9705 template <typename Derived>
9706 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9707     OMPDistScheduleClause *C) {
9708   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9709   if (E.isInvalid())
9710     return nullptr;
9711   return getDerived().RebuildOMPDistScheduleClause(
9712       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9713       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9714 }
9715 
9716 template <typename Derived>
9717 OMPClause *
9718 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9719   // Rebuild Defaultmap Clause since we need to invoke the checking of
9720   // defaultmap(none:variable-category) after template initialization.
9721   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
9722                                                  C->getDefaultmapKind(),
9723                                                  C->getBeginLoc(),
9724                                                  C->getLParenLoc(),
9725                                                  C->getDefaultmapModifierLoc(),
9726                                                  C->getDefaultmapKindLoc(),
9727                                                  C->getEndLoc());
9728 }
9729 
9730 template <typename Derived>
9731 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9732   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9733   llvm::SmallVector<Expr *, 16> Vars;
9734   CXXScopeSpec MapperIdScopeSpec;
9735   DeclarationNameInfo MapperIdInfo;
9736   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9737   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9738           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9739     return nullptr;
9740   return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9741                                          Locs, UnresolvedMappers);
9742 }
9743 
9744 template <typename Derived>
9745 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9746   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9747   llvm::SmallVector<Expr *, 16> Vars;
9748   CXXScopeSpec MapperIdScopeSpec;
9749   DeclarationNameInfo MapperIdInfo;
9750   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9751   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9752           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9753     return nullptr;
9754   return getDerived().RebuildOMPFromClause(
9755       Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9756 }
9757 
9758 template <typename Derived>
9759 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9760     OMPUseDevicePtrClause *C) {
9761   llvm::SmallVector<Expr *, 16> Vars;
9762   Vars.reserve(C->varlist_size());
9763   for (auto *VE : C->varlists()) {
9764     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9765     if (EVar.isInvalid())
9766       return nullptr;
9767     Vars.push_back(EVar.get());
9768   }
9769   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9770   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9771 }
9772 
9773 template <typename Derived>
9774 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
9775     OMPUseDeviceAddrClause *C) {
9776   llvm::SmallVector<Expr *, 16> Vars;
9777   Vars.reserve(C->varlist_size());
9778   for (auto *VE : C->varlists()) {
9779     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9780     if (EVar.isInvalid())
9781       return nullptr;
9782     Vars.push_back(EVar.get());
9783   }
9784   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9785   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
9786 }
9787 
9788 template <typename Derived>
9789 OMPClause *
9790 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9791   llvm::SmallVector<Expr *, 16> Vars;
9792   Vars.reserve(C->varlist_size());
9793   for (auto *VE : C->varlists()) {
9794     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9795     if (EVar.isInvalid())
9796       return nullptr;
9797     Vars.push_back(EVar.get());
9798   }
9799   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9800   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9801 }
9802 
9803 template <typename Derived>
9804 OMPClause *
9805 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
9806   llvm::SmallVector<Expr *, 16> Vars;
9807   Vars.reserve(C->varlist_size());
9808   for (auto *VE : C->varlists()) {
9809     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9810     if (EVar.isInvalid())
9811       return nullptr;
9812     Vars.push_back(EVar.get());
9813   }
9814   return getDerived().RebuildOMPNontemporalClause(
9815       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9816 }
9817 
9818 template <typename Derived>
9819 OMPClause *
9820 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
9821   llvm::SmallVector<Expr *, 16> Vars;
9822   Vars.reserve(C->varlist_size());
9823   for (auto *VE : C->varlists()) {
9824     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9825     if (EVar.isInvalid())
9826       return nullptr;
9827     Vars.push_back(EVar.get());
9828   }
9829   return getDerived().RebuildOMPInclusiveClause(
9830       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9831 }
9832 
9833 template <typename Derived>
9834 OMPClause *
9835 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
9836   llvm::SmallVector<Expr *, 16> Vars;
9837   Vars.reserve(C->varlist_size());
9838   for (auto *VE : C->varlists()) {
9839     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9840     if (EVar.isInvalid())
9841       return nullptr;
9842     Vars.push_back(EVar.get());
9843   }
9844   return getDerived().RebuildOMPExclusiveClause(
9845       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9846 }
9847 
9848 template <typename Derived>
9849 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
9850     OMPUsesAllocatorsClause *C) {
9851   SmallVector<Sema::UsesAllocatorsData, 16> Data;
9852   Data.reserve(C->getNumberOfAllocators());
9853   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
9854     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
9855     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
9856     if (Allocator.isInvalid())
9857       continue;
9858     ExprResult AllocatorTraits;
9859     if (Expr *AT = D.AllocatorTraits) {
9860       AllocatorTraits = getDerived().TransformExpr(AT);
9861       if (AllocatorTraits.isInvalid())
9862         continue;
9863     }
9864     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
9865     NewD.Allocator = Allocator.get();
9866     NewD.AllocatorTraits = AllocatorTraits.get();
9867     NewD.LParenLoc = D.LParenLoc;
9868     NewD.RParenLoc = D.RParenLoc;
9869   }
9870   return getDerived().RebuildOMPUsesAllocatorsClause(
9871       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9872 }
9873 
9874 template <typename Derived>
9875 OMPClause *
9876 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
9877   SmallVector<Expr *, 4> Locators;
9878   Locators.reserve(C->varlist_size());
9879   ExprResult ModifierRes;
9880   if (Expr *Modifier = C->getModifier()) {
9881     ModifierRes = getDerived().TransformExpr(Modifier);
9882     if (ModifierRes.isInvalid())
9883       return nullptr;
9884   }
9885   for (Expr *E : C->varlists()) {
9886     ExprResult Locator = getDerived().TransformExpr(E);
9887     if (Locator.isInvalid())
9888       continue;
9889     Locators.push_back(Locator.get());
9890   }
9891   return getDerived().RebuildOMPAffinityClause(
9892       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
9893       ModifierRes.get(), Locators);
9894 }
9895 
9896 template <typename Derived>
9897 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
9898   return getDerived().RebuildOMPOrderClause(C->getKind(), C->getKindKwLoc(),
9899                                             C->getBeginLoc(), C->getLParenLoc(),
9900                                             C->getEndLoc());
9901 }
9902 
9903 //===----------------------------------------------------------------------===//
9904 // Expression transformation
9905 //===----------------------------------------------------------------------===//
9906 template<typename Derived>
9907 ExprResult
9908 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9909   return TransformExpr(E->getSubExpr());
9910 }
9911 
9912 template<typename Derived>
9913 ExprResult
9914 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9915   if (!E->isTypeDependent())
9916     return E;
9917 
9918   return getDerived().RebuildPredefinedExpr(E->getLocation(),
9919                                             E->getIdentKind());
9920 }
9921 
9922 template<typename Derived>
9923 ExprResult
9924 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9925   NestedNameSpecifierLoc QualifierLoc;
9926   if (E->getQualifierLoc()) {
9927     QualifierLoc
9928       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9929     if (!QualifierLoc)
9930       return ExprError();
9931   }
9932 
9933   ValueDecl *ND
9934     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9935                                                          E->getDecl()));
9936   if (!ND)
9937     return ExprError();
9938 
9939   NamedDecl *Found = ND;
9940   if (E->getFoundDecl() != E->getDecl()) {
9941     Found = cast_or_null<NamedDecl>(
9942         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9943     if (!Found)
9944       return ExprError();
9945   }
9946 
9947   DeclarationNameInfo NameInfo = E->getNameInfo();
9948   if (NameInfo.getName()) {
9949     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9950     if (!NameInfo.getName())
9951       return ExprError();
9952   }
9953 
9954   if (!getDerived().AlwaysRebuild() &&
9955       QualifierLoc == E->getQualifierLoc() &&
9956       ND == E->getDecl() &&
9957       Found == E->getFoundDecl() &&
9958       NameInfo.getName() == E->getDecl()->getDeclName() &&
9959       !E->hasExplicitTemplateArgs()) {
9960 
9961     // Mark it referenced in the new context regardless.
9962     // FIXME: this is a bit instantiation-specific.
9963     SemaRef.MarkDeclRefReferenced(E);
9964 
9965     return E;
9966   }
9967 
9968   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9969   if (E->hasExplicitTemplateArgs()) {
9970     TemplateArgs = &TransArgs;
9971     TransArgs.setLAngleLoc(E->getLAngleLoc());
9972     TransArgs.setRAngleLoc(E->getRAngleLoc());
9973     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9974                                                 E->getNumTemplateArgs(),
9975                                                 TransArgs))
9976       return ExprError();
9977   }
9978 
9979   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9980                                          Found, TemplateArgs);
9981 }
9982 
9983 template<typename Derived>
9984 ExprResult
9985 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9986   return E;
9987 }
9988 
9989 template <typename Derived>
9990 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9991     FixedPointLiteral *E) {
9992   return E;
9993 }
9994 
9995 template<typename Derived>
9996 ExprResult
9997 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9998   return E;
9999 }
10000 
10001 template<typename Derived>
10002 ExprResult
10003 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10004   return E;
10005 }
10006 
10007 template<typename Derived>
10008 ExprResult
10009 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10010   return E;
10011 }
10012 
10013 template<typename Derived>
10014 ExprResult
10015 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10016   return E;
10017 }
10018 
10019 template<typename Derived>
10020 ExprResult
10021 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10022   if (FunctionDecl *FD = E->getDirectCallee())
10023     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
10024   return SemaRef.MaybeBindToTemporary(E);
10025 }
10026 
10027 template<typename Derived>
10028 ExprResult
10029 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10030   ExprResult ControllingExpr =
10031     getDerived().TransformExpr(E->getControllingExpr());
10032   if (ControllingExpr.isInvalid())
10033     return ExprError();
10034 
10035   SmallVector<Expr *, 4> AssocExprs;
10036   SmallVector<TypeSourceInfo *, 4> AssocTypes;
10037   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10038     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10039     if (TSI) {
10040       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10041       if (!AssocType)
10042         return ExprError();
10043       AssocTypes.push_back(AssocType);
10044     } else {
10045       AssocTypes.push_back(nullptr);
10046     }
10047 
10048     ExprResult AssocExpr =
10049         getDerived().TransformExpr(Assoc.getAssociationExpr());
10050     if (AssocExpr.isInvalid())
10051       return ExprError();
10052     AssocExprs.push_back(AssocExpr.get());
10053   }
10054 
10055   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10056                                                   E->getDefaultLoc(),
10057                                                   E->getRParenLoc(),
10058                                                   ControllingExpr.get(),
10059                                                   AssocTypes,
10060                                                   AssocExprs);
10061 }
10062 
10063 template<typename Derived>
10064 ExprResult
10065 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10066   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10067   if (SubExpr.isInvalid())
10068     return ExprError();
10069 
10070   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10071     return E;
10072 
10073   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10074                                        E->getRParen());
10075 }
10076 
10077 /// The operand of a unary address-of operator has special rules: it's
10078 /// allowed to refer to a non-static member of a class even if there's no 'this'
10079 /// object available.
10080 template<typename Derived>
10081 ExprResult
10082 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10083   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10084     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10085   else
10086     return getDerived().TransformExpr(E);
10087 }
10088 
10089 template<typename Derived>
10090 ExprResult
10091 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10092   ExprResult SubExpr;
10093   if (E->getOpcode() == UO_AddrOf)
10094     SubExpr = TransformAddressOfOperand(E->getSubExpr());
10095   else
10096     SubExpr = TransformExpr(E->getSubExpr());
10097   if (SubExpr.isInvalid())
10098     return ExprError();
10099 
10100   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10101     return E;
10102 
10103   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10104                                            E->getOpcode(),
10105                                            SubExpr.get());
10106 }
10107 
10108 template<typename Derived>
10109 ExprResult
10110 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10111   // Transform the type.
10112   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10113   if (!Type)
10114     return ExprError();
10115 
10116   // Transform all of the components into components similar to what the
10117   // parser uses.
10118   // FIXME: It would be slightly more efficient in the non-dependent case to
10119   // just map FieldDecls, rather than requiring the rebuilder to look for
10120   // the fields again. However, __builtin_offsetof is rare enough in
10121   // template code that we don't care.
10122   bool ExprChanged = false;
10123   typedef Sema::OffsetOfComponent Component;
10124   SmallVector<Component, 4> Components;
10125   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10126     const OffsetOfNode &ON = E->getComponent(I);
10127     Component Comp;
10128     Comp.isBrackets = true;
10129     Comp.LocStart = ON.getSourceRange().getBegin();
10130     Comp.LocEnd = ON.getSourceRange().getEnd();
10131     switch (ON.getKind()) {
10132     case OffsetOfNode::Array: {
10133       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10134       ExprResult Index = getDerived().TransformExpr(FromIndex);
10135       if (Index.isInvalid())
10136         return ExprError();
10137 
10138       ExprChanged = ExprChanged || Index.get() != FromIndex;
10139       Comp.isBrackets = true;
10140       Comp.U.E = Index.get();
10141       break;
10142     }
10143 
10144     case OffsetOfNode::Field:
10145     case OffsetOfNode::Identifier:
10146       Comp.isBrackets = false;
10147       Comp.U.IdentInfo = ON.getFieldName();
10148       if (!Comp.U.IdentInfo)
10149         continue;
10150 
10151       break;
10152 
10153     case OffsetOfNode::Base:
10154       // Will be recomputed during the rebuild.
10155       continue;
10156     }
10157 
10158     Components.push_back(Comp);
10159   }
10160 
10161   // If nothing changed, retain the existing expression.
10162   if (!getDerived().AlwaysRebuild() &&
10163       Type == E->getTypeSourceInfo() &&
10164       !ExprChanged)
10165     return E;
10166 
10167   // Build a new offsetof expression.
10168   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10169                                           Components, E->getRParenLoc());
10170 }
10171 
10172 template<typename Derived>
10173 ExprResult
10174 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
10175   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
10176          "opaque value expression requires transformation");
10177   return E;
10178 }
10179 
10180 template<typename Derived>
10181 ExprResult
10182 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
10183   return E;
10184 }
10185 
10186 template <typename Derived>
10187 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
10188   llvm::SmallVector<Expr *, 8> Children;
10189   bool Changed = false;
10190   for (Expr *C : E->subExpressions()) {
10191     ExprResult NewC = getDerived().TransformExpr(C);
10192     if (NewC.isInvalid())
10193       return ExprError();
10194     Children.push_back(NewC.get());
10195 
10196     Changed |= NewC.get() != C;
10197   }
10198   if (!getDerived().AlwaysRebuild() && !Changed)
10199     return E;
10200   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
10201                                           Children);
10202 }
10203 
10204 template<typename Derived>
10205 ExprResult
10206 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
10207   // Rebuild the syntactic form.  The original syntactic form has
10208   // opaque-value expressions in it, so strip those away and rebuild
10209   // the result.  This is a really awful way of doing this, but the
10210   // better solution (rebuilding the semantic expressions and
10211   // rebinding OVEs as necessary) doesn't work; we'd need
10212   // TreeTransform to not strip away implicit conversions.
10213   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
10214   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
10215   if (result.isInvalid()) return ExprError();
10216 
10217   // If that gives us a pseudo-object result back, the pseudo-object
10218   // expression must have been an lvalue-to-rvalue conversion which we
10219   // should reapply.
10220   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
10221     result = SemaRef.checkPseudoObjectRValue(result.get());
10222 
10223   return result;
10224 }
10225 
10226 template<typename Derived>
10227 ExprResult
10228 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
10229                                                 UnaryExprOrTypeTraitExpr *E) {
10230   if (E->isArgumentType()) {
10231     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
10232 
10233     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10234     if (!NewT)
10235       return ExprError();
10236 
10237     if (!getDerived().AlwaysRebuild() && OldT == NewT)
10238       return E;
10239 
10240     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
10241                                                     E->getKind(),
10242                                                     E->getSourceRange());
10243   }
10244 
10245   // C++0x [expr.sizeof]p1:
10246   //   The operand is either an expression, which is an unevaluated operand
10247   //   [...]
10248   EnterExpressionEvaluationContext Unevaluated(
10249       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10250       Sema::ReuseLambdaContextDecl);
10251 
10252   // Try to recover if we have something like sizeof(T::X) where X is a type.
10253   // Notably, there must be *exactly* one set of parens if X is a type.
10254   TypeSourceInfo *RecoveryTSI = nullptr;
10255   ExprResult SubExpr;
10256   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
10257   if (auto *DRE =
10258           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
10259     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
10260         PE, DRE, false, &RecoveryTSI);
10261   else
10262     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
10263 
10264   if (RecoveryTSI) {
10265     return getDerived().RebuildUnaryExprOrTypeTrait(
10266         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
10267   } else if (SubExpr.isInvalid())
10268     return ExprError();
10269 
10270   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
10271     return E;
10272 
10273   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
10274                                                   E->getOperatorLoc(),
10275                                                   E->getKind(),
10276                                                   E->getSourceRange());
10277 }
10278 
10279 template<typename Derived>
10280 ExprResult
10281 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
10282   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10283   if (LHS.isInvalid())
10284     return ExprError();
10285 
10286   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10287   if (RHS.isInvalid())
10288     return ExprError();
10289 
10290 
10291   if (!getDerived().AlwaysRebuild() &&
10292       LHS.get() == E->getLHS() &&
10293       RHS.get() == E->getRHS())
10294     return E;
10295 
10296   return getDerived().RebuildArraySubscriptExpr(
10297       LHS.get(),
10298       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
10299 }
10300 
10301 template <typename Derived>
10302 ExprResult
10303 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
10304   ExprResult Base = getDerived().TransformExpr(E->getBase());
10305   if (Base.isInvalid())
10306     return ExprError();
10307 
10308   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
10309   if (RowIdx.isInvalid())
10310     return ExprError();
10311 
10312   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
10313   if (ColumnIdx.isInvalid())
10314     return ExprError();
10315 
10316   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10317       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
10318     return E;
10319 
10320   return getDerived().RebuildMatrixSubscriptExpr(
10321       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
10322 }
10323 
10324 template <typename Derived>
10325 ExprResult
10326 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
10327   ExprResult Base = getDerived().TransformExpr(E->getBase());
10328   if (Base.isInvalid())
10329     return ExprError();
10330 
10331   ExprResult LowerBound;
10332   if (E->getLowerBound()) {
10333     LowerBound = getDerived().TransformExpr(E->getLowerBound());
10334     if (LowerBound.isInvalid())
10335       return ExprError();
10336   }
10337 
10338   ExprResult Length;
10339   if (E->getLength()) {
10340     Length = getDerived().TransformExpr(E->getLength());
10341     if (Length.isInvalid())
10342       return ExprError();
10343   }
10344 
10345   ExprResult Stride;
10346   if (Expr *Str = E->getStride()) {
10347     Stride = getDerived().TransformExpr(Str);
10348     if (Stride.isInvalid())
10349       return ExprError();
10350   }
10351 
10352   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10353       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
10354     return E;
10355 
10356   return getDerived().RebuildOMPArraySectionExpr(
10357       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
10358       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
10359       E->getRBracketLoc());
10360 }
10361 
10362 template <typename Derived>
10363 ExprResult
10364 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
10365   ExprResult Base = getDerived().TransformExpr(E->getBase());
10366   if (Base.isInvalid())
10367     return ExprError();
10368 
10369   SmallVector<Expr *, 4> Dims;
10370   bool ErrorFound = false;
10371   for (Expr *Dim : E->getDimensions()) {
10372     ExprResult DimRes = getDerived().TransformExpr(Dim);
10373     if (DimRes.isInvalid()) {
10374       ErrorFound = true;
10375       continue;
10376     }
10377     Dims.push_back(DimRes.get());
10378   }
10379 
10380   if (ErrorFound)
10381     return ExprError();
10382   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
10383                                                  E->getRParenLoc(), Dims,
10384                                                  E->getBracketsRanges());
10385 }
10386 
10387 template <typename Derived>
10388 ExprResult
10389 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
10390   unsigned NumIterators = E->numOfIterators();
10391   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
10392 
10393   bool ErrorFound = false;
10394   bool NeedToRebuild = getDerived().AlwaysRebuild();
10395   for (unsigned I = 0; I < NumIterators; ++I) {
10396     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
10397     Data[I].DeclIdent = D->getIdentifier();
10398     Data[I].DeclIdentLoc = D->getLocation();
10399     if (D->getLocation() == D->getBeginLoc()) {
10400       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
10401              "Implicit type must be int.");
10402     } else {
10403       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
10404       QualType DeclTy = getDerived().TransformType(D->getType());
10405       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
10406     }
10407     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
10408     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
10409     ExprResult End = getDerived().TransformExpr(Range.End);
10410     ExprResult Step = getDerived().TransformExpr(Range.Step);
10411     ErrorFound = ErrorFound ||
10412                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
10413                                                !Data[I].Type.get().isNull())) ||
10414                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
10415     if (ErrorFound)
10416       continue;
10417     Data[I].Range.Begin = Begin.get();
10418     Data[I].Range.End = End.get();
10419     Data[I].Range.Step = Step.get();
10420     Data[I].AssignLoc = E->getAssignLoc(I);
10421     Data[I].ColonLoc = E->getColonLoc(I);
10422     Data[I].SecColonLoc = E->getSecondColonLoc(I);
10423     NeedToRebuild =
10424         NeedToRebuild ||
10425         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
10426                                        D->getType().getTypePtrOrNull()) ||
10427         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
10428         Range.Step != Data[I].Range.Step;
10429   }
10430   if (ErrorFound)
10431     return ExprError();
10432   if (!NeedToRebuild)
10433     return E;
10434 
10435   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
10436       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
10437   if (!Res.isUsable())
10438     return Res;
10439   auto *IE = cast<OMPIteratorExpr>(Res.get());
10440   for (unsigned I = 0; I < NumIterators; ++I)
10441     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
10442                                       IE->getIteratorDecl(I));
10443   return Res;
10444 }
10445 
10446 template<typename Derived>
10447 ExprResult
10448 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
10449   // Transform the callee.
10450   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10451   if (Callee.isInvalid())
10452     return ExprError();
10453 
10454   // Transform arguments.
10455   bool ArgChanged = false;
10456   SmallVector<Expr*, 8> Args;
10457   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10458                                   &ArgChanged))
10459     return ExprError();
10460 
10461   if (!getDerived().AlwaysRebuild() &&
10462       Callee.get() == E->getCallee() &&
10463       !ArgChanged)
10464     return SemaRef.MaybeBindToTemporary(E);
10465 
10466   // FIXME: Wrong source location information for the '('.
10467   SourceLocation FakeLParenLoc
10468     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10469   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10470                                       Args,
10471                                       E->getRParenLoc());
10472 }
10473 
10474 template<typename Derived>
10475 ExprResult
10476 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
10477   ExprResult Base = getDerived().TransformExpr(E->getBase());
10478   if (Base.isInvalid())
10479     return ExprError();
10480 
10481   NestedNameSpecifierLoc QualifierLoc;
10482   if (E->hasQualifier()) {
10483     QualifierLoc
10484       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10485 
10486     if (!QualifierLoc)
10487       return ExprError();
10488   }
10489   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10490 
10491   ValueDecl *Member
10492     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
10493                                                          E->getMemberDecl()));
10494   if (!Member)
10495     return ExprError();
10496 
10497   NamedDecl *FoundDecl = E->getFoundDecl();
10498   if (FoundDecl == E->getMemberDecl()) {
10499     FoundDecl = Member;
10500   } else {
10501     FoundDecl = cast_or_null<NamedDecl>(
10502                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
10503     if (!FoundDecl)
10504       return ExprError();
10505   }
10506 
10507   if (!getDerived().AlwaysRebuild() &&
10508       Base.get() == E->getBase() &&
10509       QualifierLoc == E->getQualifierLoc() &&
10510       Member == E->getMemberDecl() &&
10511       FoundDecl == E->getFoundDecl() &&
10512       !E->hasExplicitTemplateArgs()) {
10513 
10514     // Mark it referenced in the new context regardless.
10515     // FIXME: this is a bit instantiation-specific.
10516     SemaRef.MarkMemberReferenced(E);
10517 
10518     return E;
10519   }
10520 
10521   TemplateArgumentListInfo TransArgs;
10522   if (E->hasExplicitTemplateArgs()) {
10523     TransArgs.setLAngleLoc(E->getLAngleLoc());
10524     TransArgs.setRAngleLoc(E->getRAngleLoc());
10525     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10526                                                 E->getNumTemplateArgs(),
10527                                                 TransArgs))
10528       return ExprError();
10529   }
10530 
10531   // FIXME: Bogus source location for the operator
10532   SourceLocation FakeOperatorLoc =
10533       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
10534 
10535   // FIXME: to do this check properly, we will need to preserve the
10536   // first-qualifier-in-scope here, just in case we had a dependent
10537   // base (and therefore couldn't do the check) and a
10538   // nested-name-qualifier (and therefore could do the lookup).
10539   NamedDecl *FirstQualifierInScope = nullptr;
10540   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
10541   if (MemberNameInfo.getName()) {
10542     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
10543     if (!MemberNameInfo.getName())
10544       return ExprError();
10545   }
10546 
10547   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
10548                                         E->isArrow(),
10549                                         QualifierLoc,
10550                                         TemplateKWLoc,
10551                                         MemberNameInfo,
10552                                         Member,
10553                                         FoundDecl,
10554                                         (E->hasExplicitTemplateArgs()
10555                                            ? &TransArgs : nullptr),
10556                                         FirstQualifierInScope);
10557 }
10558 
10559 template<typename Derived>
10560 ExprResult
10561 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
10562   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10563   if (LHS.isInvalid())
10564     return ExprError();
10565 
10566   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10567   if (RHS.isInvalid())
10568     return ExprError();
10569 
10570   if (!getDerived().AlwaysRebuild() &&
10571       LHS.get() == E->getLHS() &&
10572       RHS.get() == E->getRHS())
10573     return E;
10574 
10575   if (E->isCompoundAssignmentOp())
10576     // FPFeatures has already been established from trailing storage
10577     return getDerived().RebuildBinaryOperator(
10578         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
10579   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10580   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
10581   getSema().CurFPFeatures =
10582       NewOverrides.applyOverrides(getSema().getLangOpts());
10583   getSema().FpPragmaStack.CurrentValue = NewOverrides.getAsOpaqueInt();
10584   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
10585                                             LHS.get(), RHS.get());
10586 }
10587 
10588 template <typename Derived>
10589 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
10590     CXXRewrittenBinaryOperator *E) {
10591   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
10592 
10593   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
10594   if (LHS.isInvalid())
10595     return ExprError();
10596 
10597   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
10598   if (RHS.isInvalid())
10599     return ExprError();
10600 
10601   if (!getDerived().AlwaysRebuild() &&
10602       LHS.get() == Decomp.LHS &&
10603       RHS.get() == Decomp.RHS)
10604     return E;
10605 
10606   // Extract the already-resolved callee declarations so that we can restrict
10607   // ourselves to using them as the unqualified lookup results when rebuilding.
10608   UnresolvedSet<2> UnqualLookups;
10609   Expr *PossibleBinOps[] = {E->getSemanticForm(),
10610                             const_cast<Expr *>(Decomp.InnerBinOp)};
10611   for (Expr *PossibleBinOp : PossibleBinOps) {
10612     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
10613     if (!Op)
10614       continue;
10615     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
10616     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
10617       continue;
10618 
10619     // Transform the callee in case we built a call to a local extern
10620     // declaration.
10621     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
10622         E->getOperatorLoc(), Callee->getFoundDecl()));
10623     if (!Found)
10624       return ExprError();
10625     UnqualLookups.addDecl(Found);
10626   }
10627 
10628   return getDerived().RebuildCXXRewrittenBinaryOperator(
10629       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
10630 }
10631 
10632 template<typename Derived>
10633 ExprResult
10634 TreeTransform<Derived>::TransformCompoundAssignOperator(
10635                                                       CompoundAssignOperator *E) {
10636   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10637   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
10638   getSema().CurFPFeatures =
10639       NewOverrides.applyOverrides(getSema().getLangOpts());
10640   getSema().FpPragmaStack.CurrentValue = NewOverrides.getAsOpaqueInt();
10641   return getDerived().TransformBinaryOperator(E);
10642 }
10643 
10644 template<typename Derived>
10645 ExprResult TreeTransform<Derived>::
10646 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
10647   // Just rebuild the common and RHS expressions and see whether we
10648   // get any changes.
10649 
10650   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
10651   if (commonExpr.isInvalid())
10652     return ExprError();
10653 
10654   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
10655   if (rhs.isInvalid())
10656     return ExprError();
10657 
10658   if (!getDerived().AlwaysRebuild() &&
10659       commonExpr.get() == e->getCommon() &&
10660       rhs.get() == e->getFalseExpr())
10661     return e;
10662 
10663   return getDerived().RebuildConditionalOperator(commonExpr.get(),
10664                                                  e->getQuestionLoc(),
10665                                                  nullptr,
10666                                                  e->getColonLoc(),
10667                                                  rhs.get());
10668 }
10669 
10670 template<typename Derived>
10671 ExprResult
10672 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
10673   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10674   if (Cond.isInvalid())
10675     return ExprError();
10676 
10677   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10678   if (LHS.isInvalid())
10679     return ExprError();
10680 
10681   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10682   if (RHS.isInvalid())
10683     return ExprError();
10684 
10685   if (!getDerived().AlwaysRebuild() &&
10686       Cond.get() == E->getCond() &&
10687       LHS.get() == E->getLHS() &&
10688       RHS.get() == E->getRHS())
10689     return E;
10690 
10691   return getDerived().RebuildConditionalOperator(Cond.get(),
10692                                                  E->getQuestionLoc(),
10693                                                  LHS.get(),
10694                                                  E->getColonLoc(),
10695                                                  RHS.get());
10696 }
10697 
10698 template<typename Derived>
10699 ExprResult
10700 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
10701   // Implicit casts are eliminated during transformation, since they
10702   // will be recomputed by semantic analysis after transformation.
10703   return getDerived().TransformExpr(E->getSubExprAsWritten());
10704 }
10705 
10706 template<typename Derived>
10707 ExprResult
10708 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
10709   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10710   if (!Type)
10711     return ExprError();
10712 
10713   ExprResult SubExpr
10714     = getDerived().TransformExpr(E->getSubExprAsWritten());
10715   if (SubExpr.isInvalid())
10716     return ExprError();
10717 
10718   if (!getDerived().AlwaysRebuild() &&
10719       Type == E->getTypeInfoAsWritten() &&
10720       SubExpr.get() == E->getSubExpr())
10721     return E;
10722 
10723   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
10724                                             Type,
10725                                             E->getRParenLoc(),
10726                                             SubExpr.get());
10727 }
10728 
10729 template<typename Derived>
10730 ExprResult
10731 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
10732   TypeSourceInfo *OldT = E->getTypeSourceInfo();
10733   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10734   if (!NewT)
10735     return ExprError();
10736 
10737   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
10738   if (Init.isInvalid())
10739     return ExprError();
10740 
10741   if (!getDerived().AlwaysRebuild() &&
10742       OldT == NewT &&
10743       Init.get() == E->getInitializer())
10744     return SemaRef.MaybeBindToTemporary(E);
10745 
10746   // Note: the expression type doesn't necessarily match the
10747   // type-as-written, but that's okay, because it should always be
10748   // derivable from the initializer.
10749 
10750   return getDerived().RebuildCompoundLiteralExpr(
10751       E->getLParenLoc(), NewT,
10752       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
10753 }
10754 
10755 template<typename Derived>
10756 ExprResult
10757 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
10758   ExprResult Base = getDerived().TransformExpr(E->getBase());
10759   if (Base.isInvalid())
10760     return ExprError();
10761 
10762   if (!getDerived().AlwaysRebuild() &&
10763       Base.get() == E->getBase())
10764     return E;
10765 
10766   // FIXME: Bad source location
10767   SourceLocation FakeOperatorLoc =
10768       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
10769   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
10770                                                   E->getAccessorLoc(),
10771                                                   E->getAccessor());
10772 }
10773 
10774 template<typename Derived>
10775 ExprResult
10776 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
10777   if (InitListExpr *Syntactic = E->getSyntacticForm())
10778     E = Syntactic;
10779 
10780   bool InitChanged = false;
10781 
10782   EnterExpressionEvaluationContext Context(
10783       getSema(), EnterExpressionEvaluationContext::InitList);
10784 
10785   SmallVector<Expr*, 4> Inits;
10786   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
10787                                   Inits, &InitChanged))
10788     return ExprError();
10789 
10790   if (!getDerived().AlwaysRebuild() && !InitChanged) {
10791     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
10792     // in some cases. We can't reuse it in general, because the syntactic and
10793     // semantic forms are linked, and we can't know that semantic form will
10794     // match even if the syntactic form does.
10795   }
10796 
10797   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
10798                                       E->getRBraceLoc());
10799 }
10800 
10801 template<typename Derived>
10802 ExprResult
10803 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
10804   Designation Desig;
10805 
10806   // transform the initializer value
10807   ExprResult Init = getDerived().TransformExpr(E->getInit());
10808   if (Init.isInvalid())
10809     return ExprError();
10810 
10811   // transform the designators.
10812   SmallVector<Expr*, 4> ArrayExprs;
10813   bool ExprChanged = false;
10814   for (const DesignatedInitExpr::Designator &D : E->designators()) {
10815     if (D.isFieldDesignator()) {
10816       Desig.AddDesignator(Designator::getField(D.getFieldName(),
10817                                                D.getDotLoc(),
10818                                                D.getFieldLoc()));
10819       if (D.getField()) {
10820         FieldDecl *Field = cast_or_null<FieldDecl>(
10821             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
10822         if (Field != D.getField())
10823           // Rebuild the expression when the transformed FieldDecl is
10824           // different to the already assigned FieldDecl.
10825           ExprChanged = true;
10826       } else {
10827         // Ensure that the designator expression is rebuilt when there isn't
10828         // a resolved FieldDecl in the designator as we don't want to assign
10829         // a FieldDecl to a pattern designator that will be instantiated again.
10830         ExprChanged = true;
10831       }
10832       continue;
10833     }
10834 
10835     if (D.isArrayDesignator()) {
10836       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
10837       if (Index.isInvalid())
10838         return ExprError();
10839 
10840       Desig.AddDesignator(
10841           Designator::getArray(Index.get(), D.getLBracketLoc()));
10842 
10843       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
10844       ArrayExprs.push_back(Index.get());
10845       continue;
10846     }
10847 
10848     assert(D.isArrayRangeDesignator() && "New kind of designator?");
10849     ExprResult Start
10850       = getDerived().TransformExpr(E->getArrayRangeStart(D));
10851     if (Start.isInvalid())
10852       return ExprError();
10853 
10854     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
10855     if (End.isInvalid())
10856       return ExprError();
10857 
10858     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
10859                                                   End.get(),
10860                                                   D.getLBracketLoc(),
10861                                                   D.getEllipsisLoc()));
10862 
10863     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
10864                   End.get() != E->getArrayRangeEnd(D);
10865 
10866     ArrayExprs.push_back(Start.get());
10867     ArrayExprs.push_back(End.get());
10868   }
10869 
10870   if (!getDerived().AlwaysRebuild() &&
10871       Init.get() == E->getInit() &&
10872       !ExprChanged)
10873     return E;
10874 
10875   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
10876                                                 E->getEqualOrColonLoc(),
10877                                                 E->usesGNUSyntax(), Init.get());
10878 }
10879 
10880 // Seems that if TransformInitListExpr() only works on the syntactic form of an
10881 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
10882 template<typename Derived>
10883 ExprResult
10884 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
10885     DesignatedInitUpdateExpr *E) {
10886   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
10887                    "initializer");
10888   return ExprError();
10889 }
10890 
10891 template<typename Derived>
10892 ExprResult
10893 TreeTransform<Derived>::TransformNoInitExpr(
10894     NoInitExpr *E) {
10895   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
10896   return ExprError();
10897 }
10898 
10899 template<typename Derived>
10900 ExprResult
10901 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
10902   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
10903   return ExprError();
10904 }
10905 
10906 template<typename Derived>
10907 ExprResult
10908 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
10909   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
10910   return ExprError();
10911 }
10912 
10913 template<typename Derived>
10914 ExprResult
10915 TreeTransform<Derived>::TransformImplicitValueInitExpr(
10916                                                      ImplicitValueInitExpr *E) {
10917   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
10918 
10919   // FIXME: Will we ever have proper type location here? Will we actually
10920   // need to transform the type?
10921   QualType T = getDerived().TransformType(E->getType());
10922   if (T.isNull())
10923     return ExprError();
10924 
10925   if (!getDerived().AlwaysRebuild() &&
10926       T == E->getType())
10927     return E;
10928 
10929   return getDerived().RebuildImplicitValueInitExpr(T);
10930 }
10931 
10932 template<typename Derived>
10933 ExprResult
10934 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10935   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10936   if (!TInfo)
10937     return ExprError();
10938 
10939   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10940   if (SubExpr.isInvalid())
10941     return ExprError();
10942 
10943   if (!getDerived().AlwaysRebuild() &&
10944       TInfo == E->getWrittenTypeInfo() &&
10945       SubExpr.get() == E->getSubExpr())
10946     return E;
10947 
10948   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10949                                        TInfo, E->getRParenLoc());
10950 }
10951 
10952 template<typename Derived>
10953 ExprResult
10954 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10955   bool ArgumentChanged = false;
10956   SmallVector<Expr*, 4> Inits;
10957   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10958                      &ArgumentChanged))
10959     return ExprError();
10960 
10961   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10962                                            Inits,
10963                                            E->getRParenLoc());
10964 }
10965 
10966 /// Transform an address-of-label expression.
10967 ///
10968 /// By default, the transformation of an address-of-label expression always
10969 /// rebuilds the expression, so that the label identifier can be resolved to
10970 /// the corresponding label statement by semantic analysis.
10971 template<typename Derived>
10972 ExprResult
10973 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10974   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10975                                         E->getLabel());
10976   if (!LD)
10977     return ExprError();
10978 
10979   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10980                                            cast<LabelDecl>(LD));
10981 }
10982 
10983 template<typename Derived>
10984 ExprResult
10985 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10986   SemaRef.ActOnStartStmtExpr();
10987   StmtResult SubStmt
10988     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10989   if (SubStmt.isInvalid()) {
10990     SemaRef.ActOnStmtExprError();
10991     return ExprError();
10992   }
10993 
10994   unsigned OldDepth = E->getTemplateDepth();
10995   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
10996 
10997   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
10998       SubStmt.get() == E->getSubStmt()) {
10999     // Calling this an 'error' is unintuitive, but it does the right thing.
11000     SemaRef.ActOnStmtExprError();
11001     return SemaRef.MaybeBindToTemporary(E);
11002   }
11003 
11004   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11005                                       E->getRParenLoc(), NewDepth);
11006 }
11007 
11008 template<typename Derived>
11009 ExprResult
11010 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11011   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11012   if (Cond.isInvalid())
11013     return ExprError();
11014 
11015   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11016   if (LHS.isInvalid())
11017     return ExprError();
11018 
11019   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11020   if (RHS.isInvalid())
11021     return ExprError();
11022 
11023   if (!getDerived().AlwaysRebuild() &&
11024       Cond.get() == E->getCond() &&
11025       LHS.get() == E->getLHS() &&
11026       RHS.get() == E->getRHS())
11027     return E;
11028 
11029   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11030                                         Cond.get(), LHS.get(), RHS.get(),
11031                                         E->getRParenLoc());
11032 }
11033 
11034 template<typename Derived>
11035 ExprResult
11036 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11037   return E;
11038 }
11039 
11040 template<typename Derived>
11041 ExprResult
11042 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11043   switch (E->getOperator()) {
11044   case OO_New:
11045   case OO_Delete:
11046   case OO_Array_New:
11047   case OO_Array_Delete:
11048     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
11049 
11050   case OO_Call: {
11051     // This is a call to an object's operator().
11052     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
11053 
11054     // Transform the object itself.
11055     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11056     if (Object.isInvalid())
11057       return ExprError();
11058 
11059     // FIXME: Poor location information
11060     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11061         static_cast<Expr *>(Object.get())->getEndLoc());
11062 
11063     // Transform the call arguments.
11064     SmallVector<Expr*, 8> Args;
11065     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11066                                     Args))
11067       return ExprError();
11068 
11069     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11070                                         E->getEndLoc());
11071   }
11072 
11073 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11074   case OO_##Name:
11075 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11076 #include "clang/Basic/OperatorKinds.def"
11077   case OO_Subscript:
11078     // Handled below.
11079     break;
11080 
11081   case OO_Conditional:
11082     llvm_unreachable("conditional operator is not actually overloadable");
11083 
11084   case OO_None:
11085   case NUM_OVERLOADED_OPERATORS:
11086     llvm_unreachable("not an overloaded operator?");
11087   }
11088 
11089   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11090   if (Callee.isInvalid())
11091     return ExprError();
11092 
11093   ExprResult First;
11094   if (E->getOperator() == OO_Amp)
11095     First = getDerived().TransformAddressOfOperand(E->getArg(0));
11096   else
11097     First = getDerived().TransformExpr(E->getArg(0));
11098   if (First.isInvalid())
11099     return ExprError();
11100 
11101   ExprResult Second;
11102   if (E->getNumArgs() == 2) {
11103     Second = getDerived().TransformExpr(E->getArg(1));
11104     if (Second.isInvalid())
11105       return ExprError();
11106   }
11107 
11108   if (!getDerived().AlwaysRebuild() &&
11109       Callee.get() == E->getCallee() &&
11110       First.get() == E->getArg(0) &&
11111       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11112     return SemaRef.MaybeBindToTemporary(E);
11113 
11114   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11115   FPOptionsOverride NewOverrides(E->getFPFeatures());
11116   getSema().CurFPFeatures =
11117       NewOverrides.applyOverrides(getSema().getLangOpts());
11118   getSema().FpPragmaStack.CurrentValue = NewOverrides.getAsOpaqueInt();
11119 
11120   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11121                                                  E->getOperatorLoc(),
11122                                                  Callee.get(),
11123                                                  First.get(),
11124                                                  Second.get());
11125 }
11126 
11127 template<typename Derived>
11128 ExprResult
11129 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11130   return getDerived().TransformCallExpr(E);
11131 }
11132 
11133 template <typename Derived>
11134 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11135   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11136                          getSema().CurContext != E->getParentContext();
11137 
11138   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11139     return E;
11140 
11141   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
11142                                            E->getEndLoc(),
11143                                            getSema().CurContext);
11144 }
11145 
11146 template<typename Derived>
11147 ExprResult
11148 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11149   // Transform the callee.
11150   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11151   if (Callee.isInvalid())
11152     return ExprError();
11153 
11154   // Transform exec config.
11155   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
11156   if (EC.isInvalid())
11157     return ExprError();
11158 
11159   // Transform arguments.
11160   bool ArgChanged = false;
11161   SmallVector<Expr*, 8> Args;
11162   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11163                                   &ArgChanged))
11164     return ExprError();
11165 
11166   if (!getDerived().AlwaysRebuild() &&
11167       Callee.get() == E->getCallee() &&
11168       !ArgChanged)
11169     return SemaRef.MaybeBindToTemporary(E);
11170 
11171   // FIXME: Wrong source location information for the '('.
11172   SourceLocation FakeLParenLoc
11173     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11174   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11175                                       Args,
11176                                       E->getRParenLoc(), EC.get());
11177 }
11178 
11179 template<typename Derived>
11180 ExprResult
11181 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
11182   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11183   if (!Type)
11184     return ExprError();
11185 
11186   ExprResult SubExpr
11187     = getDerived().TransformExpr(E->getSubExprAsWritten());
11188   if (SubExpr.isInvalid())
11189     return ExprError();
11190 
11191   if (!getDerived().AlwaysRebuild() &&
11192       Type == E->getTypeInfoAsWritten() &&
11193       SubExpr.get() == E->getSubExpr())
11194     return E;
11195   return getDerived().RebuildCXXNamedCastExpr(
11196       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
11197       Type, E->getAngleBrackets().getEnd(),
11198       // FIXME. this should be '(' location
11199       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
11200 }
11201 
11202 template<typename Derived>
11203 ExprResult
11204 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
11205   TypeSourceInfo *TSI =
11206       getDerived().TransformType(BCE->getTypeInfoAsWritten());
11207   if (!TSI)
11208     return ExprError();
11209 
11210   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
11211   if (Sub.isInvalid())
11212     return ExprError();
11213 
11214   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
11215                                                 Sub.get(), BCE->getEndLoc());
11216 }
11217 
11218 template<typename Derived>
11219 ExprResult
11220 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
11221   return getDerived().TransformCXXNamedCastExpr(E);
11222 }
11223 
11224 template<typename Derived>
11225 ExprResult
11226 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
11227   return getDerived().TransformCXXNamedCastExpr(E);
11228 }
11229 
11230 template<typename Derived>
11231 ExprResult
11232 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
11233                                                       CXXReinterpretCastExpr *E) {
11234   return getDerived().TransformCXXNamedCastExpr(E);
11235 }
11236 
11237 template<typename Derived>
11238 ExprResult
11239 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
11240   return getDerived().TransformCXXNamedCastExpr(E);
11241 }
11242 
11243 template<typename Derived>
11244 ExprResult
11245 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
11246   return getDerived().TransformCXXNamedCastExpr(E);
11247 }
11248 
11249 template<typename Derived>
11250 ExprResult
11251 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
11252                                                      CXXFunctionalCastExpr *E) {
11253   TypeSourceInfo *Type =
11254       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
11255   if (!Type)
11256     return ExprError();
11257 
11258   ExprResult SubExpr
11259     = getDerived().TransformExpr(E->getSubExprAsWritten());
11260   if (SubExpr.isInvalid())
11261     return ExprError();
11262 
11263   if (!getDerived().AlwaysRebuild() &&
11264       Type == E->getTypeInfoAsWritten() &&
11265       SubExpr.get() == E->getSubExpr())
11266     return E;
11267 
11268   return getDerived().RebuildCXXFunctionalCastExpr(Type,
11269                                                    E->getLParenLoc(),
11270                                                    SubExpr.get(),
11271                                                    E->getRParenLoc(),
11272                                                    E->isListInitialization());
11273 }
11274 
11275 template<typename Derived>
11276 ExprResult
11277 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
11278   if (E->isTypeOperand()) {
11279     TypeSourceInfo *TInfo
11280       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11281     if (!TInfo)
11282       return ExprError();
11283 
11284     if (!getDerived().AlwaysRebuild() &&
11285         TInfo == E->getTypeOperandSourceInfo())
11286       return E;
11287 
11288     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11289                                              TInfo, E->getEndLoc());
11290   }
11291 
11292   // We don't know whether the subexpression is potentially evaluated until
11293   // after we perform semantic analysis.  We speculatively assume it is
11294   // unevaluated; it will get fixed later if the subexpression is in fact
11295   // potentially evaluated.
11296   EnterExpressionEvaluationContext Unevaluated(
11297       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11298       Sema::ReuseLambdaContextDecl);
11299 
11300   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11301   if (SubExpr.isInvalid())
11302     return ExprError();
11303 
11304   if (!getDerived().AlwaysRebuild() &&
11305       SubExpr.get() == E->getExprOperand())
11306     return E;
11307 
11308   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11309                                            SubExpr.get(), E->getEndLoc());
11310 }
11311 
11312 template<typename Derived>
11313 ExprResult
11314 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
11315   if (E->isTypeOperand()) {
11316     TypeSourceInfo *TInfo
11317       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11318     if (!TInfo)
11319       return ExprError();
11320 
11321     if (!getDerived().AlwaysRebuild() &&
11322         TInfo == E->getTypeOperandSourceInfo())
11323       return E;
11324 
11325     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11326                                              TInfo, E->getEndLoc());
11327   }
11328 
11329   EnterExpressionEvaluationContext Unevaluated(
11330       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11331 
11332   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11333   if (SubExpr.isInvalid())
11334     return ExprError();
11335 
11336   if (!getDerived().AlwaysRebuild() &&
11337       SubExpr.get() == E->getExprOperand())
11338     return E;
11339 
11340   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11341                                            SubExpr.get(), E->getEndLoc());
11342 }
11343 
11344 template<typename Derived>
11345 ExprResult
11346 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
11347   return E;
11348 }
11349 
11350 template<typename Derived>
11351 ExprResult
11352 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
11353                                                      CXXNullPtrLiteralExpr *E) {
11354   return E;
11355 }
11356 
11357 template<typename Derived>
11358 ExprResult
11359 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
11360   QualType T = getSema().getCurrentThisType();
11361 
11362   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
11363     // Mark it referenced in the new context regardless.
11364     // FIXME: this is a bit instantiation-specific.
11365     getSema().MarkThisReferenced(E);
11366     return E;
11367   }
11368 
11369   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
11370 }
11371 
11372 template<typename Derived>
11373 ExprResult
11374 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
11375   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11376   if (SubExpr.isInvalid())
11377     return ExprError();
11378 
11379   if (!getDerived().AlwaysRebuild() &&
11380       SubExpr.get() == E->getSubExpr())
11381     return E;
11382 
11383   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
11384                                           E->isThrownVariableInScope());
11385 }
11386 
11387 template<typename Derived>
11388 ExprResult
11389 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11390   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
11391       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
11392   if (!Param)
11393     return ExprError();
11394 
11395   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
11396       E->getUsedContext() == SemaRef.CurContext)
11397     return E;
11398 
11399   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
11400 }
11401 
11402 template<typename Derived>
11403 ExprResult
11404 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
11405   FieldDecl *Field = cast_or_null<FieldDecl>(
11406       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
11407   if (!Field)
11408     return ExprError();
11409 
11410   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
11411       E->getUsedContext() == SemaRef.CurContext)
11412     return E;
11413 
11414   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
11415 }
11416 
11417 template<typename Derived>
11418 ExprResult
11419 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
11420                                                     CXXScalarValueInitExpr *E) {
11421   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
11422   if (!T)
11423     return ExprError();
11424 
11425   if (!getDerived().AlwaysRebuild() &&
11426       T == E->getTypeSourceInfo())
11427     return E;
11428 
11429   return getDerived().RebuildCXXScalarValueInitExpr(T,
11430                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
11431                                                     E->getRParenLoc());
11432 }
11433 
11434 template<typename Derived>
11435 ExprResult
11436 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
11437   // Transform the type that we're allocating
11438   TypeSourceInfo *AllocTypeInfo =
11439       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
11440   if (!AllocTypeInfo)
11441     return ExprError();
11442 
11443   // Transform the size of the array we're allocating (if any).
11444   Optional<Expr *> ArraySize;
11445   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
11446     ExprResult NewArraySize;
11447     if (*OldArraySize) {
11448       NewArraySize = getDerived().TransformExpr(*OldArraySize);
11449       if (NewArraySize.isInvalid())
11450         return ExprError();
11451     }
11452     ArraySize = NewArraySize.get();
11453   }
11454 
11455   // Transform the placement arguments (if any).
11456   bool ArgumentChanged = false;
11457   SmallVector<Expr*, 8> PlacementArgs;
11458   if (getDerived().TransformExprs(E->getPlacementArgs(),
11459                                   E->getNumPlacementArgs(), true,
11460                                   PlacementArgs, &ArgumentChanged))
11461     return ExprError();
11462 
11463   // Transform the initializer (if any).
11464   Expr *OldInit = E->getInitializer();
11465   ExprResult NewInit;
11466   if (OldInit)
11467     NewInit = getDerived().TransformInitializer(OldInit, true);
11468   if (NewInit.isInvalid())
11469     return ExprError();
11470 
11471   // Transform new operator and delete operator.
11472   FunctionDecl *OperatorNew = nullptr;
11473   if (E->getOperatorNew()) {
11474     OperatorNew = cast_or_null<FunctionDecl>(
11475         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
11476     if (!OperatorNew)
11477       return ExprError();
11478   }
11479 
11480   FunctionDecl *OperatorDelete = nullptr;
11481   if (E->getOperatorDelete()) {
11482     OperatorDelete = cast_or_null<FunctionDecl>(
11483         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
11484     if (!OperatorDelete)
11485       return ExprError();
11486   }
11487 
11488   if (!getDerived().AlwaysRebuild() &&
11489       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
11490       ArraySize == E->getArraySize() &&
11491       NewInit.get() == OldInit &&
11492       OperatorNew == E->getOperatorNew() &&
11493       OperatorDelete == E->getOperatorDelete() &&
11494       !ArgumentChanged) {
11495     // Mark any declarations we need as referenced.
11496     // FIXME: instantiation-specific.
11497     if (OperatorNew)
11498       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
11499     if (OperatorDelete)
11500       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
11501 
11502     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
11503       QualType ElementType
11504         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
11505       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
11506         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
11507         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
11508           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
11509         }
11510       }
11511     }
11512 
11513     return E;
11514   }
11515 
11516   QualType AllocType = AllocTypeInfo->getType();
11517   if (!ArraySize) {
11518     // If no array size was specified, but the new expression was
11519     // instantiated with an array type (e.g., "new T" where T is
11520     // instantiated with "int[4]"), extract the outer bound from the
11521     // array type as our array size. We do this with constant and
11522     // dependently-sized array types.
11523     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
11524     if (!ArrayT) {
11525       // Do nothing
11526     } else if (const ConstantArrayType *ConsArrayT
11527                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
11528       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
11529                                          SemaRef.Context.getSizeType(),
11530                                          /*FIXME:*/ E->getBeginLoc());
11531       AllocType = ConsArrayT->getElementType();
11532     } else if (const DependentSizedArrayType *DepArrayT
11533                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
11534       if (DepArrayT->getSizeExpr()) {
11535         ArraySize = DepArrayT->getSizeExpr();
11536         AllocType = DepArrayT->getElementType();
11537       }
11538     }
11539   }
11540 
11541   return getDerived().RebuildCXXNewExpr(
11542       E->getBeginLoc(), E->isGlobalNew(),
11543       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
11544       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
11545       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
11546 }
11547 
11548 template<typename Derived>
11549 ExprResult
11550 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
11551   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
11552   if (Operand.isInvalid())
11553     return ExprError();
11554 
11555   // Transform the delete operator, if known.
11556   FunctionDecl *OperatorDelete = nullptr;
11557   if (E->getOperatorDelete()) {
11558     OperatorDelete = cast_or_null<FunctionDecl>(
11559         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
11560     if (!OperatorDelete)
11561       return ExprError();
11562   }
11563 
11564   if (!getDerived().AlwaysRebuild() &&
11565       Operand.get() == E->getArgument() &&
11566       OperatorDelete == E->getOperatorDelete()) {
11567     // Mark any declarations we need as referenced.
11568     // FIXME: instantiation-specific.
11569     if (OperatorDelete)
11570       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
11571 
11572     if (!E->getArgument()->isTypeDependent()) {
11573       QualType Destroyed = SemaRef.Context.getBaseElementType(
11574                                                          E->getDestroyedType());
11575       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11576         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11577         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
11578                                        SemaRef.LookupDestructor(Record));
11579       }
11580     }
11581 
11582     return E;
11583   }
11584 
11585   return getDerived().RebuildCXXDeleteExpr(
11586       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
11587 }
11588 
11589 template<typename Derived>
11590 ExprResult
11591 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
11592                                                      CXXPseudoDestructorExpr *E) {
11593   ExprResult Base = getDerived().TransformExpr(E->getBase());
11594   if (Base.isInvalid())
11595     return ExprError();
11596 
11597   ParsedType ObjectTypePtr;
11598   bool MayBePseudoDestructor = false;
11599   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11600                                               E->getOperatorLoc(),
11601                                         E->isArrow()? tok::arrow : tok::period,
11602                                               ObjectTypePtr,
11603                                               MayBePseudoDestructor);
11604   if (Base.isInvalid())
11605     return ExprError();
11606 
11607   QualType ObjectType = ObjectTypePtr.get();
11608   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
11609   if (QualifierLoc) {
11610     QualifierLoc
11611       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
11612     if (!QualifierLoc)
11613       return ExprError();
11614   }
11615   CXXScopeSpec SS;
11616   SS.Adopt(QualifierLoc);
11617 
11618   PseudoDestructorTypeStorage Destroyed;
11619   if (E->getDestroyedTypeInfo()) {
11620     TypeSourceInfo *DestroyedTypeInfo
11621       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
11622                                                 ObjectType, nullptr, SS);
11623     if (!DestroyedTypeInfo)
11624       return ExprError();
11625     Destroyed = DestroyedTypeInfo;
11626   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
11627     // We aren't likely to be able to resolve the identifier down to a type
11628     // now anyway, so just retain the identifier.
11629     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
11630                                             E->getDestroyedTypeLoc());
11631   } else {
11632     // Look for a destructor known with the given name.
11633     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
11634                                               *E->getDestroyedTypeIdentifier(),
11635                                                 E->getDestroyedTypeLoc(),
11636                                                 /*Scope=*/nullptr,
11637                                                 SS, ObjectTypePtr,
11638                                                 false);
11639     if (!T)
11640       return ExprError();
11641 
11642     Destroyed
11643       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
11644                                                  E->getDestroyedTypeLoc());
11645   }
11646 
11647   TypeSourceInfo *ScopeTypeInfo = nullptr;
11648   if (E->getScopeTypeInfo()) {
11649     CXXScopeSpec EmptySS;
11650     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
11651                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
11652     if (!ScopeTypeInfo)
11653       return ExprError();
11654   }
11655 
11656   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
11657                                                      E->getOperatorLoc(),
11658                                                      E->isArrow(),
11659                                                      SS,
11660                                                      ScopeTypeInfo,
11661                                                      E->getColonColonLoc(),
11662                                                      E->getTildeLoc(),
11663                                                      Destroyed);
11664 }
11665 
11666 template <typename Derived>
11667 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
11668                                                         bool RequiresADL,
11669                                                         LookupResult &R) {
11670   // Transform all the decls.
11671   bool AllEmptyPacks = true;
11672   for (auto *OldD : Old->decls()) {
11673     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
11674     if (!InstD) {
11675       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
11676       // This can happen because of dependent hiding.
11677       if (isa<UsingShadowDecl>(OldD))
11678         continue;
11679       else {
11680         R.clear();
11681         return true;
11682       }
11683     }
11684 
11685     // Expand using pack declarations.
11686     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
11687     ArrayRef<NamedDecl*> Decls = SingleDecl;
11688     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
11689       Decls = UPD->expansions();
11690 
11691     // Expand using declarations.
11692     for (auto *D : Decls) {
11693       if (auto *UD = dyn_cast<UsingDecl>(D)) {
11694         for (auto *SD : UD->shadows())
11695           R.addDecl(SD);
11696       } else {
11697         R.addDecl(D);
11698       }
11699     }
11700 
11701     AllEmptyPacks &= Decls.empty();
11702   };
11703 
11704   // C++ [temp.res]/8.4.2:
11705   //   The program is ill-formed, no diagnostic required, if [...] lookup for
11706   //   a name in the template definition found a using-declaration, but the
11707   //   lookup in the corresponding scope in the instantiation odoes not find
11708   //   any declarations because the using-declaration was a pack expansion and
11709   //   the corresponding pack is empty
11710   if (AllEmptyPacks && !RequiresADL) {
11711     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
11712         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
11713     return true;
11714   }
11715 
11716   // Resolve a kind, but don't do any further analysis.  If it's
11717   // ambiguous, the callee needs to deal with it.
11718   R.resolveKind();
11719   return false;
11720 }
11721 
11722 template<typename Derived>
11723 ExprResult
11724 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
11725                                                   UnresolvedLookupExpr *Old) {
11726   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
11727                  Sema::LookupOrdinaryName);
11728 
11729   // Transform the declaration set.
11730   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
11731     return ExprError();
11732 
11733   // Rebuild the nested-name qualifier, if present.
11734   CXXScopeSpec SS;
11735   if (Old->getQualifierLoc()) {
11736     NestedNameSpecifierLoc QualifierLoc
11737       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11738     if (!QualifierLoc)
11739       return ExprError();
11740 
11741     SS.Adopt(QualifierLoc);
11742   }
11743 
11744   if (Old->getNamingClass()) {
11745     CXXRecordDecl *NamingClass
11746       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11747                                                             Old->getNameLoc(),
11748                                                         Old->getNamingClass()));
11749     if (!NamingClass) {
11750       R.clear();
11751       return ExprError();
11752     }
11753 
11754     R.setNamingClass(NamingClass);
11755   }
11756 
11757   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11758 
11759   // If we have neither explicit template arguments, nor the template keyword,
11760   // it's a normal declaration name or member reference.
11761   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
11762     NamedDecl *D = R.getAsSingle<NamedDecl>();
11763     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
11764     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
11765     // give a good diagnostic.
11766     if (D && D->isCXXInstanceMember()) {
11767       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11768                                                      /*TemplateArgs=*/nullptr,
11769                                                      /*Scope=*/nullptr);
11770     }
11771 
11772     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
11773   }
11774 
11775   // If we have template arguments, rebuild them, then rebuild the
11776   // templateid expression.
11777   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
11778   if (Old->hasExplicitTemplateArgs() &&
11779       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11780                                               Old->getNumTemplateArgs(),
11781                                               TransArgs)) {
11782     R.clear();
11783     return ExprError();
11784   }
11785 
11786   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
11787                                             Old->requiresADL(), &TransArgs);
11788 }
11789 
11790 template<typename Derived>
11791 ExprResult
11792 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
11793   bool ArgChanged = false;
11794   SmallVector<TypeSourceInfo *, 4> Args;
11795   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
11796     TypeSourceInfo *From = E->getArg(I);
11797     TypeLoc FromTL = From->getTypeLoc();
11798     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
11799       TypeLocBuilder TLB;
11800       TLB.reserve(FromTL.getFullDataSize());
11801       QualType To = getDerived().TransformType(TLB, FromTL);
11802       if (To.isNull())
11803         return ExprError();
11804 
11805       if (To == From->getType())
11806         Args.push_back(From);
11807       else {
11808         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11809         ArgChanged = true;
11810       }
11811       continue;
11812     }
11813 
11814     ArgChanged = true;
11815 
11816     // We have a pack expansion. Instantiate it.
11817     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
11818     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
11819     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11820     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
11821 
11822     // Determine whether the set of unexpanded parameter packs can and should
11823     // be expanded.
11824     bool Expand = true;
11825     bool RetainExpansion = false;
11826     Optional<unsigned> OrigNumExpansions =
11827         ExpansionTL.getTypePtr()->getNumExpansions();
11828     Optional<unsigned> NumExpansions = OrigNumExpansions;
11829     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
11830                                              PatternTL.getSourceRange(),
11831                                              Unexpanded,
11832                                              Expand, RetainExpansion,
11833                                              NumExpansions))
11834       return ExprError();
11835 
11836     if (!Expand) {
11837       // The transform has determined that we should perform a simple
11838       // transformation on the pack expansion, producing another pack
11839       // expansion.
11840       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11841 
11842       TypeLocBuilder TLB;
11843       TLB.reserve(From->getTypeLoc().getFullDataSize());
11844 
11845       QualType To = getDerived().TransformType(TLB, PatternTL);
11846       if (To.isNull())
11847         return ExprError();
11848 
11849       To = getDerived().RebuildPackExpansionType(To,
11850                                                  PatternTL.getSourceRange(),
11851                                                  ExpansionTL.getEllipsisLoc(),
11852                                                  NumExpansions);
11853       if (To.isNull())
11854         return ExprError();
11855 
11856       PackExpansionTypeLoc ToExpansionTL
11857         = TLB.push<PackExpansionTypeLoc>(To);
11858       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11859       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11860       continue;
11861     }
11862 
11863     // Expand the pack expansion by substituting for each argument in the
11864     // pack(s).
11865     for (unsigned I = 0; I != *NumExpansions; ++I) {
11866       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
11867       TypeLocBuilder TLB;
11868       TLB.reserve(PatternTL.getFullDataSize());
11869       QualType To = getDerived().TransformType(TLB, PatternTL);
11870       if (To.isNull())
11871         return ExprError();
11872 
11873       if (To->containsUnexpandedParameterPack()) {
11874         To = getDerived().RebuildPackExpansionType(To,
11875                                                    PatternTL.getSourceRange(),
11876                                                    ExpansionTL.getEllipsisLoc(),
11877                                                    NumExpansions);
11878         if (To.isNull())
11879           return ExprError();
11880 
11881         PackExpansionTypeLoc ToExpansionTL
11882           = TLB.push<PackExpansionTypeLoc>(To);
11883         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11884       }
11885 
11886       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11887     }
11888 
11889     if (!RetainExpansion)
11890       continue;
11891 
11892     // If we're supposed to retain a pack expansion, do so by temporarily
11893     // forgetting the partially-substituted parameter pack.
11894     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11895 
11896     TypeLocBuilder TLB;
11897     TLB.reserve(From->getTypeLoc().getFullDataSize());
11898 
11899     QualType To = getDerived().TransformType(TLB, PatternTL);
11900     if (To.isNull())
11901       return ExprError();
11902 
11903     To = getDerived().RebuildPackExpansionType(To,
11904                                                PatternTL.getSourceRange(),
11905                                                ExpansionTL.getEllipsisLoc(),
11906                                                NumExpansions);
11907     if (To.isNull())
11908       return ExprError();
11909 
11910     PackExpansionTypeLoc ToExpansionTL
11911       = TLB.push<PackExpansionTypeLoc>(To);
11912     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11913     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11914   }
11915 
11916   if (!getDerived().AlwaysRebuild() && !ArgChanged)
11917     return E;
11918 
11919   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
11920                                        E->getEndLoc());
11921 }
11922 
11923 template<typename Derived>
11924 ExprResult
11925 TreeTransform<Derived>::TransformConceptSpecializationExpr(
11926                                                  ConceptSpecializationExpr *E) {
11927   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
11928   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
11929   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11930                                               Old->NumTemplateArgs, TransArgs))
11931     return ExprError();
11932 
11933   return getDerived().RebuildConceptSpecializationExpr(
11934       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
11935       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
11936       &TransArgs);
11937 }
11938 
11939 template<typename Derived>
11940 ExprResult
11941 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
11942   SmallVector<ParmVarDecl*, 4> TransParams;
11943   SmallVector<QualType, 4> TransParamTypes;
11944   Sema::ExtParameterInfoBuilder ExtParamInfos;
11945 
11946   // C++2a [expr.prim.req]p2
11947   // Expressions appearing within a requirement-body are unevaluated operands.
11948   EnterExpressionEvaluationContext Ctx(
11949       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11950 
11951   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
11952       getSema().Context, getSema().CurContext,
11953       E->getBody()->getBeginLoc());
11954 
11955   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
11956 
11957   if (getDerived().TransformFunctionTypeParams(E->getRequiresKWLoc(),
11958                                                E->getLocalParameters(),
11959                                                /*ParamTypes=*/nullptr,
11960                                                /*ParamInfos=*/nullptr,
11961                                                TransParamTypes, &TransParams,
11962                                                ExtParamInfos))
11963     return ExprError();
11964 
11965   for (ParmVarDecl *Param : TransParams)
11966     Param->setDeclContext(Body);
11967 
11968   SmallVector<concepts::Requirement *, 4> TransReqs;
11969   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
11970                                                      TransReqs))
11971     return ExprError();
11972 
11973   for (concepts::Requirement *Req : TransReqs) {
11974     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
11975       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
11976         ER->getReturnTypeRequirement()
11977                 .getTypeConstraintTemplateParameterList()->getParam(0)
11978                 ->setDeclContext(Body);
11979       }
11980     }
11981   }
11982 
11983   return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
11984                                           TransParams, TransReqs,
11985                                           E->getRBraceLoc());
11986 }
11987 
11988 template<typename Derived>
11989 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
11990     ArrayRef<concepts::Requirement *> Reqs,
11991     SmallVectorImpl<concepts::Requirement *> &Transformed) {
11992   for (concepts::Requirement *Req : Reqs) {
11993     concepts::Requirement *TransReq = nullptr;
11994     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
11995       TransReq = getDerived().TransformTypeRequirement(TypeReq);
11996     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
11997       TransReq = getDerived().TransformExprRequirement(ExprReq);
11998     else
11999       TransReq = getDerived().TransformNestedRequirement(
12000                      cast<concepts::NestedRequirement>(Req));
12001     if (!TransReq)
12002       return true;
12003     Transformed.push_back(TransReq);
12004   }
12005   return false;
12006 }
12007 
12008 template<typename Derived>
12009 concepts::TypeRequirement *
12010 TreeTransform<Derived>::TransformTypeRequirement(
12011     concepts::TypeRequirement *Req) {
12012   if (Req->isSubstitutionFailure()) {
12013     if (getDerived().AlwaysRebuild())
12014       return getDerived().RebuildTypeRequirement(
12015               Req->getSubstitutionDiagnostic());
12016     return Req;
12017   }
12018   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12019   if (!TransType)
12020     return nullptr;
12021   return getDerived().RebuildTypeRequirement(TransType);
12022 }
12023 
12024 template<typename Derived>
12025 concepts::ExprRequirement *
12026 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12027   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12028   if (Req->isExprSubstitutionFailure())
12029     TransExpr = Req->getExprSubstitutionDiagnostic();
12030   else {
12031     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12032     if (TransExprRes.isInvalid())
12033       return nullptr;
12034     TransExpr = TransExprRes.get();
12035   }
12036 
12037   llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12038   const auto &RetReq = Req->getReturnTypeRequirement();
12039   if (RetReq.isEmpty())
12040     TransRetReq.emplace();
12041   else if (RetReq.isSubstitutionFailure())
12042     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12043   else if (RetReq.isTypeConstraint()) {
12044     TemplateParameterList *OrigTPL =
12045         RetReq.getTypeConstraintTemplateParameterList();
12046     TemplateParameterList *TPL =
12047         getDerived().TransformTemplateParameterList(OrigTPL);
12048     if (!TPL)
12049       return nullptr;
12050     TransRetReq.emplace(TPL);
12051   }
12052   assert(TransRetReq.hasValue() &&
12053          "All code paths leading here must set TransRetReq");
12054   if (Expr *E = TransExpr.dyn_cast<Expr *>())
12055     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12056                                                Req->getNoexceptLoc(),
12057                                                std::move(*TransRetReq));
12058   return getDerived().RebuildExprRequirement(
12059       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12060       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12061 }
12062 
12063 template<typename Derived>
12064 concepts::NestedRequirement *
12065 TreeTransform<Derived>::TransformNestedRequirement(
12066     concepts::NestedRequirement *Req) {
12067   if (Req->isSubstitutionFailure()) {
12068     if (getDerived().AlwaysRebuild())
12069       return getDerived().RebuildNestedRequirement(
12070           Req->getSubstitutionDiagnostic());
12071     return Req;
12072   }
12073   ExprResult TransConstraint =
12074       getDerived().TransformExpr(Req->getConstraintExpr());
12075   if (TransConstraint.isInvalid())
12076     return nullptr;
12077   return getDerived().RebuildNestedRequirement(TransConstraint.get());
12078 }
12079 
12080 template<typename Derived>
12081 ExprResult
12082 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12083   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12084   if (!T)
12085     return ExprError();
12086 
12087   if (!getDerived().AlwaysRebuild() &&
12088       T == E->getQueriedTypeSourceInfo())
12089     return E;
12090 
12091   ExprResult SubExpr;
12092   {
12093     EnterExpressionEvaluationContext Unevaluated(
12094         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12095     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12096     if (SubExpr.isInvalid())
12097       return ExprError();
12098 
12099     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12100       return E;
12101   }
12102 
12103   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12104                                             SubExpr.get(), E->getEndLoc());
12105 }
12106 
12107 template<typename Derived>
12108 ExprResult
12109 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12110   ExprResult SubExpr;
12111   {
12112     EnterExpressionEvaluationContext Unevaluated(
12113         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12114     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12115     if (SubExpr.isInvalid())
12116       return ExprError();
12117 
12118     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12119       return E;
12120   }
12121 
12122   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12123                                              SubExpr.get(), E->getEndLoc());
12124 }
12125 
12126 template <typename Derived>
12127 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12128     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12129     TypeSourceInfo **RecoveryTSI) {
12130   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
12131       DRE, AddrTaken, RecoveryTSI);
12132 
12133   // Propagate both errors and recovered types, which return ExprEmpty.
12134   if (!NewDRE.isUsable())
12135     return NewDRE;
12136 
12137   // We got an expr, wrap it up in parens.
12138   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
12139     return PE;
12140   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
12141                                        PE->getRParen());
12142 }
12143 
12144 template <typename Derived>
12145 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12146     DependentScopeDeclRefExpr *E) {
12147   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
12148                                             nullptr);
12149 }
12150 
12151 template<typename Derived>
12152 ExprResult
12153 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12154                                                DependentScopeDeclRefExpr *E,
12155                                                bool IsAddressOfOperand,
12156                                                TypeSourceInfo **RecoveryTSI) {
12157   assert(E->getQualifierLoc());
12158   NestedNameSpecifierLoc QualifierLoc
12159   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
12160   if (!QualifierLoc)
12161     return ExprError();
12162   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12163 
12164   // TODO: If this is a conversion-function-id, verify that the
12165   // destination type name (if present) resolves the same way after
12166   // instantiation as it did in the local scope.
12167 
12168   DeclarationNameInfo NameInfo
12169     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
12170   if (!NameInfo.getName())
12171     return ExprError();
12172 
12173   if (!E->hasExplicitTemplateArgs()) {
12174     if (!getDerived().AlwaysRebuild() &&
12175         QualifierLoc == E->getQualifierLoc() &&
12176         // Note: it is sufficient to compare the Name component of NameInfo:
12177         // if name has not changed, DNLoc has not changed either.
12178         NameInfo.getName() == E->getDeclName())
12179       return E;
12180 
12181     return getDerived().RebuildDependentScopeDeclRefExpr(
12182         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
12183         IsAddressOfOperand, RecoveryTSI);
12184   }
12185 
12186   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12187   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
12188                                               E->getNumTemplateArgs(),
12189                                               TransArgs))
12190     return ExprError();
12191 
12192   return getDerived().RebuildDependentScopeDeclRefExpr(
12193       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
12194       RecoveryTSI);
12195 }
12196 
12197 template<typename Derived>
12198 ExprResult
12199 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
12200   // CXXConstructExprs other than for list-initialization and
12201   // CXXTemporaryObjectExpr are always implicit, so when we have
12202   // a 1-argument construction we just transform that argument.
12203   if (getDerived().AllowSkippingCXXConstructExpr() &&
12204       ((E->getNumArgs() == 1 ||
12205         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
12206        (!getDerived().DropCallArgument(E->getArg(0))) &&
12207        !E->isListInitialization()))
12208     return getDerived().TransformExpr(E->getArg(0));
12209 
12210   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
12211 
12212   QualType T = getDerived().TransformType(E->getType());
12213   if (T.isNull())
12214     return ExprError();
12215 
12216   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12217       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12218   if (!Constructor)
12219     return ExprError();
12220 
12221   bool ArgumentChanged = false;
12222   SmallVector<Expr*, 8> Args;
12223   {
12224     EnterExpressionEvaluationContext Context(
12225         getSema(), EnterExpressionEvaluationContext::InitList,
12226         E->isListInitialization());
12227     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12228                                     &ArgumentChanged))
12229       return ExprError();
12230   }
12231 
12232   if (!getDerived().AlwaysRebuild() &&
12233       T == E->getType() &&
12234       Constructor == E->getConstructor() &&
12235       !ArgumentChanged) {
12236     // Mark the constructor as referenced.
12237     // FIXME: Instantiation-specific
12238     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12239     return E;
12240   }
12241 
12242   return getDerived().RebuildCXXConstructExpr(
12243       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
12244       E->hadMultipleCandidates(), E->isListInitialization(),
12245       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
12246       E->getConstructionKind(), E->getParenOrBraceRange());
12247 }
12248 
12249 template<typename Derived>
12250 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
12251     CXXInheritedCtorInitExpr *E) {
12252   QualType T = getDerived().TransformType(E->getType());
12253   if (T.isNull())
12254     return ExprError();
12255 
12256   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12257       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12258   if (!Constructor)
12259     return ExprError();
12260 
12261   if (!getDerived().AlwaysRebuild() &&
12262       T == E->getType() &&
12263       Constructor == E->getConstructor()) {
12264     // Mark the constructor as referenced.
12265     // FIXME: Instantiation-specific
12266     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12267     return E;
12268   }
12269 
12270   return getDerived().RebuildCXXInheritedCtorInitExpr(
12271       T, E->getLocation(), Constructor,
12272       E->constructsVBase(), E->inheritedFromVBase());
12273 }
12274 
12275 /// Transform a C++ temporary-binding expression.
12276 ///
12277 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
12278 /// transform the subexpression and return that.
12279 template<typename Derived>
12280 ExprResult
12281 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12282   return getDerived().TransformExpr(E->getSubExpr());
12283 }
12284 
12285 /// Transform a C++ expression that contains cleanups that should
12286 /// be run after the expression is evaluated.
12287 ///
12288 /// Since ExprWithCleanups nodes are implicitly generated, we
12289 /// just transform the subexpression and return that.
12290 template<typename Derived>
12291 ExprResult
12292 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
12293   return getDerived().TransformExpr(E->getSubExpr());
12294 }
12295 
12296 template<typename Derived>
12297 ExprResult
12298 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
12299                                                     CXXTemporaryObjectExpr *E) {
12300   TypeSourceInfo *T =
12301       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12302   if (!T)
12303     return ExprError();
12304 
12305   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12306       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12307   if (!Constructor)
12308     return ExprError();
12309 
12310   bool ArgumentChanged = false;
12311   SmallVector<Expr*, 8> Args;
12312   Args.reserve(E->getNumArgs());
12313   {
12314     EnterExpressionEvaluationContext Context(
12315         getSema(), EnterExpressionEvaluationContext::InitList,
12316         E->isListInitialization());
12317     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12318                        &ArgumentChanged))
12319       return ExprError();
12320   }
12321 
12322   if (!getDerived().AlwaysRebuild() &&
12323       T == E->getTypeSourceInfo() &&
12324       Constructor == E->getConstructor() &&
12325       !ArgumentChanged) {
12326     // FIXME: Instantiation-specific
12327     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12328     return SemaRef.MaybeBindToTemporary(E);
12329   }
12330 
12331   // FIXME: We should just pass E->isListInitialization(), but we're not
12332   // prepared to handle list-initialization without a child InitListExpr.
12333   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
12334   return getDerived().RebuildCXXTemporaryObjectExpr(
12335       T, LParenLoc, Args, E->getEndLoc(),
12336       /*ListInitialization=*/LParenLoc.isInvalid());
12337 }
12338 
12339 template<typename Derived>
12340 ExprResult
12341 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
12342   // Transform any init-capture expressions before entering the scope of the
12343   // lambda body, because they are not semantically within that scope.
12344   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
12345   struct TransformedInitCapture {
12346     // The location of the ... if the result is retaining a pack expansion.
12347     SourceLocation EllipsisLoc;
12348     // Zero or more expansions of the init-capture.
12349     SmallVector<InitCaptureInfoTy, 4> Expansions;
12350   };
12351   SmallVector<TransformedInitCapture, 4> InitCaptures;
12352   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
12353   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12354                                     CEnd = E->capture_end();
12355        C != CEnd; ++C) {
12356     if (!E->isInitCapture(C))
12357       continue;
12358 
12359     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
12360     VarDecl *OldVD = C->getCapturedVar();
12361 
12362     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
12363                                 Optional<unsigned> NumExpansions) {
12364       ExprResult NewExprInitResult = getDerived().TransformInitializer(
12365           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
12366 
12367       if (NewExprInitResult.isInvalid()) {
12368         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
12369         return;
12370       }
12371       Expr *NewExprInit = NewExprInitResult.get();
12372 
12373       QualType NewInitCaptureType =
12374           getSema().buildLambdaInitCaptureInitialization(
12375               C->getLocation(), OldVD->getType()->isReferenceType(),
12376               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
12377               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
12378               NewExprInit);
12379       Result.Expansions.push_back(
12380           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
12381     };
12382 
12383     // If this is an init-capture pack, consider expanding the pack now.
12384     if (OldVD->isParameterPack()) {
12385       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
12386                                              ->getTypeLoc()
12387                                              .castAs<PackExpansionTypeLoc>();
12388       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12389       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
12390 
12391       // Determine whether the set of unexpanded parameter packs can and should
12392       // be expanded.
12393       bool Expand = true;
12394       bool RetainExpansion = false;
12395       Optional<unsigned> OrigNumExpansions =
12396           ExpansionTL.getTypePtr()->getNumExpansions();
12397       Optional<unsigned> NumExpansions = OrigNumExpansions;
12398       if (getDerived().TryExpandParameterPacks(
12399               ExpansionTL.getEllipsisLoc(),
12400               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
12401               RetainExpansion, NumExpansions))
12402         return ExprError();
12403       if (Expand) {
12404         for (unsigned I = 0; I != *NumExpansions; ++I) {
12405           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12406           SubstInitCapture(SourceLocation(), None);
12407         }
12408       }
12409       if (!Expand || RetainExpansion) {
12410         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12411         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
12412         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
12413       }
12414     } else {
12415       SubstInitCapture(SourceLocation(), None);
12416     }
12417   }
12418 
12419   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
12420   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
12421 
12422   // Transform the template parameters, and add them to the current
12423   // instantiation scope. The null case is handled correctly.
12424   auto TPL = getDerived().TransformTemplateParameterList(
12425       E->getTemplateParameterList());
12426   LSI->GLTemplateParameterList = TPL;
12427 
12428   // Transform the type of the original lambda's call operator.
12429   // The transformation MUST be done in the CurrentInstantiationScope since
12430   // it introduces a mapping of the original to the newly created
12431   // transformed parameters.
12432   TypeSourceInfo *NewCallOpTSI = nullptr;
12433   {
12434     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
12435     FunctionProtoTypeLoc OldCallOpFPTL =
12436         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
12437 
12438     TypeLocBuilder NewCallOpTLBuilder;
12439     SmallVector<QualType, 4> ExceptionStorage;
12440     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
12441     QualType NewCallOpType = TransformFunctionProtoType(
12442         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
12443         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
12444           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
12445                                               ExceptionStorage, Changed);
12446         });
12447     if (NewCallOpType.isNull())
12448       return ExprError();
12449     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
12450                                                         NewCallOpType);
12451   }
12452 
12453   // Transform the trailing requires clause
12454   ExprResult NewTrailingRequiresClause;
12455   if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
12456     // FIXME: Concepts: Substitution into requires clause should only happen
12457     //                  when checking satisfaction.
12458     NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
12459 
12460   // Create the local class that will describe the lambda.
12461   // FIXME: KnownDependent below is wrong when substituting inside a templated
12462   // context that isn't a DeclContext (such as a variable template).
12463   CXXRecordDecl *OldClass = E->getLambdaClass();
12464   CXXRecordDecl *Class
12465     = getSema().createLambdaClosureType(E->getIntroducerRange(),
12466                                         NewCallOpTSI,
12467                                         /*KnownDependent=*/false,
12468                                         E->getCaptureDefault());
12469   getDerived().transformedLocalDecl(OldClass, {Class});
12470 
12471   Optional<std::tuple<unsigned, bool, Decl *>> Mangling;
12472   if (getDerived().ReplacingOriginal())
12473     Mangling = std::make_tuple(OldClass->getLambdaManglingNumber(),
12474                                OldClass->hasKnownLambdaInternalLinkage(),
12475                                OldClass->getLambdaContextDecl());
12476 
12477   // Build the call operator.
12478   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
12479       Class, E->getIntroducerRange(), NewCallOpTSI,
12480       E->getCallOperator()->getEndLoc(),
12481       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
12482       E->getCallOperator()->getConstexprKind(),
12483       NewTrailingRequiresClause.get());
12484 
12485   LSI->CallOperator = NewCallOperator;
12486 
12487   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
12488   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
12489 
12490   // Number the lambda for linkage purposes if necessary.
12491   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
12492 
12493   // Introduce the context of the call operator.
12494   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
12495                                  /*NewThisContext*/false);
12496 
12497   // Enter the scope of the lambda.
12498   getSema().buildLambdaScope(LSI, NewCallOperator,
12499                              E->getIntroducerRange(),
12500                              E->getCaptureDefault(),
12501                              E->getCaptureDefaultLoc(),
12502                              E->hasExplicitParameters(),
12503                              E->hasExplicitResultType(),
12504                              E->isMutable());
12505 
12506   bool Invalid = false;
12507 
12508   // Transform captures.
12509   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12510                                  CEnd = E->capture_end();
12511        C != CEnd; ++C) {
12512     // When we hit the first implicit capture, tell Sema that we've finished
12513     // the list of explicit captures.
12514     if (C->isImplicit())
12515       break;
12516 
12517     // Capturing 'this' is trivial.
12518     if (C->capturesThis()) {
12519       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
12520                                     /*BuildAndDiagnose*/ true, nullptr,
12521                                     C->getCaptureKind() == LCK_StarThis);
12522       continue;
12523     }
12524     // Captured expression will be recaptured during captured variables
12525     // rebuilding.
12526     if (C->capturesVLAType())
12527       continue;
12528 
12529     // Rebuild init-captures, including the implied field declaration.
12530     if (E->isInitCapture(C)) {
12531       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
12532 
12533       VarDecl *OldVD = C->getCapturedVar();
12534       llvm::SmallVector<Decl*, 4> NewVDs;
12535 
12536       for (InitCaptureInfoTy &Info : NewC.Expansions) {
12537         ExprResult Init = Info.first;
12538         QualType InitQualType = Info.second;
12539         if (Init.isInvalid() || InitQualType.isNull()) {
12540           Invalid = true;
12541           break;
12542         }
12543         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
12544             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
12545             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
12546         if (!NewVD) {
12547           Invalid = true;
12548           break;
12549         }
12550         NewVDs.push_back(NewVD);
12551         getSema().addInitCapture(LSI, NewVD);
12552       }
12553 
12554       if (Invalid)
12555         break;
12556 
12557       getDerived().transformedLocalDecl(OldVD, NewVDs);
12558       continue;
12559     }
12560 
12561     assert(C->capturesVariable() && "unexpected kind of lambda capture");
12562 
12563     // Determine the capture kind for Sema.
12564     Sema::TryCaptureKind Kind
12565       = C->isImplicit()? Sema::TryCapture_Implicit
12566                        : C->getCaptureKind() == LCK_ByCopy
12567                            ? Sema::TryCapture_ExplicitByVal
12568                            : Sema::TryCapture_ExplicitByRef;
12569     SourceLocation EllipsisLoc;
12570     if (C->isPackExpansion()) {
12571       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
12572       bool ShouldExpand = false;
12573       bool RetainExpansion = false;
12574       Optional<unsigned> NumExpansions;
12575       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
12576                                                C->getLocation(),
12577                                                Unexpanded,
12578                                                ShouldExpand, RetainExpansion,
12579                                                NumExpansions)) {
12580         Invalid = true;
12581         continue;
12582       }
12583 
12584       if (ShouldExpand) {
12585         // The transform has determined that we should perform an expansion;
12586         // transform and capture each of the arguments.
12587         // expansion of the pattern. Do so.
12588         VarDecl *Pack = C->getCapturedVar();
12589         for (unsigned I = 0; I != *NumExpansions; ++I) {
12590           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12591           VarDecl *CapturedVar
12592             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
12593                                                                Pack));
12594           if (!CapturedVar) {
12595             Invalid = true;
12596             continue;
12597           }
12598 
12599           // Capture the transformed variable.
12600           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
12601         }
12602 
12603         // FIXME: Retain a pack expansion if RetainExpansion is true.
12604 
12605         continue;
12606       }
12607 
12608       EllipsisLoc = C->getEllipsisLoc();
12609     }
12610 
12611     // Transform the captured variable.
12612     VarDecl *CapturedVar
12613       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
12614                                                          C->getCapturedVar()));
12615     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
12616       Invalid = true;
12617       continue;
12618     }
12619 
12620     // Capture the transformed variable.
12621     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
12622                                  EllipsisLoc);
12623   }
12624   getSema().finishLambdaExplicitCaptures(LSI);
12625 
12626   // FIXME: Sema's lambda-building mechanism expects us to push an expression
12627   // evaluation context even if we're not transforming the function body.
12628   getSema().PushExpressionEvaluationContext(
12629       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
12630 
12631   // Instantiate the body of the lambda expression.
12632   StmtResult Body =
12633       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
12634 
12635   // ActOnLambda* will pop the function scope for us.
12636   FuncScopeCleanup.disable();
12637 
12638   if (Body.isInvalid()) {
12639     SavedContext.pop();
12640     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
12641                                /*IsInstantiation=*/true);
12642     return ExprError();
12643   }
12644 
12645   // Copy the LSI before ActOnFinishFunctionBody removes it.
12646   // FIXME: This is dumb. Store the lambda information somewhere that outlives
12647   // the call operator.
12648   auto LSICopy = *LSI;
12649   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
12650                                     /*IsInstantiation*/ true);
12651   SavedContext.pop();
12652 
12653   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
12654                                    &LSICopy);
12655 }
12656 
12657 template<typename Derived>
12658 StmtResult
12659 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
12660   return TransformStmt(S);
12661 }
12662 
12663 template<typename Derived>
12664 StmtResult
12665 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
12666   // Transform captures.
12667   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12668                                  CEnd = E->capture_end();
12669        C != CEnd; ++C) {
12670     // When we hit the first implicit capture, tell Sema that we've finished
12671     // the list of explicit captures.
12672     if (!C->isImplicit())
12673       continue;
12674 
12675     // Capturing 'this' is trivial.
12676     if (C->capturesThis()) {
12677       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
12678                                     /*BuildAndDiagnose*/ true, nullptr,
12679                                     C->getCaptureKind() == LCK_StarThis);
12680       continue;
12681     }
12682     // Captured expression will be recaptured during captured variables
12683     // rebuilding.
12684     if (C->capturesVLAType())
12685       continue;
12686 
12687     assert(C->capturesVariable() && "unexpected kind of lambda capture");
12688     assert(!E->isInitCapture(C) && "implicit init-capture?");
12689 
12690     // Transform the captured variable.
12691     VarDecl *CapturedVar = cast_or_null<VarDecl>(
12692         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
12693     if (!CapturedVar || CapturedVar->isInvalidDecl())
12694       return StmtError();
12695 
12696     // Capture the transformed variable.
12697     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
12698   }
12699 
12700   return S;
12701 }
12702 
12703 template<typename Derived>
12704 ExprResult
12705 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
12706                                                   CXXUnresolvedConstructExpr *E) {
12707   TypeSourceInfo *T =
12708       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12709   if (!T)
12710     return ExprError();
12711 
12712   bool ArgumentChanged = false;
12713   SmallVector<Expr*, 8> Args;
12714   Args.reserve(E->arg_size());
12715   {
12716     EnterExpressionEvaluationContext Context(
12717         getSema(), EnterExpressionEvaluationContext::InitList,
12718         E->isListInitialization());
12719     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
12720                                     &ArgumentChanged))
12721       return ExprError();
12722   }
12723 
12724   if (!getDerived().AlwaysRebuild() &&
12725       T == E->getTypeSourceInfo() &&
12726       !ArgumentChanged)
12727     return E;
12728 
12729   // FIXME: we're faking the locations of the commas
12730   return getDerived().RebuildCXXUnresolvedConstructExpr(
12731       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
12732 }
12733 
12734 template<typename Derived>
12735 ExprResult
12736 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
12737                                              CXXDependentScopeMemberExpr *E) {
12738   // Transform the base of the expression.
12739   ExprResult Base((Expr*) nullptr);
12740   Expr *OldBase;
12741   QualType BaseType;
12742   QualType ObjectType;
12743   if (!E->isImplicitAccess()) {
12744     OldBase = E->getBase();
12745     Base = getDerived().TransformExpr(OldBase);
12746     if (Base.isInvalid())
12747       return ExprError();
12748 
12749     // Start the member reference and compute the object's type.
12750     ParsedType ObjectTy;
12751     bool MayBePseudoDestructor = false;
12752     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12753                                                 E->getOperatorLoc(),
12754                                       E->isArrow()? tok::arrow : tok::period,
12755                                                 ObjectTy,
12756                                                 MayBePseudoDestructor);
12757     if (Base.isInvalid())
12758       return ExprError();
12759 
12760     ObjectType = ObjectTy.get();
12761     BaseType = ((Expr*) Base.get())->getType();
12762   } else {
12763     OldBase = nullptr;
12764     BaseType = getDerived().TransformType(E->getBaseType());
12765     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
12766   }
12767 
12768   // Transform the first part of the nested-name-specifier that qualifies
12769   // the member name.
12770   NamedDecl *FirstQualifierInScope
12771     = getDerived().TransformFirstQualifierInScope(
12772                                             E->getFirstQualifierFoundInScope(),
12773                                             E->getQualifierLoc().getBeginLoc());
12774 
12775   NestedNameSpecifierLoc QualifierLoc;
12776   if (E->getQualifier()) {
12777     QualifierLoc
12778       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
12779                                                      ObjectType,
12780                                                      FirstQualifierInScope);
12781     if (!QualifierLoc)
12782       return ExprError();
12783   }
12784 
12785   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12786 
12787   // TODO: If this is a conversion-function-id, verify that the
12788   // destination type name (if present) resolves the same way after
12789   // instantiation as it did in the local scope.
12790 
12791   DeclarationNameInfo NameInfo
12792     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
12793   if (!NameInfo.getName())
12794     return ExprError();
12795 
12796   if (!E->hasExplicitTemplateArgs()) {
12797     // This is a reference to a member without an explicitly-specified
12798     // template argument list. Optimize for this common case.
12799     if (!getDerived().AlwaysRebuild() &&
12800         Base.get() == OldBase &&
12801         BaseType == E->getBaseType() &&
12802         QualifierLoc == E->getQualifierLoc() &&
12803         NameInfo.getName() == E->getMember() &&
12804         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
12805       return E;
12806 
12807     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
12808                                                        BaseType,
12809                                                        E->isArrow(),
12810                                                        E->getOperatorLoc(),
12811                                                        QualifierLoc,
12812                                                        TemplateKWLoc,
12813                                                        FirstQualifierInScope,
12814                                                        NameInfo,
12815                                                        /*TemplateArgs*/nullptr);
12816   }
12817 
12818   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12819   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
12820                                               E->getNumTemplateArgs(),
12821                                               TransArgs))
12822     return ExprError();
12823 
12824   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
12825                                                      BaseType,
12826                                                      E->isArrow(),
12827                                                      E->getOperatorLoc(),
12828                                                      QualifierLoc,
12829                                                      TemplateKWLoc,
12830                                                      FirstQualifierInScope,
12831                                                      NameInfo,
12832                                                      &TransArgs);
12833 }
12834 
12835 template<typename Derived>
12836 ExprResult
12837 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
12838   // Transform the base of the expression.
12839   ExprResult Base((Expr*) nullptr);
12840   QualType BaseType;
12841   if (!Old->isImplicitAccess()) {
12842     Base = getDerived().TransformExpr(Old->getBase());
12843     if (Base.isInvalid())
12844       return ExprError();
12845     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
12846                                                      Old->isArrow());
12847     if (Base.isInvalid())
12848       return ExprError();
12849     BaseType = Base.get()->getType();
12850   } else {
12851     BaseType = getDerived().TransformType(Old->getBaseType());
12852   }
12853 
12854   NestedNameSpecifierLoc QualifierLoc;
12855   if (Old->getQualifierLoc()) {
12856     QualifierLoc
12857     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12858     if (!QualifierLoc)
12859       return ExprError();
12860   }
12861 
12862   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12863 
12864   LookupResult R(SemaRef, Old->getMemberNameInfo(),
12865                  Sema::LookupOrdinaryName);
12866 
12867   // Transform the declaration set.
12868   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
12869     return ExprError();
12870 
12871   // Determine the naming class.
12872   if (Old->getNamingClass()) {
12873     CXXRecordDecl *NamingClass
12874       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12875                                                           Old->getMemberLoc(),
12876                                                         Old->getNamingClass()));
12877     if (!NamingClass)
12878       return ExprError();
12879 
12880     R.setNamingClass(NamingClass);
12881   }
12882 
12883   TemplateArgumentListInfo TransArgs;
12884   if (Old->hasExplicitTemplateArgs()) {
12885     TransArgs.setLAngleLoc(Old->getLAngleLoc());
12886     TransArgs.setRAngleLoc(Old->getRAngleLoc());
12887     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12888                                                 Old->getNumTemplateArgs(),
12889                                                 TransArgs))
12890       return ExprError();
12891   }
12892 
12893   // FIXME: to do this check properly, we will need to preserve the
12894   // first-qualifier-in-scope here, just in case we had a dependent
12895   // base (and therefore couldn't do the check) and a
12896   // nested-name-qualifier (and therefore could do the lookup).
12897   NamedDecl *FirstQualifierInScope = nullptr;
12898 
12899   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
12900                                                   BaseType,
12901                                                   Old->getOperatorLoc(),
12902                                                   Old->isArrow(),
12903                                                   QualifierLoc,
12904                                                   TemplateKWLoc,
12905                                                   FirstQualifierInScope,
12906                                                   R,
12907                                               (Old->hasExplicitTemplateArgs()
12908                                                   ? &TransArgs : nullptr));
12909 }
12910 
12911 template<typename Derived>
12912 ExprResult
12913 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
12914   EnterExpressionEvaluationContext Unevaluated(
12915       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12916   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
12917   if (SubExpr.isInvalid())
12918     return ExprError();
12919 
12920   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
12921     return E;
12922 
12923   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
12924 }
12925 
12926 template<typename Derived>
12927 ExprResult
12928 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
12929   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
12930   if (Pattern.isInvalid())
12931     return ExprError();
12932 
12933   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
12934     return E;
12935 
12936   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
12937                                            E->getNumExpansions());
12938 }
12939 
12940 template<typename Derived>
12941 ExprResult
12942 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
12943   // If E is not value-dependent, then nothing will change when we transform it.
12944   // Note: This is an instantiation-centric view.
12945   if (!E->isValueDependent())
12946     return E;
12947 
12948   EnterExpressionEvaluationContext Unevaluated(
12949       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
12950 
12951   ArrayRef<TemplateArgument> PackArgs;
12952   TemplateArgument ArgStorage;
12953 
12954   // Find the argument list to transform.
12955   if (E->isPartiallySubstituted()) {
12956     PackArgs = E->getPartialArguments();
12957   } else if (E->isValueDependent()) {
12958     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
12959     bool ShouldExpand = false;
12960     bool RetainExpansion = false;
12961     Optional<unsigned> NumExpansions;
12962     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
12963                                              Unexpanded,
12964                                              ShouldExpand, RetainExpansion,
12965                                              NumExpansions))
12966       return ExprError();
12967 
12968     // If we need to expand the pack, build a template argument from it and
12969     // expand that.
12970     if (ShouldExpand) {
12971       auto *Pack = E->getPack();
12972       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
12973         ArgStorage = getSema().Context.getPackExpansionType(
12974             getSema().Context.getTypeDeclType(TTPD), None);
12975       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
12976         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
12977       } else {
12978         auto *VD = cast<ValueDecl>(Pack);
12979         ExprResult DRE = getSema().BuildDeclRefExpr(
12980             VD, VD->getType().getNonLValueExprType(getSema().Context),
12981             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
12982             E->getPackLoc());
12983         if (DRE.isInvalid())
12984           return ExprError();
12985         ArgStorage = new (getSema().Context) PackExpansionExpr(
12986             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
12987       }
12988       PackArgs = ArgStorage;
12989     }
12990   }
12991 
12992   // If we're not expanding the pack, just transform the decl.
12993   if (!PackArgs.size()) {
12994     auto *Pack = cast_or_null<NamedDecl>(
12995         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
12996     if (!Pack)
12997       return ExprError();
12998     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
12999                                               E->getPackLoc(),
13000                                               E->getRParenLoc(), None, None);
13001   }
13002 
13003   // Try to compute the result without performing a partial substitution.
13004   Optional<unsigned> Result = 0;
13005   for (const TemplateArgument &Arg : PackArgs) {
13006     if (!Arg.isPackExpansion()) {
13007       Result = *Result + 1;
13008       continue;
13009     }
13010 
13011     TemplateArgumentLoc ArgLoc;
13012     InventTemplateArgumentLoc(Arg, ArgLoc);
13013 
13014     // Find the pattern of the pack expansion.
13015     SourceLocation Ellipsis;
13016     Optional<unsigned> OrigNumExpansions;
13017     TemplateArgumentLoc Pattern =
13018         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13019                                                           OrigNumExpansions);
13020 
13021     // Substitute under the pack expansion. Do not expand the pack (yet).
13022     TemplateArgumentLoc OutPattern;
13023     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13024     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13025                                                /*Uneval*/ true))
13026       return true;
13027 
13028     // See if we can determine the number of arguments from the result.
13029     Optional<unsigned> NumExpansions =
13030         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13031     if (!NumExpansions) {
13032       // No: we must be in an alias template expansion, and we're going to need
13033       // to actually expand the packs.
13034       Result = None;
13035       break;
13036     }
13037 
13038     Result = *Result + *NumExpansions;
13039   }
13040 
13041   // Common case: we could determine the number of expansions without
13042   // substituting.
13043   if (Result)
13044     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13045                                               E->getPackLoc(),
13046                                               E->getRParenLoc(), *Result, None);
13047 
13048   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13049                                                E->getPackLoc());
13050   {
13051     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13052     typedef TemplateArgumentLocInventIterator<
13053         Derived, const TemplateArgument*> PackLocIterator;
13054     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13055                                    PackLocIterator(*this, PackArgs.end()),
13056                                    TransformedPackArgs, /*Uneval*/true))
13057       return ExprError();
13058   }
13059 
13060   // Check whether we managed to fully-expand the pack.
13061   // FIXME: Is it possible for us to do so and not hit the early exit path?
13062   SmallVector<TemplateArgument, 8> Args;
13063   bool PartialSubstitution = false;
13064   for (auto &Loc : TransformedPackArgs.arguments()) {
13065     Args.push_back(Loc.getArgument());
13066     if (Loc.getArgument().isPackExpansion())
13067       PartialSubstitution = true;
13068   }
13069 
13070   if (PartialSubstitution)
13071     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13072                                               E->getPackLoc(),
13073                                               E->getRParenLoc(), None, Args);
13074 
13075   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13076                                             E->getPackLoc(), E->getRParenLoc(),
13077                                             Args.size(), None);
13078 }
13079 
13080 template<typename Derived>
13081 ExprResult
13082 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13083                                           SubstNonTypeTemplateParmPackExpr *E) {
13084   // Default behavior is to do nothing with this transformation.
13085   return E;
13086 }
13087 
13088 template<typename Derived>
13089 ExprResult
13090 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13091                                           SubstNonTypeTemplateParmExpr *E) {
13092   // Default behavior is to do nothing with this transformation.
13093   return E;
13094 }
13095 
13096 template<typename Derived>
13097 ExprResult
13098 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13099   // Default behavior is to do nothing with this transformation.
13100   return E;
13101 }
13102 
13103 template<typename Derived>
13104 ExprResult
13105 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13106                                                   MaterializeTemporaryExpr *E) {
13107   return getDerived().TransformExpr(E->getSubExpr());
13108 }
13109 
13110 template<typename Derived>
13111 ExprResult
13112 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13113   Expr *Pattern = E->getPattern();
13114 
13115   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13116   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13117   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13118 
13119   // Determine whether the set of unexpanded parameter packs can and should
13120   // be expanded.
13121   bool Expand = true;
13122   bool RetainExpansion = false;
13123   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13124                      NumExpansions = OrigNumExpansions;
13125   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
13126                                            Pattern->getSourceRange(),
13127                                            Unexpanded,
13128                                            Expand, RetainExpansion,
13129                                            NumExpansions))
13130     return true;
13131 
13132   if (!Expand) {
13133     // Do not expand any packs here, just transform and rebuild a fold
13134     // expression.
13135     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13136 
13137     ExprResult LHS =
13138         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
13139     if (LHS.isInvalid())
13140       return true;
13141 
13142     ExprResult RHS =
13143         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
13144     if (RHS.isInvalid())
13145       return true;
13146 
13147     if (!getDerived().AlwaysRebuild() &&
13148         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
13149       return E;
13150 
13151     return getDerived().RebuildCXXFoldExpr(
13152         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
13153         RHS.get(), E->getEndLoc(), NumExpansions);
13154   }
13155 
13156   // The transform has determined that we should perform an elementwise
13157   // expansion of the pattern. Do so.
13158   ExprResult Result = getDerived().TransformExpr(E->getInit());
13159   if (Result.isInvalid())
13160     return true;
13161   bool LeftFold = E->isLeftFold();
13162 
13163   // If we're retaining an expansion for a right fold, it is the innermost
13164   // component and takes the init (if any).
13165   if (!LeftFold && RetainExpansion) {
13166     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13167 
13168     ExprResult Out = getDerived().TransformExpr(Pattern);
13169     if (Out.isInvalid())
13170       return true;
13171 
13172     Result = getDerived().RebuildCXXFoldExpr(
13173         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
13174         Result.get(), E->getEndLoc(), OrigNumExpansions);
13175     if (Result.isInvalid())
13176       return true;
13177   }
13178 
13179   for (unsigned I = 0; I != *NumExpansions; ++I) {
13180     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
13181         getSema(), LeftFold ? I : *NumExpansions - I - 1);
13182     ExprResult Out = getDerived().TransformExpr(Pattern);
13183     if (Out.isInvalid())
13184       return true;
13185 
13186     if (Out.get()->containsUnexpandedParameterPack()) {
13187       // We still have a pack; retain a pack expansion for this slice.
13188       Result = getDerived().RebuildCXXFoldExpr(
13189           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
13190           E->getOperator(), E->getEllipsisLoc(),
13191           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
13192           OrigNumExpansions);
13193     } else if (Result.isUsable()) {
13194       // We've got down to a single element; build a binary operator.
13195       Result = getDerived().RebuildBinaryOperator(
13196           E->getEllipsisLoc(), E->getOperator(),
13197           LeftFold ? Result.get() : Out.get(),
13198           LeftFold ? Out.get() : Result.get());
13199     } else
13200       Result = Out;
13201 
13202     if (Result.isInvalid())
13203       return true;
13204   }
13205 
13206   // If we're retaining an expansion for a left fold, it is the outermost
13207   // component and takes the complete expansion so far as its init (if any).
13208   if (LeftFold && RetainExpansion) {
13209     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13210 
13211     ExprResult Out = getDerived().TransformExpr(Pattern);
13212     if (Out.isInvalid())
13213       return true;
13214 
13215     Result = getDerived().RebuildCXXFoldExpr(
13216         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
13217         Out.get(), E->getEndLoc(), OrigNumExpansions);
13218     if (Result.isInvalid())
13219       return true;
13220   }
13221 
13222   // If we had no init and an empty pack, and we're not retaining an expansion,
13223   // then produce a fallback value or error.
13224   if (Result.isUnset())
13225     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
13226                                                 E->getOperator());
13227 
13228   return Result;
13229 }
13230 
13231 template<typename Derived>
13232 ExprResult
13233 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
13234     CXXStdInitializerListExpr *E) {
13235   return getDerived().TransformExpr(E->getSubExpr());
13236 }
13237 
13238 template<typename Derived>
13239 ExprResult
13240 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
13241   return SemaRef.MaybeBindToTemporary(E);
13242 }
13243 
13244 template<typename Derived>
13245 ExprResult
13246 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
13247   return E;
13248 }
13249 
13250 template<typename Derived>
13251 ExprResult
13252 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
13253   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
13254   if (SubExpr.isInvalid())
13255     return ExprError();
13256 
13257   if (!getDerived().AlwaysRebuild() &&
13258       SubExpr.get() == E->getSubExpr())
13259     return E;
13260 
13261   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
13262 }
13263 
13264 template<typename Derived>
13265 ExprResult
13266 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
13267   // Transform each of the elements.
13268   SmallVector<Expr *, 8> Elements;
13269   bool ArgChanged = false;
13270   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
13271                                   /*IsCall=*/false, Elements, &ArgChanged))
13272     return ExprError();
13273 
13274   if (!getDerived().AlwaysRebuild() && !ArgChanged)
13275     return SemaRef.MaybeBindToTemporary(E);
13276 
13277   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
13278                                               Elements.data(),
13279                                               Elements.size());
13280 }
13281 
13282 template<typename Derived>
13283 ExprResult
13284 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
13285                                                     ObjCDictionaryLiteral *E) {
13286   // Transform each of the elements.
13287   SmallVector<ObjCDictionaryElement, 8> Elements;
13288   bool ArgChanged = false;
13289   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
13290     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
13291 
13292     if (OrigElement.isPackExpansion()) {
13293       // This key/value element is a pack expansion.
13294       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13295       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
13296       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
13297       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13298 
13299       // Determine whether the set of unexpanded parameter packs can
13300       // and should be expanded.
13301       bool Expand = true;
13302       bool RetainExpansion = false;
13303       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
13304       Optional<unsigned> NumExpansions = OrigNumExpansions;
13305       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
13306                                OrigElement.Value->getEndLoc());
13307       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
13308                                                PatternRange, Unexpanded, Expand,
13309                                                RetainExpansion, NumExpansions))
13310         return ExprError();
13311 
13312       if (!Expand) {
13313         // The transform has determined that we should perform a simple
13314         // transformation on the pack expansion, producing another pack
13315         // expansion.
13316         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13317         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13318         if (Key.isInvalid())
13319           return ExprError();
13320 
13321         if (Key.get() != OrigElement.Key)
13322           ArgChanged = true;
13323 
13324         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13325         if (Value.isInvalid())
13326           return ExprError();
13327 
13328         if (Value.get() != OrigElement.Value)
13329           ArgChanged = true;
13330 
13331         ObjCDictionaryElement Expansion = {
13332           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
13333         };
13334         Elements.push_back(Expansion);
13335         continue;
13336       }
13337 
13338       // Record right away that the argument was changed.  This needs
13339       // to happen even if the array expands to nothing.
13340       ArgChanged = true;
13341 
13342       // The transform has determined that we should perform an elementwise
13343       // expansion of the pattern. Do so.
13344       for (unsigned I = 0; I != *NumExpansions; ++I) {
13345         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13346         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13347         if (Key.isInvalid())
13348           return ExprError();
13349 
13350         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13351         if (Value.isInvalid())
13352           return ExprError();
13353 
13354         ObjCDictionaryElement Element = {
13355           Key.get(), Value.get(), SourceLocation(), NumExpansions
13356         };
13357 
13358         // If any unexpanded parameter packs remain, we still have a
13359         // pack expansion.
13360         // FIXME: Can this really happen?
13361         if (Key.get()->containsUnexpandedParameterPack() ||
13362             Value.get()->containsUnexpandedParameterPack())
13363           Element.EllipsisLoc = OrigElement.EllipsisLoc;
13364 
13365         Elements.push_back(Element);
13366       }
13367 
13368       // FIXME: Retain a pack expansion if RetainExpansion is true.
13369 
13370       // We've finished with this pack expansion.
13371       continue;
13372     }
13373 
13374     // Transform and check key.
13375     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13376     if (Key.isInvalid())
13377       return ExprError();
13378 
13379     if (Key.get() != OrigElement.Key)
13380       ArgChanged = true;
13381 
13382     // Transform and check value.
13383     ExprResult Value
13384       = getDerived().TransformExpr(OrigElement.Value);
13385     if (Value.isInvalid())
13386       return ExprError();
13387 
13388     if (Value.get() != OrigElement.Value)
13389       ArgChanged = true;
13390 
13391     ObjCDictionaryElement Element = {
13392       Key.get(), Value.get(), SourceLocation(), None
13393     };
13394     Elements.push_back(Element);
13395   }
13396 
13397   if (!getDerived().AlwaysRebuild() && !ArgChanged)
13398     return SemaRef.MaybeBindToTemporary(E);
13399 
13400   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
13401                                                    Elements);
13402 }
13403 
13404 template<typename Derived>
13405 ExprResult
13406 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
13407   TypeSourceInfo *EncodedTypeInfo
13408     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
13409   if (!EncodedTypeInfo)
13410     return ExprError();
13411 
13412   if (!getDerived().AlwaysRebuild() &&
13413       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
13414     return E;
13415 
13416   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
13417                                             EncodedTypeInfo,
13418                                             E->getRParenLoc());
13419 }
13420 
13421 template<typename Derived>
13422 ExprResult TreeTransform<Derived>::
13423 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
13424   // This is a kind of implicit conversion, and it needs to get dropped
13425   // and recomputed for the same general reasons that ImplicitCastExprs
13426   // do, as well a more specific one: this expression is only valid when
13427   // it appears *immediately* as an argument expression.
13428   return getDerived().TransformExpr(E->getSubExpr());
13429 }
13430 
13431 template<typename Derived>
13432 ExprResult TreeTransform<Derived>::
13433 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
13434   TypeSourceInfo *TSInfo
13435     = getDerived().TransformType(E->getTypeInfoAsWritten());
13436   if (!TSInfo)
13437     return ExprError();
13438 
13439   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
13440   if (Result.isInvalid())
13441     return ExprError();
13442 
13443   if (!getDerived().AlwaysRebuild() &&
13444       TSInfo == E->getTypeInfoAsWritten() &&
13445       Result.get() == E->getSubExpr())
13446     return E;
13447 
13448   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
13449                                       E->getBridgeKeywordLoc(), TSInfo,
13450                                       Result.get());
13451 }
13452 
13453 template <typename Derived>
13454 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
13455     ObjCAvailabilityCheckExpr *E) {
13456   return E;
13457 }
13458 
13459 template<typename Derived>
13460 ExprResult
13461 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
13462   // Transform arguments.
13463   bool ArgChanged = false;
13464   SmallVector<Expr*, 8> Args;
13465   Args.reserve(E->getNumArgs());
13466   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
13467                                   &ArgChanged))
13468     return ExprError();
13469 
13470   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
13471     // Class message: transform the receiver type.
13472     TypeSourceInfo *ReceiverTypeInfo
13473       = getDerived().TransformType(E->getClassReceiverTypeInfo());
13474     if (!ReceiverTypeInfo)
13475       return ExprError();
13476 
13477     // If nothing changed, just retain the existing message send.
13478     if (!getDerived().AlwaysRebuild() &&
13479         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
13480       return SemaRef.MaybeBindToTemporary(E);
13481 
13482     // Build a new class message send.
13483     SmallVector<SourceLocation, 16> SelLocs;
13484     E->getSelectorLocs(SelLocs);
13485     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
13486                                                E->getSelector(),
13487                                                SelLocs,
13488                                                E->getMethodDecl(),
13489                                                E->getLeftLoc(),
13490                                                Args,
13491                                                E->getRightLoc());
13492   }
13493   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
13494            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13495     if (!E->getMethodDecl())
13496       return ExprError();
13497 
13498     // Build a new class message send to 'super'.
13499     SmallVector<SourceLocation, 16> SelLocs;
13500     E->getSelectorLocs(SelLocs);
13501     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
13502                                                E->getSelector(),
13503                                                SelLocs,
13504                                                E->getReceiverType(),
13505                                                E->getMethodDecl(),
13506                                                E->getLeftLoc(),
13507                                                Args,
13508                                                E->getRightLoc());
13509   }
13510 
13511   // Instance message: transform the receiver
13512   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
13513          "Only class and instance messages may be instantiated");
13514   ExprResult Receiver
13515     = getDerived().TransformExpr(E->getInstanceReceiver());
13516   if (Receiver.isInvalid())
13517     return ExprError();
13518 
13519   // If nothing changed, just retain the existing message send.
13520   if (!getDerived().AlwaysRebuild() &&
13521       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
13522     return SemaRef.MaybeBindToTemporary(E);
13523 
13524   // Build a new instance message send.
13525   SmallVector<SourceLocation, 16> SelLocs;
13526   E->getSelectorLocs(SelLocs);
13527   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
13528                                              E->getSelector(),
13529                                              SelLocs,
13530                                              E->getMethodDecl(),
13531                                              E->getLeftLoc(),
13532                                              Args,
13533                                              E->getRightLoc());
13534 }
13535 
13536 template<typename Derived>
13537 ExprResult
13538 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
13539   return E;
13540 }
13541 
13542 template<typename Derived>
13543 ExprResult
13544 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
13545   return E;
13546 }
13547 
13548 template<typename Derived>
13549 ExprResult
13550 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
13551   // Transform the base expression.
13552   ExprResult Base = getDerived().TransformExpr(E->getBase());
13553   if (Base.isInvalid())
13554     return ExprError();
13555 
13556   // We don't need to transform the ivar; it will never change.
13557 
13558   // If nothing changed, just retain the existing expression.
13559   if (!getDerived().AlwaysRebuild() &&
13560       Base.get() == E->getBase())
13561     return E;
13562 
13563   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
13564                                              E->getLocation(),
13565                                              E->isArrow(), E->isFreeIvar());
13566 }
13567 
13568 template<typename Derived>
13569 ExprResult
13570 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
13571   // 'super' and types never change. Property never changes. Just
13572   // retain the existing expression.
13573   if (!E->isObjectReceiver())
13574     return E;
13575 
13576   // Transform the base expression.
13577   ExprResult Base = getDerived().TransformExpr(E->getBase());
13578   if (Base.isInvalid())
13579     return ExprError();
13580 
13581   // We don't need to transform the property; it will never change.
13582 
13583   // If nothing changed, just retain the existing expression.
13584   if (!getDerived().AlwaysRebuild() &&
13585       Base.get() == E->getBase())
13586     return E;
13587 
13588   if (E->isExplicitProperty())
13589     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
13590                                                    E->getExplicitProperty(),
13591                                                    E->getLocation());
13592 
13593   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
13594                                                  SemaRef.Context.PseudoObjectTy,
13595                                                  E->getImplicitPropertyGetter(),
13596                                                  E->getImplicitPropertySetter(),
13597                                                  E->getLocation());
13598 }
13599 
13600 template<typename Derived>
13601 ExprResult
13602 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
13603   // Transform the base expression.
13604   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
13605   if (Base.isInvalid())
13606     return ExprError();
13607 
13608   // Transform the key expression.
13609   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
13610   if (Key.isInvalid())
13611     return ExprError();
13612 
13613   // If nothing changed, just retain the existing expression.
13614   if (!getDerived().AlwaysRebuild() &&
13615       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
13616     return E;
13617 
13618   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
13619                                                   Base.get(), Key.get(),
13620                                                   E->getAtIndexMethodDecl(),
13621                                                   E->setAtIndexMethodDecl());
13622 }
13623 
13624 template<typename Derived>
13625 ExprResult
13626 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
13627   // Transform the base expression.
13628   ExprResult Base = getDerived().TransformExpr(E->getBase());
13629   if (Base.isInvalid())
13630     return ExprError();
13631 
13632   // If nothing changed, just retain the existing expression.
13633   if (!getDerived().AlwaysRebuild() &&
13634       Base.get() == E->getBase())
13635     return E;
13636 
13637   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
13638                                          E->getOpLoc(),
13639                                          E->isArrow());
13640 }
13641 
13642 template<typename Derived>
13643 ExprResult
13644 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
13645   bool ArgumentChanged = false;
13646   SmallVector<Expr*, 8> SubExprs;
13647   SubExprs.reserve(E->getNumSubExprs());
13648   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
13649                                   SubExprs, &ArgumentChanged))
13650     return ExprError();
13651 
13652   if (!getDerived().AlwaysRebuild() &&
13653       !ArgumentChanged)
13654     return E;
13655 
13656   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
13657                                                SubExprs,
13658                                                E->getRParenLoc());
13659 }
13660 
13661 template<typename Derived>
13662 ExprResult
13663 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
13664   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
13665   if (SrcExpr.isInvalid())
13666     return ExprError();
13667 
13668   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
13669   if (!Type)
13670     return ExprError();
13671 
13672   if (!getDerived().AlwaysRebuild() &&
13673       Type == E->getTypeSourceInfo() &&
13674       SrcExpr.get() == E->getSrcExpr())
13675     return E;
13676 
13677   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
13678                                                SrcExpr.get(), Type,
13679                                                E->getRParenLoc());
13680 }
13681 
13682 template<typename Derived>
13683 ExprResult
13684 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
13685   BlockDecl *oldBlock = E->getBlockDecl();
13686 
13687   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
13688   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
13689 
13690   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
13691   blockScope->TheDecl->setBlockMissingReturnType(
13692                          oldBlock->blockMissingReturnType());
13693 
13694   SmallVector<ParmVarDecl*, 4> params;
13695   SmallVector<QualType, 4> paramTypes;
13696 
13697   const FunctionProtoType *exprFunctionType = E->getFunctionType();
13698 
13699   // Parameter substitution.
13700   Sema::ExtParameterInfoBuilder extParamInfos;
13701   if (getDerived().TransformFunctionTypeParams(
13702           E->getCaretLocation(), oldBlock->parameters(), nullptr,
13703           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
13704           extParamInfos)) {
13705     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
13706     return ExprError();
13707   }
13708 
13709   QualType exprResultType =
13710       getDerived().TransformType(exprFunctionType->getReturnType());
13711 
13712   auto epi = exprFunctionType->getExtProtoInfo();
13713   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
13714 
13715   QualType functionType =
13716     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
13717   blockScope->FunctionType = functionType;
13718 
13719   // Set the parameters on the block decl.
13720   if (!params.empty())
13721     blockScope->TheDecl->setParams(params);
13722 
13723   if (!oldBlock->blockMissingReturnType()) {
13724     blockScope->HasImplicitReturnType = false;
13725     blockScope->ReturnType = exprResultType;
13726   }
13727 
13728   // Transform the body
13729   StmtResult body = getDerived().TransformStmt(E->getBody());
13730   if (body.isInvalid()) {
13731     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
13732     return ExprError();
13733   }
13734 
13735 #ifndef NDEBUG
13736   // In builds with assertions, make sure that we captured everything we
13737   // captured before.
13738   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
13739     for (const auto &I : oldBlock->captures()) {
13740       VarDecl *oldCapture = I.getVariable();
13741 
13742       // Ignore parameter packs.
13743       if (oldCapture->isParameterPack())
13744         continue;
13745 
13746       VarDecl *newCapture =
13747         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
13748                                                  oldCapture));
13749       assert(blockScope->CaptureMap.count(newCapture));
13750     }
13751     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
13752   }
13753 #endif
13754 
13755   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
13756                                     /*Scope=*/nullptr);
13757 }
13758 
13759 template<typename Derived>
13760 ExprResult
13761 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
13762   llvm_unreachable("Cannot transform asType expressions yet");
13763 }
13764 
13765 template<typename Derived>
13766 ExprResult
13767 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
13768   bool ArgumentChanged = false;
13769   SmallVector<Expr*, 8> SubExprs;
13770   SubExprs.reserve(E->getNumSubExprs());
13771   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
13772                                   SubExprs, &ArgumentChanged))
13773     return ExprError();
13774 
13775   if (!getDerived().AlwaysRebuild() &&
13776       !ArgumentChanged)
13777     return E;
13778 
13779   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
13780                                         E->getOp(), E->getRParenLoc());
13781 }
13782 
13783 //===----------------------------------------------------------------------===//
13784 // Type reconstruction
13785 //===----------------------------------------------------------------------===//
13786 
13787 template<typename Derived>
13788 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
13789                                                     SourceLocation Star) {
13790   return SemaRef.BuildPointerType(PointeeType, Star,
13791                                   getDerived().getBaseEntity());
13792 }
13793 
13794 template<typename Derived>
13795 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
13796                                                          SourceLocation Star) {
13797   return SemaRef.BuildBlockPointerType(PointeeType, Star,
13798                                        getDerived().getBaseEntity());
13799 }
13800 
13801 template<typename Derived>
13802 QualType
13803 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
13804                                              bool WrittenAsLValue,
13805                                              SourceLocation Sigil) {
13806   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
13807                                     Sigil, getDerived().getBaseEntity());
13808 }
13809 
13810 template<typename Derived>
13811 QualType
13812 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
13813                                                  QualType ClassType,
13814                                                  SourceLocation Sigil) {
13815   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
13816                                         getDerived().getBaseEntity());
13817 }
13818 
13819 template<typename Derived>
13820 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
13821            const ObjCTypeParamDecl *Decl,
13822            SourceLocation ProtocolLAngleLoc,
13823            ArrayRef<ObjCProtocolDecl *> Protocols,
13824            ArrayRef<SourceLocation> ProtocolLocs,
13825            SourceLocation ProtocolRAngleLoc) {
13826   return SemaRef.BuildObjCTypeParamType(Decl,
13827                                         ProtocolLAngleLoc, Protocols,
13828                                         ProtocolLocs, ProtocolRAngleLoc,
13829                                         /*FailOnError=*/true);
13830 }
13831 
13832 template<typename Derived>
13833 QualType TreeTransform<Derived>::RebuildObjCObjectType(
13834            QualType BaseType,
13835            SourceLocation Loc,
13836            SourceLocation TypeArgsLAngleLoc,
13837            ArrayRef<TypeSourceInfo *> TypeArgs,
13838            SourceLocation TypeArgsRAngleLoc,
13839            SourceLocation ProtocolLAngleLoc,
13840            ArrayRef<ObjCProtocolDecl *> Protocols,
13841            ArrayRef<SourceLocation> ProtocolLocs,
13842            SourceLocation ProtocolRAngleLoc) {
13843   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
13844                                      TypeArgs, TypeArgsRAngleLoc,
13845                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
13846                                      ProtocolRAngleLoc,
13847                                      /*FailOnError=*/true);
13848 }
13849 
13850 template<typename Derived>
13851 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
13852            QualType PointeeType,
13853            SourceLocation Star) {
13854   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
13855 }
13856 
13857 template<typename Derived>
13858 QualType
13859 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
13860                                          ArrayType::ArraySizeModifier SizeMod,
13861                                          const llvm::APInt *Size,
13862                                          Expr *SizeExpr,
13863                                          unsigned IndexTypeQuals,
13864                                          SourceRange BracketsRange) {
13865   if (SizeExpr || !Size)
13866     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
13867                                   IndexTypeQuals, BracketsRange,
13868                                   getDerived().getBaseEntity());
13869 
13870   QualType Types[] = {
13871     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
13872     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
13873     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
13874   };
13875   const unsigned NumTypes = llvm::array_lengthof(Types);
13876   QualType SizeType;
13877   for (unsigned I = 0; I != NumTypes; ++I)
13878     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
13879       SizeType = Types[I];
13880       break;
13881     }
13882 
13883   // Note that we can return a VariableArrayType here in the case where
13884   // the element type was a dependent VariableArrayType.
13885   IntegerLiteral *ArraySize
13886       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
13887                                /*FIXME*/BracketsRange.getBegin());
13888   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
13889                                 IndexTypeQuals, BracketsRange,
13890                                 getDerived().getBaseEntity());
13891 }
13892 
13893 template<typename Derived>
13894 QualType
13895 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
13896                                                  ArrayType::ArraySizeModifier SizeMod,
13897                                                  const llvm::APInt &Size,
13898                                                  Expr *SizeExpr,
13899                                                  unsigned IndexTypeQuals,
13900                                                  SourceRange BracketsRange) {
13901   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
13902                                         IndexTypeQuals, BracketsRange);
13903 }
13904 
13905 template<typename Derived>
13906 QualType
13907 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
13908                                           ArrayType::ArraySizeModifier SizeMod,
13909                                                  unsigned IndexTypeQuals,
13910                                                    SourceRange BracketsRange) {
13911   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
13912                                        IndexTypeQuals, BracketsRange);
13913 }
13914 
13915 template<typename Derived>
13916 QualType
13917 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
13918                                           ArrayType::ArraySizeModifier SizeMod,
13919                                                  Expr *SizeExpr,
13920                                                  unsigned IndexTypeQuals,
13921                                                  SourceRange BracketsRange) {
13922   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
13923                                        SizeExpr,
13924                                        IndexTypeQuals, BracketsRange);
13925 }
13926 
13927 template<typename Derived>
13928 QualType
13929 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
13930                                           ArrayType::ArraySizeModifier SizeMod,
13931                                                        Expr *SizeExpr,
13932                                                        unsigned IndexTypeQuals,
13933                                                    SourceRange BracketsRange) {
13934   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
13935                                        SizeExpr,
13936                                        IndexTypeQuals, BracketsRange);
13937 }
13938 
13939 template <typename Derived>
13940 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
13941     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
13942   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
13943                                           AttributeLoc);
13944 }
13945 
13946 template <typename Derived>
13947 QualType
13948 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
13949                                           unsigned NumElements,
13950                                           VectorType::VectorKind VecKind) {
13951   // FIXME: semantic checking!
13952   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
13953 }
13954 
13955 template <typename Derived>
13956 QualType TreeTransform<Derived>::RebuildDependentVectorType(
13957     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
13958     VectorType::VectorKind VecKind) {
13959   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
13960 }
13961 
13962 template<typename Derived>
13963 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
13964                                                       unsigned NumElements,
13965                                                  SourceLocation AttributeLoc) {
13966   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
13967                           NumElements, true);
13968   IntegerLiteral *VectorSize
13969     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
13970                              AttributeLoc);
13971   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
13972 }
13973 
13974 template<typename Derived>
13975 QualType
13976 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
13977                                                            Expr *SizeExpr,
13978                                                   SourceLocation AttributeLoc) {
13979   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
13980 }
13981 
13982 template <typename Derived>
13983 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
13984     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
13985   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
13986                                                NumColumns);
13987 }
13988 
13989 template <typename Derived>
13990 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
13991     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
13992     SourceLocation AttributeLoc) {
13993   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
13994                                  AttributeLoc);
13995 }
13996 
13997 template<typename Derived>
13998 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
13999     QualType T,
14000     MutableArrayRef<QualType> ParamTypes,
14001     const FunctionProtoType::ExtProtoInfo &EPI) {
14002   return SemaRef.BuildFunctionType(T, ParamTypes,
14003                                    getDerived().getBaseLocation(),
14004                                    getDerived().getBaseEntity(),
14005                                    EPI);
14006 }
14007 
14008 template<typename Derived>
14009 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14010   return SemaRef.Context.getFunctionNoProtoType(T);
14011 }
14012 
14013 template<typename Derived>
14014 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14015                                                             Decl *D) {
14016   assert(D && "no decl found");
14017   if (D->isInvalidDecl()) return QualType();
14018 
14019   // FIXME: Doesn't account for ObjCInterfaceDecl!
14020   TypeDecl *Ty;
14021   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14022     // A valid resolved using typename pack expansion decl can have multiple
14023     // UsingDecls, but they must each have exactly one type, and it must be
14024     // the same type in every case. But we must have at least one expansion!
14025     if (UPD->expansions().empty()) {
14026       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14027           << UPD->isCXXClassMember() << UPD;
14028       return QualType();
14029     }
14030 
14031     // We might still have some unresolved types. Try to pick a resolved type
14032     // if we can. The final instantiation will check that the remaining
14033     // unresolved types instantiate to the type we pick.
14034     QualType FallbackT;
14035     QualType T;
14036     for (auto *E : UPD->expansions()) {
14037       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14038       if (ThisT.isNull())
14039         continue;
14040       else if (ThisT->getAs<UnresolvedUsingType>())
14041         FallbackT = ThisT;
14042       else if (T.isNull())
14043         T = ThisT;
14044       else
14045         assert(getSema().Context.hasSameType(ThisT, T) &&
14046                "mismatched resolved types in using pack expansion");
14047     }
14048     return T.isNull() ? FallbackT : T;
14049   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14050     assert(Using->hasTypename() &&
14051            "UnresolvedUsingTypenameDecl transformed to non-typename using");
14052 
14053     // A valid resolved using typename decl points to exactly one type decl.
14054     assert(++Using->shadow_begin() == Using->shadow_end());
14055     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
14056   } else {
14057     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
14058            "UnresolvedUsingTypenameDecl transformed to non-using decl");
14059     Ty = cast<UnresolvedUsingTypenameDecl>(D);
14060   }
14061 
14062   return SemaRef.Context.getTypeDeclType(Ty);
14063 }
14064 
14065 template<typename Derived>
14066 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
14067                                                        SourceLocation Loc) {
14068   return SemaRef.BuildTypeofExprType(E, Loc);
14069 }
14070 
14071 template<typename Derived>
14072 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
14073   return SemaRef.Context.getTypeOfType(Underlying);
14074 }
14075 
14076 template<typename Derived>
14077 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
14078                                                      SourceLocation Loc) {
14079   return SemaRef.BuildDecltypeType(E, Loc);
14080 }
14081 
14082 template<typename Derived>
14083 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
14084                                             UnaryTransformType::UTTKind UKind,
14085                                             SourceLocation Loc) {
14086   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
14087 }
14088 
14089 template<typename Derived>
14090 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
14091                                                       TemplateName Template,
14092                                              SourceLocation TemplateNameLoc,
14093                                      TemplateArgumentListInfo &TemplateArgs) {
14094   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
14095 }
14096 
14097 template<typename Derived>
14098 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
14099                                                    SourceLocation KWLoc) {
14100   return SemaRef.BuildAtomicType(ValueType, KWLoc);
14101 }
14102 
14103 template<typename Derived>
14104 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
14105                                                  SourceLocation KWLoc,
14106                                                  bool isReadPipe) {
14107   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
14108                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
14109 }
14110 
14111 template <typename Derived>
14112 QualType TreeTransform<Derived>::RebuildExtIntType(bool IsUnsigned,
14113                                                    unsigned NumBits,
14114                                                    SourceLocation Loc) {
14115   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14116                         NumBits, true);
14117   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
14118                                                 SemaRef.Context.IntTy, Loc);
14119   return SemaRef.BuildExtIntType(IsUnsigned, Bits, Loc);
14120 }
14121 
14122 template <typename Derived>
14123 QualType TreeTransform<Derived>::RebuildDependentExtIntType(
14124     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
14125   return SemaRef.BuildExtIntType(IsUnsigned, NumBitsExpr, Loc);
14126 }
14127 
14128 template<typename Derived>
14129 TemplateName
14130 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14131                                             bool TemplateKW,
14132                                             TemplateDecl *Template) {
14133   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
14134                                                   Template);
14135 }
14136 
14137 template<typename Derived>
14138 TemplateName
14139 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14140                                             SourceLocation TemplateKWLoc,
14141                                             const IdentifierInfo &Name,
14142                                             SourceLocation NameLoc,
14143                                             QualType ObjectType,
14144                                             NamedDecl *FirstQualifierInScope,
14145                                             bool AllowInjectedClassName) {
14146   UnqualifiedId TemplateName;
14147   TemplateName.setIdentifier(&Name, NameLoc);
14148   Sema::TemplateTy Template;
14149   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
14150                               TemplateName, ParsedType::make(ObjectType),
14151                               /*EnteringContext=*/false, Template,
14152                               AllowInjectedClassName);
14153   return Template.get();
14154 }
14155 
14156 template<typename Derived>
14157 TemplateName
14158 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14159                                             SourceLocation TemplateKWLoc,
14160                                             OverloadedOperatorKind Operator,
14161                                             SourceLocation NameLoc,
14162                                             QualType ObjectType,
14163                                             bool AllowInjectedClassName) {
14164   UnqualifiedId Name;
14165   // FIXME: Bogus location information.
14166   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
14167   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
14168   Sema::TemplateTy Template;
14169   getSema().ActOnTemplateName(
14170       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
14171       /*EnteringContext=*/false, Template, AllowInjectedClassName);
14172   return Template.get();
14173 }
14174 
14175 template<typename Derived>
14176 ExprResult
14177 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
14178                                                    SourceLocation OpLoc,
14179                                                    Expr *OrigCallee,
14180                                                    Expr *First,
14181                                                    Expr *Second) {
14182   Expr *Callee = OrigCallee->IgnoreParenCasts();
14183   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
14184 
14185   if (First->getObjectKind() == OK_ObjCProperty) {
14186     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14187     if (BinaryOperator::isAssignmentOp(Opc))
14188       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
14189                                                  First, Second);
14190     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
14191     if (Result.isInvalid())
14192       return ExprError();
14193     First = Result.get();
14194   }
14195 
14196   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
14197     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
14198     if (Result.isInvalid())
14199       return ExprError();
14200     Second = Result.get();
14201   }
14202 
14203   // Determine whether this should be a builtin operation.
14204   if (Op == OO_Subscript) {
14205     if (!First->getType()->isOverloadableType() &&
14206         !Second->getType()->isOverloadableType())
14207       return getSema().CreateBuiltinArraySubscriptExpr(
14208           First, Callee->getBeginLoc(), Second, OpLoc);
14209   } else if (Op == OO_Arrow) {
14210     // -> is never a builtin operation.
14211     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
14212   } else if (Second == nullptr || isPostIncDec) {
14213     if (!First->getType()->isOverloadableType() ||
14214         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
14215       // The argument is not of overloadable type, or this is an expression
14216       // of the form &Class::member, so try to create a built-in unary
14217       // operation.
14218       UnaryOperatorKind Opc
14219         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14220 
14221       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
14222     }
14223   } else {
14224     if (!First->getType()->isOverloadableType() &&
14225         !Second->getType()->isOverloadableType()) {
14226       // Neither of the arguments is an overloadable type, so try to
14227       // create a built-in binary operation.
14228       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14229       ExprResult Result
14230         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
14231       if (Result.isInvalid())
14232         return ExprError();
14233 
14234       return Result;
14235     }
14236   }
14237 
14238   // Compute the transformed set of functions (and function templates) to be
14239   // used during overload resolution.
14240   UnresolvedSet<16> Functions;
14241   bool RequiresADL;
14242 
14243   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
14244     Functions.append(ULE->decls_begin(), ULE->decls_end());
14245     // If the overload could not be resolved in the template definition
14246     // (because we had a dependent argument), ADL is performed as part of
14247     // template instantiation.
14248     RequiresADL = ULE->requiresADL();
14249   } else {
14250     // If we've resolved this to a particular non-member function, just call
14251     // that function. If we resolved it to a member function,
14252     // CreateOverloaded* will find that function for us.
14253     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
14254     if (!isa<CXXMethodDecl>(ND))
14255       Functions.addDecl(ND);
14256     RequiresADL = false;
14257   }
14258 
14259   // Add any functions found via argument-dependent lookup.
14260   Expr *Args[2] = { First, Second };
14261   unsigned NumArgs = 1 + (Second != nullptr);
14262 
14263   // Create the overloaded operator invocation for unary operators.
14264   if (NumArgs == 1 || isPostIncDec) {
14265     UnaryOperatorKind Opc
14266       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14267     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
14268                                            RequiresADL);
14269   }
14270 
14271   if (Op == OO_Subscript) {
14272     SourceLocation LBrace;
14273     SourceLocation RBrace;
14274 
14275     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
14276         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
14277         LBrace = SourceLocation::getFromRawEncoding(
14278                     NameLoc.CXXOperatorName.BeginOpNameLoc);
14279         RBrace = SourceLocation::getFromRawEncoding(
14280                     NameLoc.CXXOperatorName.EndOpNameLoc);
14281     } else {
14282       LBrace = Callee->getBeginLoc();
14283       RBrace = OpLoc;
14284     }
14285 
14286     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
14287                                                       First, Second);
14288   }
14289 
14290   // Create the overloaded operator invocation for binary operators.
14291   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14292   ExprResult Result = SemaRef.CreateOverloadedBinOp(
14293       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
14294   if (Result.isInvalid())
14295     return ExprError();
14296 
14297   return Result;
14298 }
14299 
14300 template<typename Derived>
14301 ExprResult
14302 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
14303                                                      SourceLocation OperatorLoc,
14304                                                        bool isArrow,
14305                                                        CXXScopeSpec &SS,
14306                                                      TypeSourceInfo *ScopeType,
14307                                                        SourceLocation CCLoc,
14308                                                        SourceLocation TildeLoc,
14309                                         PseudoDestructorTypeStorage Destroyed) {
14310   QualType BaseType = Base->getType();
14311   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
14312       (!isArrow && !BaseType->getAs<RecordType>()) ||
14313       (isArrow && BaseType->getAs<PointerType>() &&
14314        !BaseType->castAs<PointerType>()->getPointeeType()
14315                                               ->template getAs<RecordType>())){
14316     // This pseudo-destructor expression is still a pseudo-destructor.
14317     return SemaRef.BuildPseudoDestructorExpr(
14318         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
14319         CCLoc, TildeLoc, Destroyed);
14320   }
14321 
14322   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
14323   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
14324                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
14325   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
14326   NameInfo.setNamedTypeInfo(DestroyedType);
14327 
14328   // The scope type is now known to be a valid nested name specifier
14329   // component. Tack it on to the end of the nested name specifier.
14330   if (ScopeType) {
14331     if (!ScopeType->getType()->getAs<TagType>()) {
14332       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
14333                      diag::err_expected_class_or_namespace)
14334           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
14335       return ExprError();
14336     }
14337     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
14338               CCLoc);
14339   }
14340 
14341   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
14342   return getSema().BuildMemberReferenceExpr(Base, BaseType,
14343                                             OperatorLoc, isArrow,
14344                                             SS, TemplateKWLoc,
14345                                             /*FIXME: FirstQualifier*/ nullptr,
14346                                             NameInfo,
14347                                             /*TemplateArgs*/ nullptr,
14348                                             /*S*/nullptr);
14349 }
14350 
14351 template<typename Derived>
14352 StmtResult
14353 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
14354   SourceLocation Loc = S->getBeginLoc();
14355   CapturedDecl *CD = S->getCapturedDecl();
14356   unsigned NumParams = CD->getNumParams();
14357   unsigned ContextParamPos = CD->getContextParamPosition();
14358   SmallVector<Sema::CapturedParamNameType, 4> Params;
14359   for (unsigned I = 0; I < NumParams; ++I) {
14360     if (I != ContextParamPos) {
14361       Params.push_back(
14362              std::make_pair(
14363                   CD->getParam(I)->getName(),
14364                   getDerived().TransformType(CD->getParam(I)->getType())));
14365     } else {
14366       Params.push_back(std::make_pair(StringRef(), QualType()));
14367     }
14368   }
14369   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
14370                                      S->getCapturedRegionKind(), Params);
14371   StmtResult Body;
14372   {
14373     Sema::CompoundScopeRAII CompoundScope(getSema());
14374     Body = getDerived().TransformStmt(S->getCapturedStmt());
14375   }
14376 
14377   if (Body.isInvalid()) {
14378     getSema().ActOnCapturedRegionError();
14379     return StmtError();
14380   }
14381 
14382   return getSema().ActOnCapturedRegionEnd(Body.get());
14383 }
14384 
14385 } // end namespace clang
14386 
14387 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14388