xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision ec0ea6efa1ad229d75c394c1a9b9cac33af2b1d3)
1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
7 //
8 //  This file implements a semantic tree transformation that takes a given
9 //  AST and rebuilds it, possibly transforming some nodes in the process.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15 
16 #include "CoroutineStmtBuilder.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprConcepts.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/OpenMPClause.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/StmtOpenMP.h"
31 #include "clang/Basic/DiagnosticParse.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Sema/Designator.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/Ownership.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaDiagnostic.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include <algorithm>
43 
44 using namespace llvm::omp;
45 
46 namespace clang {
47 using namespace sema;
48 
49 /// A semantic tree transformation that allows one to transform one
50 /// abstract syntax tree into another.
51 ///
52 /// A new tree transformation is defined by creating a new subclass \c X of
53 /// \c TreeTransform<X> and then overriding certain operations to provide
54 /// behavior specific to that transformation. For example, template
55 /// instantiation is implemented as a tree transformation where the
56 /// transformation of TemplateTypeParmType nodes involves substituting the
57 /// template arguments for their corresponding template parameters; a similar
58 /// transformation is performed for non-type template parameters and
59 /// template template parameters.
60 ///
61 /// This tree-transformation template uses static polymorphism to allow
62 /// subclasses to customize any of its operations. Thus, a subclass can
63 /// override any of the transformation or rebuild operators by providing an
64 /// operation with the same signature as the default implementation. The
65 /// overriding function should not be virtual.
66 ///
67 /// Semantic tree transformations are split into two stages, either of which
68 /// can be replaced by a subclass. The "transform" step transforms an AST node
69 /// or the parts of an AST node using the various transformation functions,
70 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
71 /// node of the appropriate kind from the pieces. The default transformation
72 /// routines recursively transform the operands to composite AST nodes (e.g.,
73 /// the pointee type of a PointerType node) and, if any of those operand nodes
74 /// were changed by the transformation, invokes the rebuild operation to create
75 /// a new AST node.
76 ///
77 /// Subclasses can customize the transformation at various levels. The
78 /// most coarse-grained transformations involve replacing TransformType(),
79 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
80 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
81 /// new implementations.
82 ///
83 /// For more fine-grained transformations, subclasses can replace any of the
84 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
85 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
86 /// replacing TransformTemplateTypeParmType() allows template instantiation
87 /// to substitute template arguments for their corresponding template
88 /// parameters. Additionally, subclasses can override the \c RebuildXXX
89 /// functions to control how AST nodes are rebuilt when their operands change.
90 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
91 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
92 /// be able to use more efficient rebuild steps.
93 ///
94 /// There are a handful of other functions that can be overridden, allowing one
95 /// to avoid traversing nodes that don't need any transformation
96 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
97 /// operands have not changed (\c AlwaysRebuild()), and customize the
98 /// default locations and entity names used for type-checking
99 /// (\c getBaseLocation(), \c getBaseEntity()).
100 template<typename Derived>
101 class TreeTransform {
102   /// Private RAII object that helps us forget and then re-remember
103   /// the template argument corresponding to a partially-substituted parameter
104   /// pack.
105   class ForgetPartiallySubstitutedPackRAII {
106     Derived &Self;
107     TemplateArgument Old;
108 
109   public:
110     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
111       Old = Self.ForgetPartiallySubstitutedPack();
112     }
113 
114     ~ForgetPartiallySubstitutedPackRAII() {
115       Self.RememberPartiallySubstitutedPack(Old);
116     }
117   };
118 
119 protected:
120   Sema &SemaRef;
121 
122   /// The set of local declarations that have been transformed, for
123   /// cases where we are forced to build new declarations within the transformer
124   /// rather than in the subclass (e.g., lambda closure types).
125   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
126 
127 public:
128   /// Initializes a new tree transformer.
129   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
130 
131   /// Retrieves a reference to the derived class.
132   Derived &getDerived() { return static_cast<Derived&>(*this); }
133 
134   /// Retrieves a reference to the derived class.
135   const Derived &getDerived() const {
136     return static_cast<const Derived&>(*this);
137   }
138 
139   static inline ExprResult Owned(Expr *E) { return E; }
140   static inline StmtResult Owned(Stmt *S) { return S; }
141 
142   /// Retrieves a reference to the semantic analysis object used for
143   /// this tree transform.
144   Sema &getSema() const { return SemaRef; }
145 
146   /// Whether the transformation should always rebuild AST nodes, even
147   /// if none of the children have changed.
148   ///
149   /// Subclasses may override this function to specify when the transformation
150   /// should rebuild all AST nodes.
151   ///
152   /// We must always rebuild all AST nodes when performing variadic template
153   /// pack expansion, in order to avoid violating the AST invariant that each
154   /// statement node appears at most once in its containing declaration.
155   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
156 
157   /// Whether the transformation is forming an expression or statement that
158   /// replaces the original. In this case, we'll reuse mangling numbers from
159   /// existing lambdas.
160   bool ReplacingOriginal() { return false; }
161 
162   /// Wether CXXConstructExpr can be skipped when they are implicit.
163   /// They will be reconstructed when used if needed.
164   /// This is usefull when the user that cause rebuilding of the
165   /// CXXConstructExpr is outside of the expression at which the TreeTransform
166   /// started.
167   bool AllowSkippingCXXConstructExpr() { return true; }
168 
169   /// Returns the location of the entity being transformed, if that
170   /// information was not available elsewhere in the AST.
171   ///
172   /// By default, returns no source-location information. Subclasses can
173   /// provide an alternative implementation that provides better location
174   /// information.
175   SourceLocation getBaseLocation() { return SourceLocation(); }
176 
177   /// Returns the name of the entity being transformed, if that
178   /// information was not available elsewhere in the AST.
179   ///
180   /// By default, returns an empty name. Subclasses can provide an alternative
181   /// implementation with a more precise name.
182   DeclarationName getBaseEntity() { return DeclarationName(); }
183 
184   /// Sets the "base" location and entity when that
185   /// information is known based on another transformation.
186   ///
187   /// By default, the source location and entity are ignored. Subclasses can
188   /// override this function to provide a customized implementation.
189   void setBase(SourceLocation Loc, DeclarationName Entity) { }
190 
191   /// RAII object that temporarily sets the base location and entity
192   /// used for reporting diagnostics in types.
193   class TemporaryBase {
194     TreeTransform &Self;
195     SourceLocation OldLocation;
196     DeclarationName OldEntity;
197 
198   public:
199     TemporaryBase(TreeTransform &Self, SourceLocation Location,
200                   DeclarationName Entity) : Self(Self) {
201       OldLocation = Self.getDerived().getBaseLocation();
202       OldEntity = Self.getDerived().getBaseEntity();
203 
204       if (Location.isValid())
205         Self.getDerived().setBase(Location, Entity);
206     }
207 
208     ~TemporaryBase() {
209       Self.getDerived().setBase(OldLocation, OldEntity);
210     }
211   };
212 
213   /// Determine whether the given type \p T has already been
214   /// transformed.
215   ///
216   /// Subclasses can provide an alternative implementation of this routine
217   /// to short-circuit evaluation when it is known that a given type will
218   /// not change. For example, template instantiation need not traverse
219   /// non-dependent types.
220   bool AlreadyTransformed(QualType T) {
221     return T.isNull();
222   }
223 
224   /// Transform a template parameter depth level.
225   ///
226   /// During a transformation that transforms template parameters, this maps
227   /// an old template parameter depth to a new depth.
228   unsigned TransformTemplateDepth(unsigned Depth) {
229     return Depth;
230   }
231 
232   /// Determine whether the given call argument should be dropped, e.g.,
233   /// because it is a default argument.
234   ///
235   /// Subclasses can provide an alternative implementation of this routine to
236   /// determine which kinds of call arguments get dropped. By default,
237   /// CXXDefaultArgument nodes are dropped (prior to transformation).
238   bool DropCallArgument(Expr *E) {
239     return E->isDefaultArgument();
240   }
241 
242   /// Determine whether we should expand a pack expansion with the
243   /// given set of parameter packs into separate arguments by repeatedly
244   /// transforming the pattern.
245   ///
246   /// By default, the transformer never tries to expand pack expansions.
247   /// Subclasses can override this routine to provide different behavior.
248   ///
249   /// \param EllipsisLoc The location of the ellipsis that identifies the
250   /// pack expansion.
251   ///
252   /// \param PatternRange The source range that covers the entire pattern of
253   /// the pack expansion.
254   ///
255   /// \param Unexpanded The set of unexpanded parameter packs within the
256   /// pattern.
257   ///
258   /// \param ShouldExpand Will be set to \c true if the transformer should
259   /// expand the corresponding pack expansions into separate arguments. When
260   /// set, \c NumExpansions must also be set.
261   ///
262   /// \param RetainExpansion Whether the caller should add an unexpanded
263   /// pack expansion after all of the expanded arguments. This is used
264   /// when extending explicitly-specified template argument packs per
265   /// C++0x [temp.arg.explicit]p9.
266   ///
267   /// \param NumExpansions The number of separate arguments that will be in
268   /// the expanded form of the corresponding pack expansion. This is both an
269   /// input and an output parameter, which can be set by the caller if the
270   /// number of expansions is known a priori (e.g., due to a prior substitution)
271   /// and will be set by the callee when the number of expansions is known.
272   /// The callee must set this value when \c ShouldExpand is \c true; it may
273   /// set this value in other cases.
274   ///
275   /// \returns true if an error occurred (e.g., because the parameter packs
276   /// are to be instantiated with arguments of different lengths), false
277   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
278   /// must be set.
279   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
280                                SourceRange PatternRange,
281                                ArrayRef<UnexpandedParameterPack> Unexpanded,
282                                bool &ShouldExpand,
283                                bool &RetainExpansion,
284                                Optional<unsigned> &NumExpansions) {
285     ShouldExpand = false;
286     return false;
287   }
288 
289   /// "Forget" about the partially-substituted pack template argument,
290   /// when performing an instantiation that must preserve the parameter pack
291   /// use.
292   ///
293   /// This routine is meant to be overridden by the template instantiator.
294   TemplateArgument ForgetPartiallySubstitutedPack() {
295     return TemplateArgument();
296   }
297 
298   /// "Remember" the partially-substituted pack template argument
299   /// after performing an instantiation that must preserve the parameter pack
300   /// use.
301   ///
302   /// This routine is meant to be overridden by the template instantiator.
303   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304 
305   /// Note to the derived class when a function parameter pack is
306   /// being expanded.
307   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308 
309   /// Transforms the given type into another type.
310   ///
311   /// By default, this routine transforms a type by creating a
312   /// TypeSourceInfo for it and delegating to the appropriate
313   /// function.  This is expensive, but we don't mind, because
314   /// this method is deprecated anyway;  all users should be
315   /// switched to storing TypeSourceInfos.
316   ///
317   /// \returns the transformed type.
318   QualType TransformType(QualType T);
319 
320   /// Transforms the given type-with-location into a new
321   /// type-with-location.
322   ///
323   /// By default, this routine transforms a type by delegating to the
324   /// appropriate TransformXXXType to build a new type.  Subclasses
325   /// may override this function (to take over all type
326   /// transformations) or some set of the TransformXXXType functions
327   /// to alter the transformation.
328   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329 
330   /// Transform the given type-with-location into a new
331   /// type, collecting location information in the given builder
332   /// as necessary.
333   ///
334   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335 
336   /// Transform a type that is permitted to produce a
337   /// DeducedTemplateSpecializationType.
338   ///
339   /// This is used in the (relatively rare) contexts where it is acceptable
340   /// for transformation to produce a class template type with deduced
341   /// template arguments.
342   /// @{
343   QualType TransformTypeWithDeducedTST(QualType T);
344   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345   /// @}
346 
347   /// The reason why the value of a statement is not discarded, if any.
348   enum StmtDiscardKind {
349     SDK_Discarded,
350     SDK_NotDiscarded,
351     SDK_StmtExprResult,
352   };
353 
354   /// Transform the given statement.
355   ///
356   /// By default, this routine transforms a statement by delegating to the
357   /// appropriate TransformXXXStmt function to transform a specific kind of
358   /// statement or the TransformExpr() function to transform an expression.
359   /// Subclasses may override this function to transform statements using some
360   /// other mechanism.
361   ///
362   /// \returns the transformed statement.
363   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364 
365   /// Transform the given statement.
366   ///
367   /// By default, this routine transforms a statement by delegating to the
368   /// appropriate TransformOMPXXXClause function to transform a specific kind
369   /// of clause. Subclasses may override this function to transform statements
370   /// using some other mechanism.
371   ///
372   /// \returns the transformed OpenMP clause.
373   OMPClause *TransformOMPClause(OMPClause *S);
374 
375   /// Transform the given attribute.
376   ///
377   /// By default, this routine transforms a statement by delegating to the
378   /// appropriate TransformXXXAttr function to transform a specific kind
379   /// of attribute. Subclasses may override this function to transform
380   /// attributed statements using some other mechanism.
381   ///
382   /// \returns the transformed attribute
383   const Attr *TransformAttr(const Attr *S);
384 
385 /// Transform the specified attribute.
386 ///
387 /// Subclasses should override the transformation of attributes with a pragma
388 /// spelling to transform expressions stored within the attribute.
389 ///
390 /// \returns the transformed attribute.
391 #define ATTR(X)
392 #define PRAGMA_SPELLING_ATTR(X)                                                \
393   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
394 #include "clang/Basic/AttrList.inc"
395 
396   /// Transform the given expression.
397   ///
398   /// By default, this routine transforms an expression by delegating to the
399   /// appropriate TransformXXXExpr function to build a new expression.
400   /// Subclasses may override this function to transform expressions using some
401   /// other mechanism.
402   ///
403   /// \returns the transformed expression.
404   ExprResult TransformExpr(Expr *E);
405 
406   /// Transform the given initializer.
407   ///
408   /// By default, this routine transforms an initializer by stripping off the
409   /// semantic nodes added by initialization, then passing the result to
410   /// TransformExpr or TransformExprs.
411   ///
412   /// \returns the transformed initializer.
413   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
414 
415   /// Transform the given list of expressions.
416   ///
417   /// This routine transforms a list of expressions by invoking
418   /// \c TransformExpr() for each subexpression. However, it also provides
419   /// support for variadic templates by expanding any pack expansions (if the
420   /// derived class permits such expansion) along the way. When pack expansions
421   /// are present, the number of outputs may not equal the number of inputs.
422   ///
423   /// \param Inputs The set of expressions to be transformed.
424   ///
425   /// \param NumInputs The number of expressions in \c Inputs.
426   ///
427   /// \param IsCall If \c true, then this transform is being performed on
428   /// function-call arguments, and any arguments that should be dropped, will
429   /// be.
430   ///
431   /// \param Outputs The transformed input expressions will be added to this
432   /// vector.
433   ///
434   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
435   /// due to transformation.
436   ///
437   /// \returns true if an error occurred, false otherwise.
438   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
439                       SmallVectorImpl<Expr *> &Outputs,
440                       bool *ArgChanged = nullptr);
441 
442   /// Transform the given declaration, which is referenced from a type
443   /// or expression.
444   ///
445   /// By default, acts as the identity function on declarations, unless the
446   /// transformer has had to transform the declaration itself. Subclasses
447   /// may override this function to provide alternate behavior.
448   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
449     llvm::DenseMap<Decl *, Decl *>::iterator Known
450       = TransformedLocalDecls.find(D);
451     if (Known != TransformedLocalDecls.end())
452       return Known->second;
453 
454     return D;
455   }
456 
457   /// Transform the specified condition.
458   ///
459   /// By default, this transforms the variable and expression and rebuilds
460   /// the condition.
461   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
462                                            Expr *Expr,
463                                            Sema::ConditionKind Kind);
464 
465   /// Transform the attributes associated with the given declaration and
466   /// place them on the new declaration.
467   ///
468   /// By default, this operation does nothing. Subclasses may override this
469   /// behavior to transform attributes.
470   void transformAttrs(Decl *Old, Decl *New) { }
471 
472   /// Note that a local declaration has been transformed by this
473   /// transformer.
474   ///
475   /// Local declarations are typically transformed via a call to
476   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
477   /// the transformer itself has to transform the declarations. This routine
478   /// can be overridden by a subclass that keeps track of such mappings.
479   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
480     assert(New.size() == 1 &&
481            "must override transformedLocalDecl if performing pack expansion");
482     TransformedLocalDecls[Old] = New.front();
483   }
484 
485   /// Transform the definition of the given declaration.
486   ///
487   /// By default, invokes TransformDecl() to transform the declaration.
488   /// Subclasses may override this function to provide alternate behavior.
489   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
490     return getDerived().TransformDecl(Loc, D);
491   }
492 
493   /// Transform the given declaration, which was the first part of a
494   /// nested-name-specifier in a member access expression.
495   ///
496   /// This specific declaration transformation only applies to the first
497   /// identifier in a nested-name-specifier of a member access expression, e.g.,
498   /// the \c T in \c x->T::member
499   ///
500   /// By default, invokes TransformDecl() to transform the declaration.
501   /// Subclasses may override this function to provide alternate behavior.
502   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
503     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
504   }
505 
506   /// Transform the set of declarations in an OverloadExpr.
507   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
508                                   LookupResult &R);
509 
510   /// Transform the given nested-name-specifier with source-location
511   /// information.
512   ///
513   /// By default, transforms all of the types and declarations within the
514   /// nested-name-specifier. Subclasses may override this function to provide
515   /// alternate behavior.
516   NestedNameSpecifierLoc
517   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
518                                   QualType ObjectType = QualType(),
519                                   NamedDecl *FirstQualifierInScope = nullptr);
520 
521   /// Transform the given declaration name.
522   ///
523   /// By default, transforms the types of conversion function, constructor,
524   /// and destructor names and then (if needed) rebuilds the declaration name.
525   /// Identifiers and selectors are returned unmodified. Sublcasses may
526   /// override this function to provide alternate behavior.
527   DeclarationNameInfo
528   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
529 
530   bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
531       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
532   concepts::TypeRequirement *
533   TransformTypeRequirement(concepts::TypeRequirement *Req);
534   concepts::ExprRequirement *
535   TransformExprRequirement(concepts::ExprRequirement *Req);
536   concepts::NestedRequirement *
537   TransformNestedRequirement(concepts::NestedRequirement *Req);
538 
539   /// Transform the given template name.
540   ///
541   /// \param SS The nested-name-specifier that qualifies the template
542   /// name. This nested-name-specifier must already have been transformed.
543   ///
544   /// \param Name The template name to transform.
545   ///
546   /// \param NameLoc The source location of the template name.
547   ///
548   /// \param ObjectType If we're translating a template name within a member
549   /// access expression, this is the type of the object whose member template
550   /// is being referenced.
551   ///
552   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
553   /// also refers to a name within the current (lexical) scope, this is the
554   /// declaration it refers to.
555   ///
556   /// By default, transforms the template name by transforming the declarations
557   /// and nested-name-specifiers that occur within the template name.
558   /// Subclasses may override this function to provide alternate behavior.
559   TemplateName
560   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
561                         SourceLocation NameLoc,
562                         QualType ObjectType = QualType(),
563                         NamedDecl *FirstQualifierInScope = nullptr,
564                         bool AllowInjectedClassName = false);
565 
566   /// Transform the given template argument.
567   ///
568   /// By default, this operation transforms the type, expression, or
569   /// declaration stored within the template argument and constructs a
570   /// new template argument from the transformed result. Subclasses may
571   /// override this function to provide alternate behavior.
572   ///
573   /// Returns true if there was an error.
574   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
575                                  TemplateArgumentLoc &Output,
576                                  bool Uneval = false);
577 
578   /// Transform the given set of template arguments.
579   ///
580   /// By default, this operation transforms all of the template arguments
581   /// in the input set using \c TransformTemplateArgument(), and appends
582   /// the transformed arguments to the output list.
583   ///
584   /// Note that this overload of \c TransformTemplateArguments() is merely
585   /// a convenience function. Subclasses that wish to override this behavior
586   /// should override the iterator-based member template version.
587   ///
588   /// \param Inputs The set of template arguments to be transformed.
589   ///
590   /// \param NumInputs The number of template arguments in \p Inputs.
591   ///
592   /// \param Outputs The set of transformed template arguments output by this
593   /// routine.
594   ///
595   /// Returns true if an error occurred.
596   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
597                                   unsigned NumInputs,
598                                   TemplateArgumentListInfo &Outputs,
599                                   bool Uneval = false) {
600     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
601                                       Uneval);
602   }
603 
604   /// Transform the given set of template arguments.
605   ///
606   /// By default, this operation transforms all of the template arguments
607   /// in the input set using \c TransformTemplateArgument(), and appends
608   /// the transformed arguments to the output list.
609   ///
610   /// \param First An iterator to the first template argument.
611   ///
612   /// \param Last An iterator one step past the last template argument.
613   ///
614   /// \param Outputs The set of transformed template arguments output by this
615   /// routine.
616   ///
617   /// Returns true if an error occurred.
618   template<typename InputIterator>
619   bool TransformTemplateArguments(InputIterator First,
620                                   InputIterator Last,
621                                   TemplateArgumentListInfo &Outputs,
622                                   bool Uneval = false);
623 
624   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
625   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
626                                  TemplateArgumentLoc &ArgLoc);
627 
628   /// Fakes up a TypeSourceInfo for a type.
629   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
630     return SemaRef.Context.getTrivialTypeSourceInfo(T,
631                        getDerived().getBaseLocation());
632   }
633 
634 #define ABSTRACT_TYPELOC(CLASS, PARENT)
635 #define TYPELOC(CLASS, PARENT)                                   \
636   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
637 #include "clang/AST/TypeLocNodes.def"
638 
639   template<typename Fn>
640   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
641                                       FunctionProtoTypeLoc TL,
642                                       CXXRecordDecl *ThisContext,
643                                       Qualifiers ThisTypeQuals,
644                                       Fn TransformExceptionSpec);
645 
646   bool TransformExceptionSpec(SourceLocation Loc,
647                               FunctionProtoType::ExceptionSpecInfo &ESI,
648                               SmallVectorImpl<QualType> &Exceptions,
649                               bool &Changed);
650 
651   StmtResult TransformSEHHandler(Stmt *Handler);
652 
653   QualType
654   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
655                                       TemplateSpecializationTypeLoc TL,
656                                       TemplateName Template);
657 
658   QualType
659   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
660                                       DependentTemplateSpecializationTypeLoc TL,
661                                                TemplateName Template,
662                                                CXXScopeSpec &SS);
663 
664   QualType TransformDependentTemplateSpecializationType(
665       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
666       NestedNameSpecifierLoc QualifierLoc);
667 
668   /// Transforms the parameters of a function type into the
669   /// given vectors.
670   ///
671   /// The result vectors should be kept in sync; null entries in the
672   /// variables vector are acceptable.
673   ///
674   /// Return true on error.
675   bool TransformFunctionTypeParams(
676       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
677       const QualType *ParamTypes,
678       const FunctionProtoType::ExtParameterInfo *ParamInfos,
679       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
680       Sema::ExtParameterInfoBuilder &PInfos);
681 
682   /// Transforms a single function-type parameter.  Return null
683   /// on error.
684   ///
685   /// \param indexAdjustment - A number to add to the parameter's
686   ///   scope index;  can be negative
687   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
688                                           int indexAdjustment,
689                                           Optional<unsigned> NumExpansions,
690                                           bool ExpectParameterPack);
691 
692   /// Transform the body of a lambda-expression.
693   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
694   /// Alternative implementation of TransformLambdaBody that skips transforming
695   /// the body.
696   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
697 
698   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
699 
700   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
701   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
702 
703   TemplateParameterList *TransformTemplateParameterList(
704         TemplateParameterList *TPL) {
705     return TPL;
706   }
707 
708   ExprResult TransformAddressOfOperand(Expr *E);
709 
710   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
711                                                 bool IsAddressOfOperand,
712                                                 TypeSourceInfo **RecoveryTSI);
713 
714   ExprResult TransformParenDependentScopeDeclRefExpr(
715       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
716       TypeSourceInfo **RecoveryTSI);
717 
718   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
719 
720 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
721 // amount of stack usage with clang.
722 #define STMT(Node, Parent)                        \
723   LLVM_ATTRIBUTE_NOINLINE \
724   StmtResult Transform##Node(Node *S);
725 #define VALUESTMT(Node, Parent)                   \
726   LLVM_ATTRIBUTE_NOINLINE \
727   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
728 #define EXPR(Node, Parent)                        \
729   LLVM_ATTRIBUTE_NOINLINE \
730   ExprResult Transform##Node(Node *E);
731 #define ABSTRACT_STMT(Stmt)
732 #include "clang/AST/StmtNodes.inc"
733 
734 #define GEN_CLANG_CLAUSE_CLASS
735 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
736   LLVM_ATTRIBUTE_NOINLINE                                                      \
737   OMPClause *Transform##Class(Class *S);
738 #include "llvm/Frontend/OpenMP/OMP.inc"
739 
740   /// Build a new qualified type given its unqualified type and type location.
741   ///
742   /// By default, this routine adds type qualifiers only to types that can
743   /// have qualifiers, and silently suppresses those qualifiers that are not
744   /// permitted. Subclasses may override this routine to provide different
745   /// behavior.
746   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
747 
748   /// Build a new pointer type given its pointee type.
749   ///
750   /// By default, performs semantic analysis when building the pointer type.
751   /// Subclasses may override this routine to provide different behavior.
752   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
753 
754   /// Build a new block pointer type given its pointee type.
755   ///
756   /// By default, performs semantic analysis when building the block pointer
757   /// type. Subclasses may override this routine to provide different behavior.
758   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
759 
760   /// Build a new reference type given the type it references.
761   ///
762   /// By default, performs semantic analysis when building the
763   /// reference type. Subclasses may override this routine to provide
764   /// different behavior.
765   ///
766   /// \param LValue whether the type was written with an lvalue sigil
767   /// or an rvalue sigil.
768   QualType RebuildReferenceType(QualType ReferentType,
769                                 bool LValue,
770                                 SourceLocation Sigil);
771 
772   /// Build a new member pointer type given the pointee type and the
773   /// class type it refers into.
774   ///
775   /// By default, performs semantic analysis when building the member pointer
776   /// type. Subclasses may override this routine to provide different behavior.
777   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
778                                     SourceLocation Sigil);
779 
780   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
781                                     SourceLocation ProtocolLAngleLoc,
782                                     ArrayRef<ObjCProtocolDecl *> Protocols,
783                                     ArrayRef<SourceLocation> ProtocolLocs,
784                                     SourceLocation ProtocolRAngleLoc);
785 
786   /// Build an Objective-C object type.
787   ///
788   /// By default, performs semantic analysis when building the object type.
789   /// Subclasses may override this routine to provide different behavior.
790   QualType RebuildObjCObjectType(QualType BaseType,
791                                  SourceLocation Loc,
792                                  SourceLocation TypeArgsLAngleLoc,
793                                  ArrayRef<TypeSourceInfo *> TypeArgs,
794                                  SourceLocation TypeArgsRAngleLoc,
795                                  SourceLocation ProtocolLAngleLoc,
796                                  ArrayRef<ObjCProtocolDecl *> Protocols,
797                                  ArrayRef<SourceLocation> ProtocolLocs,
798                                  SourceLocation ProtocolRAngleLoc);
799 
800   /// Build a new Objective-C object pointer type given the pointee type.
801   ///
802   /// By default, directly builds the pointer type, with no additional semantic
803   /// analysis.
804   QualType RebuildObjCObjectPointerType(QualType PointeeType,
805                                         SourceLocation Star);
806 
807   /// Build a new array type given the element type, size
808   /// modifier, size of the array (if known), size expression, and index type
809   /// qualifiers.
810   ///
811   /// By default, performs semantic analysis when building the array type.
812   /// Subclasses may override this routine to provide different behavior.
813   /// Also by default, all of the other Rebuild*Array
814   QualType RebuildArrayType(QualType ElementType,
815                             ArrayType::ArraySizeModifier SizeMod,
816                             const llvm::APInt *Size,
817                             Expr *SizeExpr,
818                             unsigned IndexTypeQuals,
819                             SourceRange BracketsRange);
820 
821   /// Build a new constant array type given the element type, size
822   /// modifier, (known) size of the array, and index type qualifiers.
823   ///
824   /// By default, performs semantic analysis when building the array type.
825   /// Subclasses may override this routine to provide different behavior.
826   QualType RebuildConstantArrayType(QualType ElementType,
827                                     ArrayType::ArraySizeModifier SizeMod,
828                                     const llvm::APInt &Size,
829                                     Expr *SizeExpr,
830                                     unsigned IndexTypeQuals,
831                                     SourceRange BracketsRange);
832 
833   /// Build a new incomplete array type given the element type, size
834   /// modifier, and index type qualifiers.
835   ///
836   /// By default, performs semantic analysis when building the array type.
837   /// Subclasses may override this routine to provide different behavior.
838   QualType RebuildIncompleteArrayType(QualType ElementType,
839                                       ArrayType::ArraySizeModifier SizeMod,
840                                       unsigned IndexTypeQuals,
841                                       SourceRange BracketsRange);
842 
843   /// Build a new variable-length array type given the element type,
844   /// size modifier, size expression, and index type qualifiers.
845   ///
846   /// By default, performs semantic analysis when building the array type.
847   /// Subclasses may override this routine to provide different behavior.
848   QualType RebuildVariableArrayType(QualType ElementType,
849                                     ArrayType::ArraySizeModifier SizeMod,
850                                     Expr *SizeExpr,
851                                     unsigned IndexTypeQuals,
852                                     SourceRange BracketsRange);
853 
854   /// Build a new dependent-sized array type given the element type,
855   /// size modifier, size expression, and index type qualifiers.
856   ///
857   /// By default, performs semantic analysis when building the array type.
858   /// Subclasses may override this routine to provide different behavior.
859   QualType RebuildDependentSizedArrayType(QualType ElementType,
860                                           ArrayType::ArraySizeModifier SizeMod,
861                                           Expr *SizeExpr,
862                                           unsigned IndexTypeQuals,
863                                           SourceRange BracketsRange);
864 
865   /// Build a new vector type given the element type and
866   /// number of elements.
867   ///
868   /// By default, performs semantic analysis when building the vector type.
869   /// Subclasses may override this routine to provide different behavior.
870   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
871                              VectorType::VectorKind VecKind);
872 
873   /// Build a new potentially dependently-sized extended vector type
874   /// given the element type and number of elements.
875   ///
876   /// By default, performs semantic analysis when building the vector type.
877   /// Subclasses may override this routine to provide different behavior.
878   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
879                                            SourceLocation AttributeLoc,
880                                            VectorType::VectorKind);
881 
882   /// Build a new extended vector type given the element type and
883   /// number of elements.
884   ///
885   /// By default, performs semantic analysis when building the vector type.
886   /// Subclasses may override this routine to provide different behavior.
887   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
888                                 SourceLocation AttributeLoc);
889 
890   /// Build a new potentially dependently-sized extended vector type
891   /// given the element type and number of elements.
892   ///
893   /// By default, performs semantic analysis when building the vector type.
894   /// Subclasses may override this routine to provide different behavior.
895   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
896                                               Expr *SizeExpr,
897                                               SourceLocation AttributeLoc);
898 
899   /// Build a new matrix type given the element type and dimensions.
900   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
901                                      unsigned NumColumns);
902 
903   /// Build a new matrix type given the type and dependently-defined
904   /// dimensions.
905   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
906                                            Expr *ColumnExpr,
907                                            SourceLocation AttributeLoc);
908 
909   /// Build a new DependentAddressSpaceType or return the pointee
910   /// type variable with the correct address space (retrieved from
911   /// AddrSpaceExpr) applied to it. The former will be returned in cases
912   /// where the address space remains dependent.
913   ///
914   /// By default, performs semantic analysis when building the type with address
915   /// space applied. Subclasses may override this routine to provide different
916   /// behavior.
917   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
918                                             Expr *AddrSpaceExpr,
919                                             SourceLocation AttributeLoc);
920 
921   /// Build a new function type.
922   ///
923   /// By default, performs semantic analysis when building the function type.
924   /// Subclasses may override this routine to provide different behavior.
925   QualType RebuildFunctionProtoType(QualType T,
926                                     MutableArrayRef<QualType> ParamTypes,
927                                     const FunctionProtoType::ExtProtoInfo &EPI);
928 
929   /// Build a new unprototyped function type.
930   QualType RebuildFunctionNoProtoType(QualType ResultType);
931 
932   /// Rebuild an unresolved typename type, given the decl that
933   /// the UnresolvedUsingTypenameDecl was transformed to.
934   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
935 
936   /// Build a new typedef type.
937   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
938     return SemaRef.Context.getTypeDeclType(Typedef);
939   }
940 
941   /// Build a new MacroDefined type.
942   QualType RebuildMacroQualifiedType(QualType T,
943                                      const IdentifierInfo *MacroII) {
944     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
945   }
946 
947   /// Build a new class/struct/union type.
948   QualType RebuildRecordType(RecordDecl *Record) {
949     return SemaRef.Context.getTypeDeclType(Record);
950   }
951 
952   /// Build a new Enum type.
953   QualType RebuildEnumType(EnumDecl *Enum) {
954     return SemaRef.Context.getTypeDeclType(Enum);
955   }
956 
957   /// Build a new typeof(expr) type.
958   ///
959   /// By default, performs semantic analysis when building the typeof type.
960   /// Subclasses may override this routine to provide different behavior.
961   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
962 
963   /// Build a new typeof(type) type.
964   ///
965   /// By default, builds a new TypeOfType with the given underlying type.
966   QualType RebuildTypeOfType(QualType Underlying);
967 
968   /// Build a new unary transform type.
969   QualType RebuildUnaryTransformType(QualType BaseType,
970                                      UnaryTransformType::UTTKind UKind,
971                                      SourceLocation Loc);
972 
973   /// Build a new C++11 decltype type.
974   ///
975   /// By default, performs semantic analysis when building the decltype type.
976   /// Subclasses may override this routine to provide different behavior.
977   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
978 
979   /// Build a new C++11 auto type.
980   ///
981   /// By default, builds a new AutoType with the given deduced type.
982   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
983                            ConceptDecl *TypeConstraintConcept,
984                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
985     // Note, IsDependent is always false here: we implicitly convert an 'auto'
986     // which has been deduced to a dependent type into an undeduced 'auto', so
987     // that we'll retry deduction after the transformation.
988     return SemaRef.Context.getAutoType(Deduced, Keyword,
989                                        /*IsDependent*/ false, /*IsPack=*/false,
990                                        TypeConstraintConcept,
991                                        TypeConstraintArgs);
992   }
993 
994   /// By default, builds a new DeducedTemplateSpecializationType with the given
995   /// deduced type.
996   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
997       QualType Deduced) {
998     return SemaRef.Context.getDeducedTemplateSpecializationType(
999         Template, Deduced, /*IsDependent*/ false);
1000   }
1001 
1002   /// Build a new template specialization type.
1003   ///
1004   /// By default, performs semantic analysis when building the template
1005   /// specialization type. Subclasses may override this routine to provide
1006   /// different behavior.
1007   QualType RebuildTemplateSpecializationType(TemplateName Template,
1008                                              SourceLocation TemplateLoc,
1009                                              TemplateArgumentListInfo &Args);
1010 
1011   /// Build a new parenthesized type.
1012   ///
1013   /// By default, builds a new ParenType type from the inner type.
1014   /// Subclasses may override this routine to provide different behavior.
1015   QualType RebuildParenType(QualType InnerType) {
1016     return SemaRef.BuildParenType(InnerType);
1017   }
1018 
1019   /// Build a new qualified name type.
1020   ///
1021   /// By default, builds a new ElaboratedType type from the keyword,
1022   /// the nested-name-specifier and the named type.
1023   /// Subclasses may override this routine to provide different behavior.
1024   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1025                                  ElaboratedTypeKeyword Keyword,
1026                                  NestedNameSpecifierLoc QualifierLoc,
1027                                  QualType Named) {
1028     return SemaRef.Context.getElaboratedType(Keyword,
1029                                          QualifierLoc.getNestedNameSpecifier(),
1030                                              Named);
1031   }
1032 
1033   /// Build a new typename type that refers to a template-id.
1034   ///
1035   /// By default, builds a new DependentNameType type from the
1036   /// nested-name-specifier and the given type. Subclasses may override
1037   /// this routine to provide different behavior.
1038   QualType RebuildDependentTemplateSpecializationType(
1039                                           ElaboratedTypeKeyword Keyword,
1040                                           NestedNameSpecifierLoc QualifierLoc,
1041                                           SourceLocation TemplateKWLoc,
1042                                           const IdentifierInfo *Name,
1043                                           SourceLocation NameLoc,
1044                                           TemplateArgumentListInfo &Args,
1045                                           bool AllowInjectedClassName) {
1046     // Rebuild the template name.
1047     // TODO: avoid TemplateName abstraction
1048     CXXScopeSpec SS;
1049     SS.Adopt(QualifierLoc);
1050     TemplateName InstName = getDerived().RebuildTemplateName(
1051         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1052         AllowInjectedClassName);
1053 
1054     if (InstName.isNull())
1055       return QualType();
1056 
1057     // If it's still dependent, make a dependent specialization.
1058     if (InstName.getAsDependentTemplateName())
1059       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1060                                           QualifierLoc.getNestedNameSpecifier(),
1061                                                                     Name,
1062                                                                     Args);
1063 
1064     // Otherwise, make an elaborated type wrapping a non-dependent
1065     // specialization.
1066     QualType T =
1067     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1068     if (T.isNull()) return QualType();
1069 
1070     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1071       return T;
1072 
1073     return SemaRef.Context.getElaboratedType(Keyword,
1074                                        QualifierLoc.getNestedNameSpecifier(),
1075                                              T);
1076   }
1077 
1078   /// Build a new typename type that refers to an identifier.
1079   ///
1080   /// By default, performs semantic analysis when building the typename type
1081   /// (or elaborated type). Subclasses may override this routine to provide
1082   /// different behavior.
1083   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1084                                     SourceLocation KeywordLoc,
1085                                     NestedNameSpecifierLoc QualifierLoc,
1086                                     const IdentifierInfo *Id,
1087                                     SourceLocation IdLoc,
1088                                     bool DeducedTSTContext) {
1089     CXXScopeSpec SS;
1090     SS.Adopt(QualifierLoc);
1091 
1092     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1093       // If the name is still dependent, just build a new dependent name type.
1094       if (!SemaRef.computeDeclContext(SS))
1095         return SemaRef.Context.getDependentNameType(Keyword,
1096                                           QualifierLoc.getNestedNameSpecifier(),
1097                                                     Id);
1098     }
1099 
1100     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1101       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1102                                        *Id, IdLoc, DeducedTSTContext);
1103     }
1104 
1105     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1106 
1107     // We had a dependent elaborated-type-specifier that has been transformed
1108     // into a non-dependent elaborated-type-specifier. Find the tag we're
1109     // referring to.
1110     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1111     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1112     if (!DC)
1113       return QualType();
1114 
1115     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1116       return QualType();
1117 
1118     TagDecl *Tag = nullptr;
1119     SemaRef.LookupQualifiedName(Result, DC);
1120     switch (Result.getResultKind()) {
1121       case LookupResult::NotFound:
1122       case LookupResult::NotFoundInCurrentInstantiation:
1123         break;
1124 
1125       case LookupResult::Found:
1126         Tag = Result.getAsSingle<TagDecl>();
1127         break;
1128 
1129       case LookupResult::FoundOverloaded:
1130       case LookupResult::FoundUnresolvedValue:
1131         llvm_unreachable("Tag lookup cannot find non-tags");
1132 
1133       case LookupResult::Ambiguous:
1134         // Let the LookupResult structure handle ambiguities.
1135         return QualType();
1136     }
1137 
1138     if (!Tag) {
1139       // Check where the name exists but isn't a tag type and use that to emit
1140       // better diagnostics.
1141       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1142       SemaRef.LookupQualifiedName(Result, DC);
1143       switch (Result.getResultKind()) {
1144         case LookupResult::Found:
1145         case LookupResult::FoundOverloaded:
1146         case LookupResult::FoundUnresolvedValue: {
1147           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1148           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1149           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1150                                                                << NTK << Kind;
1151           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1152           break;
1153         }
1154         default:
1155           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1156               << Kind << Id << DC << QualifierLoc.getSourceRange();
1157           break;
1158       }
1159       return QualType();
1160     }
1161 
1162     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1163                                               IdLoc, Id)) {
1164       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1165       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1166       return QualType();
1167     }
1168 
1169     // Build the elaborated-type-specifier type.
1170     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1171     return SemaRef.Context.getElaboratedType(Keyword,
1172                                          QualifierLoc.getNestedNameSpecifier(),
1173                                              T);
1174   }
1175 
1176   /// Build a new pack expansion type.
1177   ///
1178   /// By default, builds a new PackExpansionType type from the given pattern.
1179   /// Subclasses may override this routine to provide different behavior.
1180   QualType RebuildPackExpansionType(QualType Pattern,
1181                                     SourceRange PatternRange,
1182                                     SourceLocation EllipsisLoc,
1183                                     Optional<unsigned> NumExpansions) {
1184     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1185                                         NumExpansions);
1186   }
1187 
1188   /// Build a new atomic type given its value type.
1189   ///
1190   /// By default, performs semantic analysis when building the atomic type.
1191   /// Subclasses may override this routine to provide different behavior.
1192   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1193 
1194   /// Build a new pipe type given its value type.
1195   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1196                            bool isReadPipe);
1197 
1198    /// Build an extended int given its value type.
1199   QualType RebuildExtIntType(bool IsUnsigned, unsigned NumBits,
1200                              SourceLocation Loc);
1201 
1202   /// Build a dependent extended int given its value type.
1203   QualType RebuildDependentExtIntType(bool IsUnsigned, Expr *NumBitsExpr,
1204                                       SourceLocation Loc);
1205 
1206   /// Build a new template name given a nested name specifier, a flag
1207   /// indicating whether the "template" keyword was provided, and the template
1208   /// that the template name refers to.
1209   ///
1210   /// By default, builds the new template name directly. Subclasses may override
1211   /// this routine to provide different behavior.
1212   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1213                                    bool TemplateKW,
1214                                    TemplateDecl *Template);
1215 
1216   /// Build a new template name given a nested name specifier and the
1217   /// name that is referred to as a template.
1218   ///
1219   /// By default, performs semantic analysis to determine whether the name can
1220   /// be resolved to a specific template, then builds the appropriate kind of
1221   /// template name. Subclasses may override this routine to provide different
1222   /// behavior.
1223   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1224                                    SourceLocation TemplateKWLoc,
1225                                    const IdentifierInfo &Name,
1226                                    SourceLocation NameLoc, QualType ObjectType,
1227                                    NamedDecl *FirstQualifierInScope,
1228                                    bool AllowInjectedClassName);
1229 
1230   /// Build a new template name given a nested name specifier and the
1231   /// overloaded operator name that is referred to as a template.
1232   ///
1233   /// By default, performs semantic analysis to determine whether the name can
1234   /// be resolved to a specific template, then builds the appropriate kind of
1235   /// template name. Subclasses may override this routine to provide different
1236   /// behavior.
1237   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1238                                    SourceLocation TemplateKWLoc,
1239                                    OverloadedOperatorKind Operator,
1240                                    SourceLocation NameLoc, QualType ObjectType,
1241                                    bool AllowInjectedClassName);
1242 
1243   /// Build a new template name given a template template parameter pack
1244   /// and the
1245   ///
1246   /// By default, performs semantic analysis to determine whether the name can
1247   /// be resolved to a specific template, then builds the appropriate kind of
1248   /// template name. Subclasses may override this routine to provide different
1249   /// behavior.
1250   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1251                                    const TemplateArgument &ArgPack) {
1252     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1253   }
1254 
1255   /// Build a new compound statement.
1256   ///
1257   /// By default, performs semantic analysis to build the new statement.
1258   /// Subclasses may override this routine to provide different behavior.
1259   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1260                                        MultiStmtArg Statements,
1261                                        SourceLocation RBraceLoc,
1262                                        bool IsStmtExpr) {
1263     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1264                                        IsStmtExpr);
1265   }
1266 
1267   /// Build a new case statement.
1268   ///
1269   /// By default, performs semantic analysis to build the new statement.
1270   /// Subclasses may override this routine to provide different behavior.
1271   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1272                                    Expr *LHS,
1273                                    SourceLocation EllipsisLoc,
1274                                    Expr *RHS,
1275                                    SourceLocation ColonLoc) {
1276     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1277                                    ColonLoc);
1278   }
1279 
1280   /// Attach the body to a new case statement.
1281   ///
1282   /// By default, performs semantic analysis to build the new statement.
1283   /// Subclasses may override this routine to provide different behavior.
1284   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1285     getSema().ActOnCaseStmtBody(S, Body);
1286     return S;
1287   }
1288 
1289   /// Build a new default statement.
1290   ///
1291   /// By default, performs semantic analysis to build the new statement.
1292   /// Subclasses may override this routine to provide different behavior.
1293   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1294                                       SourceLocation ColonLoc,
1295                                       Stmt *SubStmt) {
1296     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1297                                       /*CurScope=*/nullptr);
1298   }
1299 
1300   /// Build a new label statement.
1301   ///
1302   /// By default, performs semantic analysis to build the new statement.
1303   /// Subclasses may override this routine to provide different behavior.
1304   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1305                               SourceLocation ColonLoc, Stmt *SubStmt) {
1306     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1307   }
1308 
1309   /// Build a new attributed statement.
1310   ///
1311   /// By default, performs semantic analysis to build the new statement.
1312   /// Subclasses may override this routine to provide different behavior.
1313   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1314                                    ArrayRef<const Attr *> Attrs,
1315                                    Stmt *SubStmt) {
1316     return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1317   }
1318 
1319   /// Build a new "if" statement.
1320   ///
1321   /// By default, performs semantic analysis to build the new statement.
1322   /// Subclasses may override this routine to provide different behavior.
1323   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1324                            SourceLocation LParenLoc, Sema::ConditionResult Cond,
1325                            SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1326                            SourceLocation ElseLoc, Stmt *Else) {
1327     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, LParenLoc, Init, Cond,
1328                                  RParenLoc, Then, ElseLoc, Else);
1329   }
1330 
1331   /// Start building a new switch statement.
1332   ///
1333   /// By default, performs semantic analysis to build the new statement.
1334   /// Subclasses may override this routine to provide different behavior.
1335   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1336                                     SourceLocation LParenLoc, Stmt *Init,
1337                                     Sema::ConditionResult Cond,
1338                                     SourceLocation RParenLoc) {
1339     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1340                                             RParenLoc);
1341   }
1342 
1343   /// Attach the body to the switch statement.
1344   ///
1345   /// By default, performs semantic analysis to build the new statement.
1346   /// Subclasses may override this routine to provide different behavior.
1347   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1348                                    Stmt *Switch, Stmt *Body) {
1349     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1350   }
1351 
1352   /// Build a new while statement.
1353   ///
1354   /// By default, performs semantic analysis to build the new statement.
1355   /// Subclasses may override this routine to provide different behavior.
1356   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1357                               Sema::ConditionResult Cond,
1358                               SourceLocation RParenLoc, Stmt *Body) {
1359     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1360   }
1361 
1362   /// Build a new do-while statement.
1363   ///
1364   /// By default, performs semantic analysis to build the new statement.
1365   /// Subclasses may override this routine to provide different behavior.
1366   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1367                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1368                            Expr *Cond, SourceLocation RParenLoc) {
1369     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1370                                  Cond, RParenLoc);
1371   }
1372 
1373   /// Build a new for statement.
1374   ///
1375   /// By default, performs semantic analysis to build the new statement.
1376   /// Subclasses may override this routine to provide different behavior.
1377   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1378                             Stmt *Init, Sema::ConditionResult Cond,
1379                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1380                             Stmt *Body) {
1381     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1382                                   Inc, RParenLoc, Body);
1383   }
1384 
1385   /// Build a new goto statement.
1386   ///
1387   /// By default, performs semantic analysis to build the new statement.
1388   /// Subclasses may override this routine to provide different behavior.
1389   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1390                              LabelDecl *Label) {
1391     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1392   }
1393 
1394   /// Build a new indirect goto statement.
1395   ///
1396   /// By default, performs semantic analysis to build the new statement.
1397   /// Subclasses may override this routine to provide different behavior.
1398   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1399                                      SourceLocation StarLoc,
1400                                      Expr *Target) {
1401     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1402   }
1403 
1404   /// Build a new return statement.
1405   ///
1406   /// By default, performs semantic analysis to build the new statement.
1407   /// Subclasses may override this routine to provide different behavior.
1408   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1409     return getSema().BuildReturnStmt(ReturnLoc, Result);
1410   }
1411 
1412   /// Build a new declaration statement.
1413   ///
1414   /// By default, performs semantic analysis to build the new statement.
1415   /// Subclasses may override this routine to provide different behavior.
1416   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1417                              SourceLocation StartLoc, SourceLocation EndLoc) {
1418     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1419     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1420   }
1421 
1422   /// Build a new inline asm statement.
1423   ///
1424   /// By default, performs semantic analysis to build the new statement.
1425   /// Subclasses may override this routine to provide different behavior.
1426   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1427                                bool IsVolatile, unsigned NumOutputs,
1428                                unsigned NumInputs, IdentifierInfo **Names,
1429                                MultiExprArg Constraints, MultiExprArg Exprs,
1430                                Expr *AsmString, MultiExprArg Clobbers,
1431                                unsigned NumLabels,
1432                                SourceLocation RParenLoc) {
1433     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1434                                      NumInputs, Names, Constraints, Exprs,
1435                                      AsmString, Clobbers, NumLabels, RParenLoc);
1436   }
1437 
1438   /// Build a new MS style inline asm statement.
1439   ///
1440   /// By default, performs semantic analysis to build the new statement.
1441   /// Subclasses may override this routine to provide different behavior.
1442   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1443                               ArrayRef<Token> AsmToks,
1444                               StringRef AsmString,
1445                               unsigned NumOutputs, unsigned NumInputs,
1446                               ArrayRef<StringRef> Constraints,
1447                               ArrayRef<StringRef> Clobbers,
1448                               ArrayRef<Expr*> Exprs,
1449                               SourceLocation EndLoc) {
1450     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1451                                     NumOutputs, NumInputs,
1452                                     Constraints, Clobbers, Exprs, EndLoc);
1453   }
1454 
1455   /// Build a new co_return statement.
1456   ///
1457   /// By default, performs semantic analysis to build the new statement.
1458   /// Subclasses may override this routine to provide different behavior.
1459   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1460                                  bool IsImplicit) {
1461     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1462   }
1463 
1464   /// Build a new co_await expression.
1465   ///
1466   /// By default, performs semantic analysis to build the new expression.
1467   /// Subclasses may override this routine to provide different behavior.
1468   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1469                                 bool IsImplicit) {
1470     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1471   }
1472 
1473   /// Build a new co_await expression.
1474   ///
1475   /// By default, performs semantic analysis to build the new expression.
1476   /// Subclasses may override this routine to provide different behavior.
1477   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1478                                          Expr *Result,
1479                                          UnresolvedLookupExpr *Lookup) {
1480     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1481   }
1482 
1483   /// Build a new co_yield expression.
1484   ///
1485   /// By default, performs semantic analysis to build the new expression.
1486   /// Subclasses may override this routine to provide different behavior.
1487   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1488     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1489   }
1490 
1491   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1492     return getSema().BuildCoroutineBodyStmt(Args);
1493   }
1494 
1495   /// Build a new Objective-C \@try statement.
1496   ///
1497   /// By default, performs semantic analysis to build the new statement.
1498   /// Subclasses may override this routine to provide different behavior.
1499   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1500                                         Stmt *TryBody,
1501                                         MultiStmtArg CatchStmts,
1502                                         Stmt *Finally) {
1503     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1504                                         Finally);
1505   }
1506 
1507   /// Rebuild an Objective-C exception declaration.
1508   ///
1509   /// By default, performs semantic analysis to build the new declaration.
1510   /// Subclasses may override this routine to provide different behavior.
1511   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1512                                     TypeSourceInfo *TInfo, QualType T) {
1513     return getSema().BuildObjCExceptionDecl(TInfo, T,
1514                                             ExceptionDecl->getInnerLocStart(),
1515                                             ExceptionDecl->getLocation(),
1516                                             ExceptionDecl->getIdentifier());
1517   }
1518 
1519   /// Build a new Objective-C \@catch statement.
1520   ///
1521   /// By default, performs semantic analysis to build the new statement.
1522   /// Subclasses may override this routine to provide different behavior.
1523   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1524                                           SourceLocation RParenLoc,
1525                                           VarDecl *Var,
1526                                           Stmt *Body) {
1527     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1528                                           Var, Body);
1529   }
1530 
1531   /// Build a new Objective-C \@finally statement.
1532   ///
1533   /// By default, performs semantic analysis to build the new statement.
1534   /// Subclasses may override this routine to provide different behavior.
1535   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1536                                             Stmt *Body) {
1537     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1538   }
1539 
1540   /// Build a new Objective-C \@throw statement.
1541   ///
1542   /// By default, performs semantic analysis to build the new statement.
1543   /// Subclasses may override this routine to provide different behavior.
1544   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1545                                           Expr *Operand) {
1546     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1547   }
1548 
1549   /// Build a new OpenMP Canonical loop.
1550   ///
1551   /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1552   /// OMPCanonicalLoop.
1553   StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1554     return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1555   }
1556 
1557   /// Build a new OpenMP executable directive.
1558   ///
1559   /// By default, performs semantic analysis to build the new statement.
1560   /// Subclasses may override this routine to provide different behavior.
1561   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1562                                            DeclarationNameInfo DirName,
1563                                            OpenMPDirectiveKind CancelRegion,
1564                                            ArrayRef<OMPClause *> Clauses,
1565                                            Stmt *AStmt, SourceLocation StartLoc,
1566                                            SourceLocation EndLoc) {
1567     return getSema().ActOnOpenMPExecutableDirective(
1568         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1569   }
1570 
1571   /// Build a new OpenMP 'if' clause.
1572   ///
1573   /// By default, performs semantic analysis to build the new OpenMP clause.
1574   /// Subclasses may override this routine to provide different behavior.
1575   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1576                                 Expr *Condition, SourceLocation StartLoc,
1577                                 SourceLocation LParenLoc,
1578                                 SourceLocation NameModifierLoc,
1579                                 SourceLocation ColonLoc,
1580                                 SourceLocation EndLoc) {
1581     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1582                                          LParenLoc, NameModifierLoc, ColonLoc,
1583                                          EndLoc);
1584   }
1585 
1586   /// Build a new OpenMP 'final' clause.
1587   ///
1588   /// By default, performs semantic analysis to build the new OpenMP clause.
1589   /// Subclasses may override this routine to provide different behavior.
1590   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1591                                    SourceLocation LParenLoc,
1592                                    SourceLocation EndLoc) {
1593     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1594                                             EndLoc);
1595   }
1596 
1597   /// Build a new OpenMP 'num_threads' clause.
1598   ///
1599   /// By default, performs semantic analysis to build the new OpenMP clause.
1600   /// Subclasses may override this routine to provide different behavior.
1601   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1602                                         SourceLocation StartLoc,
1603                                         SourceLocation LParenLoc,
1604                                         SourceLocation EndLoc) {
1605     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1606                                                  LParenLoc, EndLoc);
1607   }
1608 
1609   /// Build a new OpenMP 'safelen' clause.
1610   ///
1611   /// By default, performs semantic analysis to build the new OpenMP clause.
1612   /// Subclasses may override this routine to provide different behavior.
1613   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1614                                      SourceLocation LParenLoc,
1615                                      SourceLocation EndLoc) {
1616     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1617   }
1618 
1619   /// Build a new OpenMP 'simdlen' clause.
1620   ///
1621   /// By default, performs semantic analysis to build the new OpenMP clause.
1622   /// Subclasses may override this routine to provide different behavior.
1623   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1624                                      SourceLocation LParenLoc,
1625                                      SourceLocation EndLoc) {
1626     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1627   }
1628 
1629   OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1630                                    SourceLocation StartLoc,
1631                                    SourceLocation LParenLoc,
1632                                    SourceLocation EndLoc) {
1633     return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1634   }
1635 
1636   /// Build a new OpenMP 'full' clause.
1637   OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1638                                   SourceLocation EndLoc) {
1639     return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1640   }
1641 
1642   /// Build a new OpenMP 'partial' clause.
1643   OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1644                                      SourceLocation LParenLoc,
1645                                      SourceLocation EndLoc) {
1646     return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1647                                               EndLoc);
1648   }
1649 
1650   /// Build a new OpenMP 'allocator' clause.
1651   ///
1652   /// By default, performs semantic analysis to build the new OpenMP clause.
1653   /// Subclasses may override this routine to provide different behavior.
1654   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1655                                        SourceLocation LParenLoc,
1656                                        SourceLocation EndLoc) {
1657     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1658   }
1659 
1660   /// Build a new OpenMP 'collapse' clause.
1661   ///
1662   /// By default, performs semantic analysis to build the new OpenMP clause.
1663   /// Subclasses may override this routine to provide different behavior.
1664   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1665                                       SourceLocation LParenLoc,
1666                                       SourceLocation EndLoc) {
1667     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1668                                                EndLoc);
1669   }
1670 
1671   /// Build a new OpenMP 'default' clause.
1672   ///
1673   /// By default, performs semantic analysis to build the new OpenMP clause.
1674   /// Subclasses may override this routine to provide different behavior.
1675   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1676                                      SourceLocation StartLoc,
1677                                      SourceLocation LParenLoc,
1678                                      SourceLocation EndLoc) {
1679     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1680                                               StartLoc, LParenLoc, EndLoc);
1681   }
1682 
1683   /// Build a new OpenMP 'proc_bind' clause.
1684   ///
1685   /// By default, performs semantic analysis to build the new OpenMP clause.
1686   /// Subclasses may override this routine to provide different behavior.
1687   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1688                                       SourceLocation KindKwLoc,
1689                                       SourceLocation StartLoc,
1690                                       SourceLocation LParenLoc,
1691                                       SourceLocation EndLoc) {
1692     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1693                                                StartLoc, LParenLoc, EndLoc);
1694   }
1695 
1696   /// Build a new OpenMP 'schedule' clause.
1697   ///
1698   /// By default, performs semantic analysis to build the new OpenMP clause.
1699   /// Subclasses may override this routine to provide different behavior.
1700   OMPClause *RebuildOMPScheduleClause(
1701       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1702       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1703       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1704       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1705     return getSema().ActOnOpenMPScheduleClause(
1706         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1707         CommaLoc, EndLoc);
1708   }
1709 
1710   /// Build a new OpenMP 'ordered' clause.
1711   ///
1712   /// By default, performs semantic analysis to build the new OpenMP clause.
1713   /// Subclasses may override this routine to provide different behavior.
1714   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1715                                      SourceLocation EndLoc,
1716                                      SourceLocation LParenLoc, Expr *Num) {
1717     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1718   }
1719 
1720   /// Build a new OpenMP 'private' clause.
1721   ///
1722   /// By default, performs semantic analysis to build the new OpenMP clause.
1723   /// Subclasses may override this routine to provide different behavior.
1724   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1725                                      SourceLocation StartLoc,
1726                                      SourceLocation LParenLoc,
1727                                      SourceLocation EndLoc) {
1728     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1729                                               EndLoc);
1730   }
1731 
1732   /// Build a new OpenMP 'firstprivate' clause.
1733   ///
1734   /// By default, performs semantic analysis to build the new OpenMP clause.
1735   /// Subclasses may override this routine to provide different behavior.
1736   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1737                                           SourceLocation StartLoc,
1738                                           SourceLocation LParenLoc,
1739                                           SourceLocation EndLoc) {
1740     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1741                                                    EndLoc);
1742   }
1743 
1744   /// Build a new OpenMP 'lastprivate' clause.
1745   ///
1746   /// By default, performs semantic analysis to build the new OpenMP clause.
1747   /// Subclasses may override this routine to provide different behavior.
1748   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1749                                          OpenMPLastprivateModifier LPKind,
1750                                          SourceLocation LPKindLoc,
1751                                          SourceLocation ColonLoc,
1752                                          SourceLocation StartLoc,
1753                                          SourceLocation LParenLoc,
1754                                          SourceLocation EndLoc) {
1755     return getSema().ActOnOpenMPLastprivateClause(
1756         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1757   }
1758 
1759   /// Build a new OpenMP 'shared' clause.
1760   ///
1761   /// By default, performs semantic analysis to build the new OpenMP clause.
1762   /// Subclasses may override this routine to provide different behavior.
1763   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1764                                     SourceLocation StartLoc,
1765                                     SourceLocation LParenLoc,
1766                                     SourceLocation EndLoc) {
1767     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1768                                              EndLoc);
1769   }
1770 
1771   /// Build a new OpenMP 'reduction' clause.
1772   ///
1773   /// By default, performs semantic analysis to build the new statement.
1774   /// Subclasses may override this routine to provide different behavior.
1775   OMPClause *RebuildOMPReductionClause(
1776       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1777       SourceLocation StartLoc, SourceLocation LParenLoc,
1778       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1779       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1780       const DeclarationNameInfo &ReductionId,
1781       ArrayRef<Expr *> UnresolvedReductions) {
1782     return getSema().ActOnOpenMPReductionClause(
1783         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1784         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1785   }
1786 
1787   /// Build a new OpenMP 'task_reduction' clause.
1788   ///
1789   /// By default, performs semantic analysis to build the new statement.
1790   /// Subclasses may override this routine to provide different behavior.
1791   OMPClause *RebuildOMPTaskReductionClause(
1792       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1793       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1794       CXXScopeSpec &ReductionIdScopeSpec,
1795       const DeclarationNameInfo &ReductionId,
1796       ArrayRef<Expr *> UnresolvedReductions) {
1797     return getSema().ActOnOpenMPTaskReductionClause(
1798         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1799         ReductionId, UnresolvedReductions);
1800   }
1801 
1802   /// Build a new OpenMP 'in_reduction' clause.
1803   ///
1804   /// By default, performs semantic analysis to build the new statement.
1805   /// Subclasses may override this routine to provide different behavior.
1806   OMPClause *
1807   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1808                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1809                               SourceLocation EndLoc,
1810                               CXXScopeSpec &ReductionIdScopeSpec,
1811                               const DeclarationNameInfo &ReductionId,
1812                               ArrayRef<Expr *> UnresolvedReductions) {
1813     return getSema().ActOnOpenMPInReductionClause(
1814         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1815         ReductionId, UnresolvedReductions);
1816   }
1817 
1818   /// Build a new OpenMP 'linear' clause.
1819   ///
1820   /// By default, performs semantic analysis to build the new OpenMP clause.
1821   /// Subclasses may override this routine to provide different behavior.
1822   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1823                                     SourceLocation StartLoc,
1824                                     SourceLocation LParenLoc,
1825                                     OpenMPLinearClauseKind Modifier,
1826                                     SourceLocation ModifierLoc,
1827                                     SourceLocation ColonLoc,
1828                                     SourceLocation EndLoc) {
1829     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1830                                              Modifier, ModifierLoc, ColonLoc,
1831                                              EndLoc);
1832   }
1833 
1834   /// Build a new OpenMP 'aligned' clause.
1835   ///
1836   /// By default, performs semantic analysis to build the new OpenMP clause.
1837   /// Subclasses may override this routine to provide different behavior.
1838   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1839                                      SourceLocation StartLoc,
1840                                      SourceLocation LParenLoc,
1841                                      SourceLocation ColonLoc,
1842                                      SourceLocation EndLoc) {
1843     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1844                                               LParenLoc, ColonLoc, EndLoc);
1845   }
1846 
1847   /// Build a new OpenMP 'copyin' clause.
1848   ///
1849   /// By default, performs semantic analysis to build the new OpenMP clause.
1850   /// Subclasses may override this routine to provide different behavior.
1851   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1852                                     SourceLocation StartLoc,
1853                                     SourceLocation LParenLoc,
1854                                     SourceLocation EndLoc) {
1855     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1856                                              EndLoc);
1857   }
1858 
1859   /// Build a new OpenMP 'copyprivate' 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 *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1864                                          SourceLocation StartLoc,
1865                                          SourceLocation LParenLoc,
1866                                          SourceLocation EndLoc) {
1867     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1868                                                   EndLoc);
1869   }
1870 
1871   /// Build a new OpenMP 'flush' pseudo clause.
1872   ///
1873   /// By default, performs semantic analysis to build the new OpenMP clause.
1874   /// Subclasses may override this routine to provide different behavior.
1875   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1876                                    SourceLocation StartLoc,
1877                                    SourceLocation LParenLoc,
1878                                    SourceLocation EndLoc) {
1879     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1880                                             EndLoc);
1881   }
1882 
1883   /// Build a new OpenMP 'depobj' pseudo clause.
1884   ///
1885   /// By default, performs semantic analysis to build the new OpenMP clause.
1886   /// Subclasses may override this routine to provide different behavior.
1887   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1888                                     SourceLocation LParenLoc,
1889                                     SourceLocation EndLoc) {
1890     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1891                                              EndLoc);
1892   }
1893 
1894   /// Build a new OpenMP 'depend' pseudo clause.
1895   ///
1896   /// By default, performs semantic analysis to build the new OpenMP clause.
1897   /// Subclasses may override this routine to provide different behavior.
1898   OMPClause *
1899   RebuildOMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
1900                          SourceLocation DepLoc, SourceLocation ColonLoc,
1901                          ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1902                          SourceLocation LParenLoc, SourceLocation EndLoc) {
1903     return getSema().ActOnOpenMPDependClause(DepModifier, DepKind, DepLoc,
1904                                              ColonLoc, VarList, StartLoc,
1905                                              LParenLoc, EndLoc);
1906   }
1907 
1908   /// Build a new OpenMP 'device' clause.
1909   ///
1910   /// By default, performs semantic analysis to build the new statement.
1911   /// Subclasses may override this routine to provide different behavior.
1912   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1913                                     Expr *Device, SourceLocation StartLoc,
1914                                     SourceLocation LParenLoc,
1915                                     SourceLocation ModifierLoc,
1916                                     SourceLocation EndLoc) {
1917     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1918                                              LParenLoc, ModifierLoc, EndLoc);
1919   }
1920 
1921   /// Build a new OpenMP 'map' clause.
1922   ///
1923   /// By default, performs semantic analysis to build the new OpenMP clause.
1924   /// Subclasses may override this routine to provide different behavior.
1925   OMPClause *RebuildOMPMapClause(
1926       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1927       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1928       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1929       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1930       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1931       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1932     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1933                                           MapperIdScopeSpec, MapperId, MapType,
1934                                           IsMapTypeImplicit, MapLoc, ColonLoc,
1935                                           VarList, Locs, UnresolvedMappers);
1936   }
1937 
1938   /// Build a new OpenMP 'allocate' clause.
1939   ///
1940   /// By default, performs semantic analysis to build the new OpenMP clause.
1941   /// Subclasses may override this routine to provide different behavior.
1942   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1943                                       SourceLocation StartLoc,
1944                                       SourceLocation LParenLoc,
1945                                       SourceLocation ColonLoc,
1946                                       SourceLocation EndLoc) {
1947     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1948                                                LParenLoc, ColonLoc, EndLoc);
1949   }
1950 
1951   /// Build a new OpenMP 'num_teams' clause.
1952   ///
1953   /// By default, performs semantic analysis to build the new statement.
1954   /// Subclasses may override this routine to provide different behavior.
1955   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1956                                       SourceLocation LParenLoc,
1957                                       SourceLocation EndLoc) {
1958     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1959                                                EndLoc);
1960   }
1961 
1962   /// Build a new OpenMP 'thread_limit' clause.
1963   ///
1964   /// By default, performs semantic analysis to build the new statement.
1965   /// Subclasses may override this routine to provide different behavior.
1966   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1967                                          SourceLocation StartLoc,
1968                                          SourceLocation LParenLoc,
1969                                          SourceLocation EndLoc) {
1970     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1971                                                   LParenLoc, EndLoc);
1972   }
1973 
1974   /// Build a new OpenMP 'priority' clause.
1975   ///
1976   /// By default, performs semantic analysis to build the new statement.
1977   /// Subclasses may override this routine to provide different behavior.
1978   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1979                                       SourceLocation LParenLoc,
1980                                       SourceLocation EndLoc) {
1981     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1982                                                EndLoc);
1983   }
1984 
1985   /// Build a new OpenMP 'grainsize' clause.
1986   ///
1987   /// By default, performs semantic analysis to build the new statement.
1988   /// Subclasses may override this routine to provide different behavior.
1989   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1990                                        SourceLocation LParenLoc,
1991                                        SourceLocation EndLoc) {
1992     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1993                                                 EndLoc);
1994   }
1995 
1996   /// Build a new OpenMP 'num_tasks' clause.
1997   ///
1998   /// By default, performs semantic analysis to build the new statement.
1999   /// Subclasses may override this routine to provide different behavior.
2000   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
2001                                       SourceLocation LParenLoc,
2002                                       SourceLocation EndLoc) {
2003     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
2004                                                EndLoc);
2005   }
2006 
2007   /// Build a new OpenMP 'hint' clause.
2008   ///
2009   /// By default, performs semantic analysis to build the new statement.
2010   /// Subclasses may override this routine to provide different behavior.
2011   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2012                                   SourceLocation LParenLoc,
2013                                   SourceLocation EndLoc) {
2014     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2015   }
2016 
2017   /// Build a new OpenMP 'detach' clause.
2018   ///
2019   /// By default, performs semantic analysis to build the new statement.
2020   /// Subclasses may override this routine to provide different behavior.
2021   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2022                                     SourceLocation LParenLoc,
2023                                     SourceLocation EndLoc) {
2024     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2025   }
2026 
2027   /// Build a new OpenMP 'dist_schedule' clause.
2028   ///
2029   /// By default, performs semantic analysis to build the new OpenMP clause.
2030   /// Subclasses may override this routine to provide different behavior.
2031   OMPClause *
2032   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2033                                Expr *ChunkSize, SourceLocation StartLoc,
2034                                SourceLocation LParenLoc, SourceLocation KindLoc,
2035                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2036     return getSema().ActOnOpenMPDistScheduleClause(
2037         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2038   }
2039 
2040   /// Build a new OpenMP 'to' clause.
2041   ///
2042   /// By default, performs semantic analysis to build the new statement.
2043   /// Subclasses may override this routine to provide different behavior.
2044   OMPClause *
2045   RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2046                      ArrayRef<SourceLocation> MotionModifiersLoc,
2047                      CXXScopeSpec &MapperIdScopeSpec,
2048                      DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2049                      ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2050                      ArrayRef<Expr *> UnresolvedMappers) {
2051     return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2052                                          MapperIdScopeSpec, MapperId, ColonLoc,
2053                                          VarList, Locs, UnresolvedMappers);
2054   }
2055 
2056   /// Build a new OpenMP 'from' clause.
2057   ///
2058   /// By default, performs semantic analysis to build the new statement.
2059   /// Subclasses may override this routine to provide different behavior.
2060   OMPClause *
2061   RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2062                        ArrayRef<SourceLocation> MotionModifiersLoc,
2063                        CXXScopeSpec &MapperIdScopeSpec,
2064                        DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2065                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2066                        ArrayRef<Expr *> UnresolvedMappers) {
2067     return getSema().ActOnOpenMPFromClause(
2068         MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2069         ColonLoc, VarList, Locs, UnresolvedMappers);
2070   }
2071 
2072   /// Build a new OpenMP 'use_device_ptr' clause.
2073   ///
2074   /// By default, performs semantic analysis to build the new OpenMP clause.
2075   /// Subclasses may override this routine to provide different behavior.
2076   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2077                                           const OMPVarListLocTy &Locs) {
2078     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2079   }
2080 
2081   /// Build a new OpenMP 'use_device_addr' clause.
2082   ///
2083   /// By default, performs semantic analysis to build the new OpenMP clause.
2084   /// Subclasses may override this routine to provide different behavior.
2085   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2086                                            const OMPVarListLocTy &Locs) {
2087     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2088   }
2089 
2090   /// Build a new OpenMP 'is_device_ptr' clause.
2091   ///
2092   /// By default, performs semantic analysis to build the new OpenMP clause.
2093   /// Subclasses may override this routine to provide different behavior.
2094   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2095                                          const OMPVarListLocTy &Locs) {
2096     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2097   }
2098 
2099   /// Build a new OpenMP 'defaultmap' clause.
2100   ///
2101   /// By default, performs semantic analysis to build the new OpenMP clause.
2102   /// Subclasses may override this routine to provide different behavior.
2103   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2104                                         OpenMPDefaultmapClauseKind Kind,
2105                                         SourceLocation StartLoc,
2106                                         SourceLocation LParenLoc,
2107                                         SourceLocation MLoc,
2108                                         SourceLocation KindLoc,
2109                                         SourceLocation EndLoc) {
2110     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2111                                                  MLoc, KindLoc, EndLoc);
2112   }
2113 
2114   /// Build a new OpenMP 'nontemporal' clause.
2115   ///
2116   /// By default, performs semantic analysis to build the new OpenMP clause.
2117   /// Subclasses may override this routine to provide different behavior.
2118   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2119                                          SourceLocation StartLoc,
2120                                          SourceLocation LParenLoc,
2121                                          SourceLocation EndLoc) {
2122     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2123                                                   EndLoc);
2124   }
2125 
2126   /// Build a new OpenMP 'inclusive' clause.
2127   ///
2128   /// By default, performs semantic analysis to build the new OpenMP clause.
2129   /// Subclasses may override this routine to provide different behavior.
2130   OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2131                                        SourceLocation StartLoc,
2132                                        SourceLocation LParenLoc,
2133                                        SourceLocation EndLoc) {
2134     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2135                                                 EndLoc);
2136   }
2137 
2138   /// Build a new OpenMP 'exclusive' clause.
2139   ///
2140   /// By default, performs semantic analysis to build the new OpenMP clause.
2141   /// Subclasses may override this routine to provide different behavior.
2142   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2143                                        SourceLocation StartLoc,
2144                                        SourceLocation LParenLoc,
2145                                        SourceLocation EndLoc) {
2146     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2147                                                 EndLoc);
2148   }
2149 
2150   /// Build a new OpenMP 'uses_allocators' clause.
2151   ///
2152   /// By default, performs semantic analysis to build the new OpenMP clause.
2153   /// Subclasses may override this routine to provide different behavior.
2154   OMPClause *RebuildOMPUsesAllocatorsClause(
2155       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2156       SourceLocation LParenLoc, SourceLocation EndLoc) {
2157     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2158                                                     Data);
2159   }
2160 
2161   /// Build a new OpenMP 'affinity' clause.
2162   ///
2163   /// By default, performs semantic analysis to build the new OpenMP clause.
2164   /// Subclasses may override this routine to provide different behavior.
2165   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2166                                       SourceLocation LParenLoc,
2167                                       SourceLocation ColonLoc,
2168                                       SourceLocation EndLoc, Expr *Modifier,
2169                                       ArrayRef<Expr *> Locators) {
2170     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2171                                                EndLoc, Modifier, Locators);
2172   }
2173 
2174   /// Build a new OpenMP 'order' clause.
2175   ///
2176   /// By default, performs semantic analysis to build the new OpenMP clause.
2177   /// Subclasses may override this routine to provide different behavior.
2178   OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2179                                    SourceLocation KindKwLoc,
2180                                    SourceLocation StartLoc,
2181                                    SourceLocation LParenLoc,
2182                                    SourceLocation EndLoc) {
2183     return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2184                                             LParenLoc, EndLoc);
2185   }
2186 
2187   /// Build a new OpenMP 'init' clause.
2188   ///
2189   /// By default, performs semantic analysis to build the new OpenMP clause.
2190   /// Subclasses may override this routine to provide different behavior.
2191   OMPClause *RebuildOMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
2192                                   bool IsTarget, bool IsTargetSync,
2193                                   SourceLocation StartLoc,
2194                                   SourceLocation LParenLoc,
2195                                   SourceLocation VarLoc,
2196                                   SourceLocation EndLoc) {
2197     return getSema().ActOnOpenMPInitClause(InteropVar, PrefExprs, IsTarget,
2198                                            IsTargetSync, StartLoc, LParenLoc,
2199                                            VarLoc, EndLoc);
2200   }
2201 
2202   /// Build a new OpenMP 'use' clause.
2203   ///
2204   /// By default, performs semantic analysis to build the new OpenMP clause.
2205   /// Subclasses may override this routine to provide different behavior.
2206   OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2207                                  SourceLocation LParenLoc,
2208                                  SourceLocation VarLoc, SourceLocation EndLoc) {
2209     return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2210                                           VarLoc, EndLoc);
2211   }
2212 
2213   /// Build a new OpenMP 'destroy' clause.
2214   ///
2215   /// By default, performs semantic analysis to build the new OpenMP clause.
2216   /// Subclasses may override this routine to provide different behavior.
2217   OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2218                                      SourceLocation LParenLoc,
2219                                      SourceLocation VarLoc,
2220                                      SourceLocation EndLoc) {
2221     return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2222                                               VarLoc, EndLoc);
2223   }
2224 
2225   /// Build a new OpenMP 'novariants' clause.
2226   ///
2227   /// By default, performs semantic analysis to build the new OpenMP clause.
2228   /// Subclasses may override this routine to provide different behavior.
2229   OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2230                                         SourceLocation StartLoc,
2231                                         SourceLocation LParenLoc,
2232                                         SourceLocation EndLoc) {
2233     return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2234                                                  EndLoc);
2235   }
2236 
2237   /// Build a new OpenMP 'nocontext' clause.
2238   ///
2239   /// By default, performs semantic analysis to build the new OpenMP clause.
2240   /// Subclasses may override this routine to provide different behavior.
2241   OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2242                                        SourceLocation LParenLoc,
2243                                        SourceLocation EndLoc) {
2244     return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2245                                                 EndLoc);
2246   }
2247 
2248   /// Build a new OpenMP 'filter' clause.
2249   ///
2250   /// By default, performs semantic analysis to build the new OpenMP clause.
2251   /// Subclasses may override this routine to provide different behavior.
2252   OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2253                                     SourceLocation LParenLoc,
2254                                     SourceLocation EndLoc) {
2255     return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2256                                              EndLoc);
2257   }
2258 
2259   /// Rebuild the operand to an Objective-C \@synchronized statement.
2260   ///
2261   /// By default, performs semantic analysis to build the new statement.
2262   /// Subclasses may override this routine to provide different behavior.
2263   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2264                                               Expr *object) {
2265     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2266   }
2267 
2268   /// Build a new Objective-C \@synchronized 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 RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2273                                            Expr *Object, Stmt *Body) {
2274     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2275   }
2276 
2277   /// Build a new Objective-C \@autoreleasepool statement.
2278   ///
2279   /// By default, performs semantic analysis to build the new statement.
2280   /// Subclasses may override this routine to provide different behavior.
2281   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2282                                             Stmt *Body) {
2283     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2284   }
2285 
2286   /// Build a new Objective-C fast enumeration statement.
2287   ///
2288   /// By default, performs semantic analysis to build the new statement.
2289   /// Subclasses may override this routine to provide different behavior.
2290   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2291                                           Stmt *Element,
2292                                           Expr *Collection,
2293                                           SourceLocation RParenLoc,
2294                                           Stmt *Body) {
2295     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2296                                                 Element,
2297                                                 Collection,
2298                                                 RParenLoc);
2299     if (ForEachStmt.isInvalid())
2300       return StmtError();
2301 
2302     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2303   }
2304 
2305   /// Build a new C++ exception declaration.
2306   ///
2307   /// By default, performs semantic analysis to build the new decaration.
2308   /// Subclasses may override this routine to provide different behavior.
2309   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2310                                 TypeSourceInfo *Declarator,
2311                                 SourceLocation StartLoc,
2312                                 SourceLocation IdLoc,
2313                                 IdentifierInfo *Id) {
2314     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2315                                                        StartLoc, IdLoc, Id);
2316     if (Var)
2317       getSema().CurContext->addDecl(Var);
2318     return Var;
2319   }
2320 
2321   /// Build a new C++ catch statement.
2322   ///
2323   /// By default, performs semantic analysis to build the new statement.
2324   /// Subclasses may override this routine to provide different behavior.
2325   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2326                                  VarDecl *ExceptionDecl,
2327                                  Stmt *Handler) {
2328     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2329                                                       Handler));
2330   }
2331 
2332   /// Build a new C++ try statement.
2333   ///
2334   /// By default, performs semantic analysis to build the new statement.
2335   /// Subclasses may override this routine to provide different behavior.
2336   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2337                                ArrayRef<Stmt *> Handlers) {
2338     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2339   }
2340 
2341   /// Build a new C++0x range-based for statement.
2342   ///
2343   /// By default, performs semantic analysis to build the new statement.
2344   /// Subclasses may override this routine to provide different behavior.
2345   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2346                                     SourceLocation CoawaitLoc, Stmt *Init,
2347                                     SourceLocation ColonLoc, Stmt *Range,
2348                                     Stmt *Begin, Stmt *End, Expr *Cond,
2349                                     Expr *Inc, Stmt *LoopVar,
2350                                     SourceLocation RParenLoc) {
2351     // If we've just learned that the range is actually an Objective-C
2352     // collection, treat this as an Objective-C fast enumeration loop.
2353     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2354       if (RangeStmt->isSingleDecl()) {
2355         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2356           if (RangeVar->isInvalidDecl())
2357             return StmtError();
2358 
2359           Expr *RangeExpr = RangeVar->getInit();
2360           if (!RangeExpr->isTypeDependent() &&
2361               RangeExpr->getType()->isObjCObjectPointerType()) {
2362             // FIXME: Support init-statements in Objective-C++20 ranged for
2363             // statement.
2364             if (Init) {
2365               return SemaRef.Diag(Init->getBeginLoc(),
2366                                   diag::err_objc_for_range_init_stmt)
2367                          << Init->getSourceRange();
2368             }
2369             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2370                                                         RangeExpr, RParenLoc);
2371           }
2372         }
2373       }
2374     }
2375 
2376     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2377                                           Range, Begin, End, Cond, Inc, LoopVar,
2378                                           RParenLoc, Sema::BFRK_Rebuild);
2379   }
2380 
2381   /// Build a new C++0x range-based for statement.
2382   ///
2383   /// By default, performs semantic analysis to build the new statement.
2384   /// Subclasses may override this routine to provide different behavior.
2385   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2386                                           bool IsIfExists,
2387                                           NestedNameSpecifierLoc QualifierLoc,
2388                                           DeclarationNameInfo NameInfo,
2389                                           Stmt *Nested) {
2390     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2391                                                 QualifierLoc, NameInfo, Nested);
2392   }
2393 
2394   /// Attach body to a C++0x range-based for statement.
2395   ///
2396   /// By default, performs semantic analysis to finish the new statement.
2397   /// Subclasses may override this routine to provide different behavior.
2398   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2399     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2400   }
2401 
2402   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2403                                Stmt *TryBlock, Stmt *Handler) {
2404     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2405   }
2406 
2407   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2408                                   Stmt *Block) {
2409     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2410   }
2411 
2412   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2413     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2414   }
2415 
2416   ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2417                                              SourceLocation LParen,
2418                                              SourceLocation RParen,
2419                                              TypeSourceInfo *TSI) {
2420     return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2421   }
2422 
2423   /// Build a new predefined 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 RebuildPredefinedExpr(SourceLocation Loc,
2428                                    PredefinedExpr::IdentKind IK) {
2429     return getSema().BuildPredefinedExpr(Loc, IK);
2430   }
2431 
2432   /// Build a new expression that references a declaration.
2433   ///
2434   /// By default, performs semantic analysis to build the new expression.
2435   /// Subclasses may override this routine to provide different behavior.
2436   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2437                                         LookupResult &R,
2438                                         bool RequiresADL) {
2439     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2440   }
2441 
2442 
2443   /// Build a new expression that references a declaration.
2444   ///
2445   /// By default, performs semantic analysis to build the new expression.
2446   /// Subclasses may override this routine to provide different behavior.
2447   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2448                                 ValueDecl *VD,
2449                                 const DeclarationNameInfo &NameInfo,
2450                                 NamedDecl *Found,
2451                                 TemplateArgumentListInfo *TemplateArgs) {
2452     CXXScopeSpec SS;
2453     SS.Adopt(QualifierLoc);
2454     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2455                                               TemplateArgs);
2456   }
2457 
2458   /// Build a new expression in parentheses.
2459   ///
2460   /// By default, performs semantic analysis to build the new expression.
2461   /// Subclasses may override this routine to provide different behavior.
2462   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2463                                     SourceLocation RParen) {
2464     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2465   }
2466 
2467   /// Build a new pseudo-destructor expression.
2468   ///
2469   /// By default, performs semantic analysis to build the new expression.
2470   /// Subclasses may override this routine to provide different behavior.
2471   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2472                                             SourceLocation OperatorLoc,
2473                                             bool isArrow,
2474                                             CXXScopeSpec &SS,
2475                                             TypeSourceInfo *ScopeType,
2476                                             SourceLocation CCLoc,
2477                                             SourceLocation TildeLoc,
2478                                         PseudoDestructorTypeStorage Destroyed);
2479 
2480   /// Build a new unary operator expression.
2481   ///
2482   /// By default, performs semantic analysis to build the new expression.
2483   /// Subclasses may override this routine to provide different behavior.
2484   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2485                                         UnaryOperatorKind Opc,
2486                                         Expr *SubExpr) {
2487     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2488   }
2489 
2490   /// Build a new builtin offsetof expression.
2491   ///
2492   /// By default, performs semantic analysis to build the new expression.
2493   /// Subclasses may override this routine to provide different behavior.
2494   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2495                                  TypeSourceInfo *Type,
2496                                  ArrayRef<Sema::OffsetOfComponent> Components,
2497                                  SourceLocation RParenLoc) {
2498     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2499                                           RParenLoc);
2500   }
2501 
2502   /// Build a new sizeof, alignof or vec_step expression with a
2503   /// type argument.
2504   ///
2505   /// By default, performs semantic analysis to build the new expression.
2506   /// Subclasses may override this routine to provide different behavior.
2507   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2508                                          SourceLocation OpLoc,
2509                                          UnaryExprOrTypeTrait ExprKind,
2510                                          SourceRange R) {
2511     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2512   }
2513 
2514   /// Build a new sizeof, alignof or vec step expression with an
2515   /// expression argument.
2516   ///
2517   /// By default, performs semantic analysis to build the new expression.
2518   /// Subclasses may override this routine to provide different behavior.
2519   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2520                                          UnaryExprOrTypeTrait ExprKind,
2521                                          SourceRange R) {
2522     ExprResult Result
2523       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2524     if (Result.isInvalid())
2525       return ExprError();
2526 
2527     return Result;
2528   }
2529 
2530   /// Build a new array subscript expression.
2531   ///
2532   /// By default, performs semantic analysis to build the new expression.
2533   /// Subclasses may override this routine to provide different behavior.
2534   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2535                                              SourceLocation LBracketLoc,
2536                                              Expr *RHS,
2537                                              SourceLocation RBracketLoc) {
2538     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2539                                              LBracketLoc, RHS,
2540                                              RBracketLoc);
2541   }
2542 
2543   /// Build a new matrix subscript expression.
2544   ///
2545   /// By default, performs semantic analysis to build the new expression.
2546   /// Subclasses may override this routine to provide different behavior.
2547   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2548                                         Expr *ColumnIdx,
2549                                         SourceLocation RBracketLoc) {
2550     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2551                                                       RBracketLoc);
2552   }
2553 
2554   /// Build a new array section expression.
2555   ///
2556   /// By default, performs semantic analysis to build the new expression.
2557   /// Subclasses may override this routine to provide different behavior.
2558   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2559                                         Expr *LowerBound,
2560                                         SourceLocation ColonLocFirst,
2561                                         SourceLocation ColonLocSecond,
2562                                         Expr *Length, Expr *Stride,
2563                                         SourceLocation RBracketLoc) {
2564     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2565                                               ColonLocFirst, ColonLocSecond,
2566                                               Length, Stride, RBracketLoc);
2567   }
2568 
2569   /// Build a new array shaping expression.
2570   ///
2571   /// By default, performs semantic analysis to build the new expression.
2572   /// Subclasses may override this routine to provide different behavior.
2573   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2574                                         SourceLocation RParenLoc,
2575                                         ArrayRef<Expr *> Dims,
2576                                         ArrayRef<SourceRange> BracketsRanges) {
2577     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2578                                               BracketsRanges);
2579   }
2580 
2581   /// Build a new iterator expression.
2582   ///
2583   /// By default, performs semantic analysis to build the new expression.
2584   /// Subclasses may override this routine to provide different behavior.
2585   ExprResult RebuildOMPIteratorExpr(
2586       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2587       ArrayRef<Sema::OMPIteratorData> Data) {
2588     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2589                                           LLoc, RLoc, Data);
2590   }
2591 
2592   /// Build a new call expression.
2593   ///
2594   /// By default, performs semantic analysis to build the new expression.
2595   /// Subclasses may override this routine to provide different behavior.
2596   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2597                                    MultiExprArg Args,
2598                                    SourceLocation RParenLoc,
2599                                    Expr *ExecConfig = nullptr) {
2600     return getSema().ActOnCallExpr(
2601         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2602   }
2603 
2604   /// Build a new member access expression.
2605   ///
2606   /// By default, performs semantic analysis to build the new expression.
2607   /// Subclasses may override this routine to provide different behavior.
2608   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2609                                bool isArrow,
2610                                NestedNameSpecifierLoc QualifierLoc,
2611                                SourceLocation TemplateKWLoc,
2612                                const DeclarationNameInfo &MemberNameInfo,
2613                                ValueDecl *Member,
2614                                NamedDecl *FoundDecl,
2615                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2616                                NamedDecl *FirstQualifierInScope) {
2617     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2618                                                                       isArrow);
2619     if (!Member->getDeclName()) {
2620       // We have a reference to an unnamed field.  This is always the
2621       // base of an anonymous struct/union member access, i.e. the
2622       // field is always of record type.
2623       assert(Member->getType()->isRecordType() &&
2624              "unnamed member not of record type?");
2625 
2626       BaseResult =
2627         getSema().PerformObjectMemberConversion(BaseResult.get(),
2628                                                 QualifierLoc.getNestedNameSpecifier(),
2629                                                 FoundDecl, Member);
2630       if (BaseResult.isInvalid())
2631         return ExprError();
2632       Base = BaseResult.get();
2633 
2634       CXXScopeSpec EmptySS;
2635       return getSema().BuildFieldReferenceExpr(
2636           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2637           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2638     }
2639 
2640     CXXScopeSpec SS;
2641     SS.Adopt(QualifierLoc);
2642 
2643     Base = BaseResult.get();
2644     QualType BaseType = Base->getType();
2645 
2646     if (isArrow && !BaseType->isPointerType())
2647       return ExprError();
2648 
2649     // FIXME: this involves duplicating earlier analysis in a lot of
2650     // cases; we should avoid this when possible.
2651     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2652     R.addDecl(FoundDecl);
2653     R.resolveKind();
2654 
2655     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2656                                               SS, TemplateKWLoc,
2657                                               FirstQualifierInScope,
2658                                               R, ExplicitTemplateArgs,
2659                                               /*S*/nullptr);
2660   }
2661 
2662   /// Build a new binary operator expression.
2663   ///
2664   /// By default, performs semantic analysis to build the new expression.
2665   /// Subclasses may override this routine to provide different behavior.
2666   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2667                                          BinaryOperatorKind Opc,
2668                                          Expr *LHS, Expr *RHS) {
2669     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2670   }
2671 
2672   /// Build a new rewritten operator expression.
2673   ///
2674   /// By default, performs semantic analysis to build the new expression.
2675   /// Subclasses may override this routine to provide different behavior.
2676   ExprResult RebuildCXXRewrittenBinaryOperator(
2677       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2678       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2679     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2680                                            RHS, /*RequiresADL*/false);
2681   }
2682 
2683   /// Build a new conditional operator expression.
2684   ///
2685   /// By default, performs semantic analysis to build the new expression.
2686   /// Subclasses may override this routine to provide different behavior.
2687   ExprResult RebuildConditionalOperator(Expr *Cond,
2688                                         SourceLocation QuestionLoc,
2689                                         Expr *LHS,
2690                                         SourceLocation ColonLoc,
2691                                         Expr *RHS) {
2692     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2693                                         LHS, RHS);
2694   }
2695 
2696   /// Build a new C-style cast expression.
2697   ///
2698   /// By default, performs semantic analysis to build the new expression.
2699   /// Subclasses may override this routine to provide different behavior.
2700   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2701                                          TypeSourceInfo *TInfo,
2702                                          SourceLocation RParenLoc,
2703                                          Expr *SubExpr) {
2704     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2705                                          SubExpr);
2706   }
2707 
2708   /// Build a new compound literal expression.
2709   ///
2710   /// By default, performs semantic analysis to build the new expression.
2711   /// Subclasses may override this routine to provide different behavior.
2712   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2713                                               TypeSourceInfo *TInfo,
2714                                               SourceLocation RParenLoc,
2715                                               Expr *Init) {
2716     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2717                                               Init);
2718   }
2719 
2720   /// Build a new extended vector element access expression.
2721   ///
2722   /// By default, performs semantic analysis to build the new expression.
2723   /// Subclasses may override this routine to provide different behavior.
2724   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2725                                                SourceLocation OpLoc,
2726                                                SourceLocation AccessorLoc,
2727                                                IdentifierInfo &Accessor) {
2728 
2729     CXXScopeSpec SS;
2730     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2731     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2732                                               OpLoc, /*IsArrow*/ false,
2733                                               SS, SourceLocation(),
2734                                               /*FirstQualifierInScope*/ nullptr,
2735                                               NameInfo,
2736                                               /* TemplateArgs */ nullptr,
2737                                               /*S*/ nullptr);
2738   }
2739 
2740   /// Build a new initializer list expression.
2741   ///
2742   /// By default, performs semantic analysis to build the new expression.
2743   /// Subclasses may override this routine to provide different behavior.
2744   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2745                              MultiExprArg Inits,
2746                              SourceLocation RBraceLoc) {
2747     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2748   }
2749 
2750   /// Build a new designated initializer expression.
2751   ///
2752   /// By default, performs semantic analysis to build the new expression.
2753   /// Subclasses may override this routine to provide different behavior.
2754   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2755                                              MultiExprArg ArrayExprs,
2756                                              SourceLocation EqualOrColonLoc,
2757                                              bool GNUSyntax,
2758                                              Expr *Init) {
2759     ExprResult Result
2760       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2761                                            Init);
2762     if (Result.isInvalid())
2763       return ExprError();
2764 
2765     return Result;
2766   }
2767 
2768   /// Build a new value-initialized expression.
2769   ///
2770   /// By default, builds the implicit value initialization without performing
2771   /// any semantic analysis. Subclasses may override this routine to provide
2772   /// different behavior.
2773   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2774     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2775   }
2776 
2777   /// Build a new \c va_arg expression.
2778   ///
2779   /// By default, performs semantic analysis to build the new expression.
2780   /// Subclasses may override this routine to provide different behavior.
2781   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2782                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2783                                     SourceLocation RParenLoc) {
2784     return getSema().BuildVAArgExpr(BuiltinLoc,
2785                                     SubExpr, TInfo,
2786                                     RParenLoc);
2787   }
2788 
2789   /// Build a new expression list in parentheses.
2790   ///
2791   /// By default, performs semantic analysis to build the new expression.
2792   /// Subclasses may override this routine to provide different behavior.
2793   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2794                                   MultiExprArg SubExprs,
2795                                   SourceLocation RParenLoc) {
2796     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2797   }
2798 
2799   /// Build a new address-of-label expression.
2800   ///
2801   /// By default, performs semantic analysis, using the name of the label
2802   /// rather than attempting to map the label statement itself.
2803   /// Subclasses may override this routine to provide different behavior.
2804   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2805                                   SourceLocation LabelLoc, LabelDecl *Label) {
2806     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2807   }
2808 
2809   /// Build a new GNU statement expression.
2810   ///
2811   /// By default, performs semantic analysis to build the new expression.
2812   /// Subclasses may override this routine to provide different behavior.
2813   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2814                              SourceLocation RParenLoc, unsigned TemplateDepth) {
2815     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2816                                    TemplateDepth);
2817   }
2818 
2819   /// Build a new __builtin_choose_expr expression.
2820   ///
2821   /// By default, performs semantic analysis to build the new expression.
2822   /// Subclasses may override this routine to provide different behavior.
2823   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2824                                      Expr *Cond, Expr *LHS, Expr *RHS,
2825                                      SourceLocation RParenLoc) {
2826     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2827                                    Cond, LHS, RHS,
2828                                    RParenLoc);
2829   }
2830 
2831   /// Build a new generic selection expression.
2832   ///
2833   /// By default, performs semantic analysis to build the new expression.
2834   /// Subclasses may override this routine to provide different behavior.
2835   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2836                                          SourceLocation DefaultLoc,
2837                                          SourceLocation RParenLoc,
2838                                          Expr *ControllingExpr,
2839                                          ArrayRef<TypeSourceInfo *> Types,
2840                                          ArrayRef<Expr *> Exprs) {
2841     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2842                                                 ControllingExpr, Types, Exprs);
2843   }
2844 
2845   /// Build a new overloaded operator call expression.
2846   ///
2847   /// By default, performs semantic analysis to build the new expression.
2848   /// The semantic analysis provides the behavior of template instantiation,
2849   /// copying with transformations that turn what looks like an overloaded
2850   /// operator call into a use of a builtin operator, performing
2851   /// argument-dependent lookup, etc. Subclasses may override this routine to
2852   /// provide different behavior.
2853   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2854                                               SourceLocation OpLoc,
2855                                               Expr *Callee,
2856                                               Expr *First,
2857                                               Expr *Second);
2858 
2859   /// Build a new C++ "named" cast expression, such as static_cast or
2860   /// reinterpret_cast.
2861   ///
2862   /// By default, this routine dispatches to one of the more-specific routines
2863   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2864   /// Subclasses may override this routine to provide different behavior.
2865   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2866                                            Stmt::StmtClass Class,
2867                                            SourceLocation LAngleLoc,
2868                                            TypeSourceInfo *TInfo,
2869                                            SourceLocation RAngleLoc,
2870                                            SourceLocation LParenLoc,
2871                                            Expr *SubExpr,
2872                                            SourceLocation RParenLoc) {
2873     switch (Class) {
2874     case Stmt::CXXStaticCastExprClass:
2875       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2876                                                    RAngleLoc, LParenLoc,
2877                                                    SubExpr, RParenLoc);
2878 
2879     case Stmt::CXXDynamicCastExprClass:
2880       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2881                                                     RAngleLoc, LParenLoc,
2882                                                     SubExpr, RParenLoc);
2883 
2884     case Stmt::CXXReinterpretCastExprClass:
2885       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2886                                                         RAngleLoc, LParenLoc,
2887                                                         SubExpr,
2888                                                         RParenLoc);
2889 
2890     case Stmt::CXXConstCastExprClass:
2891       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2892                                                    RAngleLoc, LParenLoc,
2893                                                    SubExpr, RParenLoc);
2894 
2895     case Stmt::CXXAddrspaceCastExprClass:
2896       return getDerived().RebuildCXXAddrspaceCastExpr(
2897           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
2898 
2899     default:
2900       llvm_unreachable("Invalid C++ named cast");
2901     }
2902   }
2903 
2904   /// Build a new C++ static_cast expression.
2905   ///
2906   /// By default, performs semantic analysis to build the new expression.
2907   /// Subclasses may override this routine to provide different behavior.
2908   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2909                                             SourceLocation LAngleLoc,
2910                                             TypeSourceInfo *TInfo,
2911                                             SourceLocation RAngleLoc,
2912                                             SourceLocation LParenLoc,
2913                                             Expr *SubExpr,
2914                                             SourceLocation RParenLoc) {
2915     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2916                                        TInfo, SubExpr,
2917                                        SourceRange(LAngleLoc, RAngleLoc),
2918                                        SourceRange(LParenLoc, RParenLoc));
2919   }
2920 
2921   /// Build a new C++ dynamic_cast 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 RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2926                                              SourceLocation LAngleLoc,
2927                                              TypeSourceInfo *TInfo,
2928                                              SourceLocation RAngleLoc,
2929                                              SourceLocation LParenLoc,
2930                                              Expr *SubExpr,
2931                                              SourceLocation RParenLoc) {
2932     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2933                                        TInfo, SubExpr,
2934                                        SourceRange(LAngleLoc, RAngleLoc),
2935                                        SourceRange(LParenLoc, RParenLoc));
2936   }
2937 
2938   /// Build a new C++ reinterpret_cast expression.
2939   ///
2940   /// By default, performs semantic analysis to build the new expression.
2941   /// Subclasses may override this routine to provide different behavior.
2942   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2943                                                  SourceLocation LAngleLoc,
2944                                                  TypeSourceInfo *TInfo,
2945                                                  SourceLocation RAngleLoc,
2946                                                  SourceLocation LParenLoc,
2947                                                  Expr *SubExpr,
2948                                                  SourceLocation RParenLoc) {
2949     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2950                                        TInfo, SubExpr,
2951                                        SourceRange(LAngleLoc, RAngleLoc),
2952                                        SourceRange(LParenLoc, RParenLoc));
2953   }
2954 
2955   /// Build a new C++ const_cast expression.
2956   ///
2957   /// By default, performs semantic analysis to build the new expression.
2958   /// Subclasses may override this routine to provide different behavior.
2959   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2960                                            SourceLocation LAngleLoc,
2961                                            TypeSourceInfo *TInfo,
2962                                            SourceLocation RAngleLoc,
2963                                            SourceLocation LParenLoc,
2964                                            Expr *SubExpr,
2965                                            SourceLocation RParenLoc) {
2966     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2967                                        TInfo, SubExpr,
2968                                        SourceRange(LAngleLoc, RAngleLoc),
2969                                        SourceRange(LParenLoc, RParenLoc));
2970   }
2971 
2972   ExprResult
2973   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
2974                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
2975                               SourceLocation LParenLoc, Expr *SubExpr,
2976                               SourceLocation RParenLoc) {
2977     return getSema().BuildCXXNamedCast(
2978         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
2979         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
2980   }
2981 
2982   /// Build a new C++ functional-style cast 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 RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2987                                           SourceLocation LParenLoc,
2988                                           Expr *Sub,
2989                                           SourceLocation RParenLoc,
2990                                           bool ListInitialization) {
2991     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2992                                                MultiExprArg(&Sub, 1), RParenLoc,
2993                                                ListInitialization);
2994   }
2995 
2996   /// Build a new C++ __builtin_bit_cast expression.
2997   ///
2998   /// By default, performs semantic analysis to build the new expression.
2999   /// Subclasses may override this routine to provide different behavior.
3000   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3001                                        TypeSourceInfo *TSI, Expr *Sub,
3002                                        SourceLocation RParenLoc) {
3003     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3004   }
3005 
3006   /// Build a new C++ typeid(type) expression.
3007   ///
3008   /// By default, performs semantic analysis to build the new expression.
3009   /// Subclasses may override this routine to provide different behavior.
3010   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3011                                         SourceLocation TypeidLoc,
3012                                         TypeSourceInfo *Operand,
3013                                         SourceLocation RParenLoc) {
3014     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3015                                     RParenLoc);
3016   }
3017 
3018 
3019   /// Build a new C++ typeid(expr) expression.
3020   ///
3021   /// By default, performs semantic analysis to build the new expression.
3022   /// Subclasses may override this routine to provide different behavior.
3023   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3024                                         SourceLocation TypeidLoc,
3025                                         Expr *Operand,
3026                                         SourceLocation RParenLoc) {
3027     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3028                                     RParenLoc);
3029   }
3030 
3031   /// Build a new C++ __uuidof(type) expression.
3032   ///
3033   /// By default, performs semantic analysis to build the new expression.
3034   /// Subclasses may override this routine to provide different behavior.
3035   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3036                                   TypeSourceInfo *Operand,
3037                                   SourceLocation RParenLoc) {
3038     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3039   }
3040 
3041   /// Build a new C++ __uuidof(expr) expression.
3042   ///
3043   /// By default, performs semantic analysis to build the new expression.
3044   /// Subclasses may override this routine to provide different behavior.
3045   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3046                                   Expr *Operand, SourceLocation RParenLoc) {
3047     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3048   }
3049 
3050   /// Build a new C++ "this" expression.
3051   ///
3052   /// By default, builds a new "this" expression without performing any
3053   /// semantic analysis. Subclasses may override this routine to provide
3054   /// different behavior.
3055   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3056                                 QualType ThisType,
3057                                 bool isImplicit) {
3058     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3059   }
3060 
3061   /// Build a new C++ throw expression.
3062   ///
3063   /// By default, performs semantic analysis to build the new expression.
3064   /// Subclasses may override this routine to provide different behavior.
3065   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3066                                  bool IsThrownVariableInScope) {
3067     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3068   }
3069 
3070   /// Build a new C++ default-argument expression.
3071   ///
3072   /// By default, builds a new default-argument expression, which does not
3073   /// require any semantic analysis. Subclasses may override this routine to
3074   /// provide different behavior.
3075   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
3076     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3077                                      getSema().CurContext);
3078   }
3079 
3080   /// Build a new C++11 default-initialization expression.
3081   ///
3082   /// By default, builds a new default field initialization expression, which
3083   /// does not require any semantic analysis. Subclasses may override this
3084   /// routine to provide different behavior.
3085   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3086                                        FieldDecl *Field) {
3087     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
3088                                       getSema().CurContext);
3089   }
3090 
3091   /// Build a new C++ zero-initialization 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 RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3096                                            SourceLocation LParenLoc,
3097                                            SourceLocation RParenLoc) {
3098     return getSema().BuildCXXTypeConstructExpr(
3099         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
3100   }
3101 
3102   /// Build a new C++ "new" expression.
3103   ///
3104   /// By default, performs semantic analysis to build the new expression.
3105   /// Subclasses may override this routine to provide different behavior.
3106   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
3107                                bool UseGlobal,
3108                                SourceLocation PlacementLParen,
3109                                MultiExprArg PlacementArgs,
3110                                SourceLocation PlacementRParen,
3111                                SourceRange TypeIdParens,
3112                                QualType AllocatedType,
3113                                TypeSourceInfo *AllocatedTypeInfo,
3114                                Optional<Expr *> ArraySize,
3115                                SourceRange DirectInitRange,
3116                                Expr *Initializer) {
3117     return getSema().BuildCXXNew(StartLoc, UseGlobal,
3118                                  PlacementLParen,
3119                                  PlacementArgs,
3120                                  PlacementRParen,
3121                                  TypeIdParens,
3122                                  AllocatedType,
3123                                  AllocatedTypeInfo,
3124                                  ArraySize,
3125                                  DirectInitRange,
3126                                  Initializer);
3127   }
3128 
3129   /// Build a new C++ "delete" expression.
3130   ///
3131   /// By default, performs semantic analysis to build the new expression.
3132   /// Subclasses may override this routine to provide different behavior.
3133   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3134                                         bool IsGlobalDelete,
3135                                         bool IsArrayForm,
3136                                         Expr *Operand) {
3137     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3138                                     Operand);
3139   }
3140 
3141   /// Build a new type trait expression.
3142   ///
3143   /// By default, performs semantic analysis to build the new expression.
3144   /// Subclasses may override this routine to provide different behavior.
3145   ExprResult RebuildTypeTrait(TypeTrait Trait,
3146                               SourceLocation StartLoc,
3147                               ArrayRef<TypeSourceInfo *> Args,
3148                               SourceLocation RParenLoc) {
3149     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3150   }
3151 
3152   /// Build a new array type trait expression.
3153   ///
3154   /// By default, performs semantic analysis to build the new expression.
3155   /// Subclasses may override this routine to provide different behavior.
3156   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3157                                    SourceLocation StartLoc,
3158                                    TypeSourceInfo *TSInfo,
3159                                    Expr *DimExpr,
3160                                    SourceLocation RParenLoc) {
3161     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3162   }
3163 
3164   /// Build a new expression trait expression.
3165   ///
3166   /// By default, performs semantic analysis to build the new expression.
3167   /// Subclasses may override this routine to provide different behavior.
3168   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3169                                    SourceLocation StartLoc,
3170                                    Expr *Queried,
3171                                    SourceLocation RParenLoc) {
3172     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3173   }
3174 
3175   /// Build a new (previously unresolved) declaration reference
3176   /// expression.
3177   ///
3178   /// By default, performs semantic analysis to build the new expression.
3179   /// Subclasses may override this routine to provide different behavior.
3180   ExprResult RebuildDependentScopeDeclRefExpr(
3181                                           NestedNameSpecifierLoc QualifierLoc,
3182                                           SourceLocation TemplateKWLoc,
3183                                        const DeclarationNameInfo &NameInfo,
3184                               const TemplateArgumentListInfo *TemplateArgs,
3185                                           bool IsAddressOfOperand,
3186                                           TypeSourceInfo **RecoveryTSI) {
3187     CXXScopeSpec SS;
3188     SS.Adopt(QualifierLoc);
3189 
3190     if (TemplateArgs || TemplateKWLoc.isValid())
3191       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3192                                                     TemplateArgs);
3193 
3194     return getSema().BuildQualifiedDeclarationNameExpr(
3195         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3196   }
3197 
3198   /// Build a new template-id expression.
3199   ///
3200   /// By default, performs semantic analysis to build the new expression.
3201   /// Subclasses may override this routine to provide different behavior.
3202   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3203                                    SourceLocation TemplateKWLoc,
3204                                    LookupResult &R,
3205                                    bool RequiresADL,
3206                               const TemplateArgumentListInfo *TemplateArgs) {
3207     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3208                                          TemplateArgs);
3209   }
3210 
3211   /// Build a new object-construction expression.
3212   ///
3213   /// By default, performs semantic analysis to build the new expression.
3214   /// Subclasses may override this routine to provide different behavior.
3215   ExprResult RebuildCXXConstructExpr(QualType T,
3216                                      SourceLocation Loc,
3217                                      CXXConstructorDecl *Constructor,
3218                                      bool IsElidable,
3219                                      MultiExprArg Args,
3220                                      bool HadMultipleCandidates,
3221                                      bool ListInitialization,
3222                                      bool StdInitListInitialization,
3223                                      bool RequiresZeroInit,
3224                              CXXConstructExpr::ConstructionKind ConstructKind,
3225                                      SourceRange ParenRange) {
3226     // Reconstruct the constructor we originally found, which might be
3227     // different if this is a call to an inherited constructor.
3228     CXXConstructorDecl *FoundCtor = Constructor;
3229     if (Constructor->isInheritingConstructor())
3230       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3231 
3232     SmallVector<Expr *, 8> ConvertedArgs;
3233     if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3234                                           ConvertedArgs))
3235       return ExprError();
3236 
3237     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3238                                            IsElidable,
3239                                            ConvertedArgs,
3240                                            HadMultipleCandidates,
3241                                            ListInitialization,
3242                                            StdInitListInitialization,
3243                                            RequiresZeroInit, ConstructKind,
3244                                            ParenRange);
3245   }
3246 
3247   /// Build a new implicit construction via inherited constructor
3248   /// expression.
3249   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3250                                              CXXConstructorDecl *Constructor,
3251                                              bool ConstructsVBase,
3252                                              bool InheritedFromVBase) {
3253     return new (getSema().Context) CXXInheritedCtorInitExpr(
3254         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3255   }
3256 
3257   /// Build a new object-construction expression.
3258   ///
3259   /// By default, performs semantic analysis to build the new expression.
3260   /// Subclasses may override this routine to provide different behavior.
3261   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3262                                            SourceLocation LParenOrBraceLoc,
3263                                            MultiExprArg Args,
3264                                            SourceLocation RParenOrBraceLoc,
3265                                            bool ListInitialization) {
3266     return getSema().BuildCXXTypeConstructExpr(
3267         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3268   }
3269 
3270   /// Build a new object-construction expression.
3271   ///
3272   /// By default, performs semantic analysis to build the new expression.
3273   /// Subclasses may override this routine to provide different behavior.
3274   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3275                                                SourceLocation LParenLoc,
3276                                                MultiExprArg Args,
3277                                                SourceLocation RParenLoc,
3278                                                bool ListInitialization) {
3279     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3280                                                RParenLoc, ListInitialization);
3281   }
3282 
3283   /// Build a new member reference expression.
3284   ///
3285   /// By default, performs semantic analysis to build the new expression.
3286   /// Subclasses may override this routine to provide different behavior.
3287   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3288                                                 QualType BaseType,
3289                                                 bool IsArrow,
3290                                                 SourceLocation OperatorLoc,
3291                                           NestedNameSpecifierLoc QualifierLoc,
3292                                                 SourceLocation TemplateKWLoc,
3293                                             NamedDecl *FirstQualifierInScope,
3294                                    const DeclarationNameInfo &MemberNameInfo,
3295                               const TemplateArgumentListInfo *TemplateArgs) {
3296     CXXScopeSpec SS;
3297     SS.Adopt(QualifierLoc);
3298 
3299     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3300                                             OperatorLoc, IsArrow,
3301                                             SS, TemplateKWLoc,
3302                                             FirstQualifierInScope,
3303                                             MemberNameInfo,
3304                                             TemplateArgs, /*S*/nullptr);
3305   }
3306 
3307   /// Build a new member reference 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 RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3312                                          SourceLocation OperatorLoc,
3313                                          bool IsArrow,
3314                                          NestedNameSpecifierLoc QualifierLoc,
3315                                          SourceLocation TemplateKWLoc,
3316                                          NamedDecl *FirstQualifierInScope,
3317                                          LookupResult &R,
3318                                 const TemplateArgumentListInfo *TemplateArgs) {
3319     CXXScopeSpec SS;
3320     SS.Adopt(QualifierLoc);
3321 
3322     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3323                                             OperatorLoc, IsArrow,
3324                                             SS, TemplateKWLoc,
3325                                             FirstQualifierInScope,
3326                                             R, TemplateArgs, /*S*/nullptr);
3327   }
3328 
3329   /// Build a new noexcept expression.
3330   ///
3331   /// By default, performs semantic analysis to build the new expression.
3332   /// Subclasses may override this routine to provide different behavior.
3333   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3334     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3335   }
3336 
3337   /// Build a new expression to compute the length of a parameter pack.
3338   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3339                                    NamedDecl *Pack,
3340                                    SourceLocation PackLoc,
3341                                    SourceLocation RParenLoc,
3342                                    Optional<unsigned> Length,
3343                                    ArrayRef<TemplateArgument> PartialArgs) {
3344     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3345                                   RParenLoc, Length, PartialArgs);
3346   }
3347 
3348   /// Build a new expression representing a call to a source location
3349   ///  builtin.
3350   ///
3351   /// By default, performs semantic analysis to build the new expression.
3352   /// Subclasses may override this routine to provide different behavior.
3353   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3354                                   SourceLocation BuiltinLoc,
3355                                   SourceLocation RPLoc,
3356                                   DeclContext *ParentContext) {
3357     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3358   }
3359 
3360   /// Build a new Objective-C boxed expression.
3361   ///
3362   /// By default, performs semantic analysis to build the new expression.
3363   /// Subclasses may override this routine to provide different behavior.
3364   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3365       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3366       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3367       TemplateArgumentListInfo *TALI) {
3368     CXXScopeSpec SS;
3369     SS.Adopt(NNS);
3370     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3371                                                          ConceptNameInfo,
3372                                                          FoundDecl,
3373                                                          NamedConcept, TALI);
3374     if (Result.isInvalid())
3375       return ExprError();
3376     return Result;
3377   }
3378 
3379   /// \brief Build a new requires expression.
3380   ///
3381   /// By default, performs semantic analysis to build the new expression.
3382   /// Subclasses may override this routine to provide different behavior.
3383   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3384                                  RequiresExprBodyDecl *Body,
3385                                  ArrayRef<ParmVarDecl *> LocalParameters,
3386                                  ArrayRef<concepts::Requirement *> Requirements,
3387                                  SourceLocation ClosingBraceLoc) {
3388     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3389                                 LocalParameters, Requirements, ClosingBraceLoc);
3390   }
3391 
3392   concepts::TypeRequirement *
3393   RebuildTypeRequirement(
3394       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3395     return SemaRef.BuildTypeRequirement(SubstDiag);
3396   }
3397 
3398   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3399     return SemaRef.BuildTypeRequirement(T);
3400   }
3401 
3402   concepts::ExprRequirement *
3403   RebuildExprRequirement(
3404       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3405       SourceLocation NoexceptLoc,
3406       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3407     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3408                                         std::move(Ret));
3409   }
3410 
3411   concepts::ExprRequirement *
3412   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3413                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3414     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3415                                         std::move(Ret));
3416   }
3417 
3418   concepts::NestedRequirement *
3419   RebuildNestedRequirement(
3420       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3421     return SemaRef.BuildNestedRequirement(SubstDiag);
3422   }
3423 
3424   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3425     return SemaRef.BuildNestedRequirement(Constraint);
3426   }
3427 
3428   /// \brief Build a new Objective-C boxed expression.
3429   ///
3430   /// By default, performs semantic analysis to build the new expression.
3431   /// Subclasses may override this routine to provide different behavior.
3432   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3433     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3434   }
3435 
3436   /// Build a new Objective-C array literal.
3437   ///
3438   /// By default, performs semantic analysis to build the new expression.
3439   /// Subclasses may override this routine to provide different behavior.
3440   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3441                                      Expr **Elements, unsigned NumElements) {
3442     return getSema().BuildObjCArrayLiteral(Range,
3443                                            MultiExprArg(Elements, NumElements));
3444   }
3445 
3446   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3447                                          Expr *Base, Expr *Key,
3448                                          ObjCMethodDecl *getterMethod,
3449                                          ObjCMethodDecl *setterMethod) {
3450     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3451                                                    getterMethod, setterMethod);
3452   }
3453 
3454   /// Build a new Objective-C dictionary literal.
3455   ///
3456   /// By default, performs semantic analysis to build the new expression.
3457   /// Subclasses may override this routine to provide different behavior.
3458   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3459                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3460     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3461   }
3462 
3463   /// Build a new Objective-C \@encode expression.
3464   ///
3465   /// By default, performs semantic analysis to build the new expression.
3466   /// Subclasses may override this routine to provide different behavior.
3467   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3468                                          TypeSourceInfo *EncodeTypeInfo,
3469                                          SourceLocation RParenLoc) {
3470     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3471   }
3472 
3473   /// Build a new Objective-C class message.
3474   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3475                                           Selector Sel,
3476                                           ArrayRef<SourceLocation> SelectorLocs,
3477                                           ObjCMethodDecl *Method,
3478                                           SourceLocation LBracLoc,
3479                                           MultiExprArg Args,
3480                                           SourceLocation RBracLoc) {
3481     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3482                                      ReceiverTypeInfo->getType(),
3483                                      /*SuperLoc=*/SourceLocation(),
3484                                      Sel, Method, LBracLoc, SelectorLocs,
3485                                      RBracLoc, Args);
3486   }
3487 
3488   /// Build a new Objective-C instance message.
3489   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3490                                           Selector Sel,
3491                                           ArrayRef<SourceLocation> SelectorLocs,
3492                                           ObjCMethodDecl *Method,
3493                                           SourceLocation LBracLoc,
3494                                           MultiExprArg Args,
3495                                           SourceLocation RBracLoc) {
3496     return SemaRef.BuildInstanceMessage(Receiver,
3497                                         Receiver->getType(),
3498                                         /*SuperLoc=*/SourceLocation(),
3499                                         Sel, Method, LBracLoc, SelectorLocs,
3500                                         RBracLoc, Args);
3501   }
3502 
3503   /// Build a new Objective-C instance/class message to 'super'.
3504   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3505                                     Selector Sel,
3506                                     ArrayRef<SourceLocation> SelectorLocs,
3507                                     QualType SuperType,
3508                                     ObjCMethodDecl *Method,
3509                                     SourceLocation LBracLoc,
3510                                     MultiExprArg Args,
3511                                     SourceLocation RBracLoc) {
3512     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3513                                           SuperType,
3514                                           SuperLoc,
3515                                           Sel, Method, LBracLoc, SelectorLocs,
3516                                           RBracLoc, Args)
3517                                       : SemaRef.BuildClassMessage(nullptr,
3518                                           SuperType,
3519                                           SuperLoc,
3520                                           Sel, Method, LBracLoc, SelectorLocs,
3521                                           RBracLoc, Args);
3522 
3523 
3524   }
3525 
3526   /// Build a new Objective-C ivar reference expression.
3527   ///
3528   /// By default, performs semantic analysis to build the new expression.
3529   /// Subclasses may override this routine to provide different behavior.
3530   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3531                                           SourceLocation IvarLoc,
3532                                           bool IsArrow, bool IsFreeIvar) {
3533     CXXScopeSpec SS;
3534     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3535     ExprResult Result = getSema().BuildMemberReferenceExpr(
3536         BaseArg, BaseArg->getType(),
3537         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3538         /*FirstQualifierInScope=*/nullptr, NameInfo,
3539         /*TemplateArgs=*/nullptr,
3540         /*S=*/nullptr);
3541     if (IsFreeIvar && Result.isUsable())
3542       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3543     return Result;
3544   }
3545 
3546   /// Build a new Objective-C property reference expression.
3547   ///
3548   /// By default, performs semantic analysis to build the new expression.
3549   /// Subclasses may override this routine to provide different behavior.
3550   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3551                                         ObjCPropertyDecl *Property,
3552                                         SourceLocation PropertyLoc) {
3553     CXXScopeSpec SS;
3554     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3555     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3556                                               /*FIXME:*/PropertyLoc,
3557                                               /*IsArrow=*/false,
3558                                               SS, SourceLocation(),
3559                                               /*FirstQualifierInScope=*/nullptr,
3560                                               NameInfo,
3561                                               /*TemplateArgs=*/nullptr,
3562                                               /*S=*/nullptr);
3563   }
3564 
3565   /// Build a new Objective-C property reference expression.
3566   ///
3567   /// By default, performs semantic analysis to build the new expression.
3568   /// Subclasses may override this routine to provide different behavior.
3569   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3570                                         ObjCMethodDecl *Getter,
3571                                         ObjCMethodDecl *Setter,
3572                                         SourceLocation PropertyLoc) {
3573     // Since these expressions can only be value-dependent, we do not
3574     // need to perform semantic analysis again.
3575     return Owned(
3576       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3577                                                   VK_LValue, OK_ObjCProperty,
3578                                                   PropertyLoc, Base));
3579   }
3580 
3581   /// Build a new Objective-C "isa" expression.
3582   ///
3583   /// By default, performs semantic analysis to build the new expression.
3584   /// Subclasses may override this routine to provide different behavior.
3585   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3586                                 SourceLocation OpLoc, bool IsArrow) {
3587     CXXScopeSpec SS;
3588     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3589     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3590                                               OpLoc, IsArrow,
3591                                               SS, SourceLocation(),
3592                                               /*FirstQualifierInScope=*/nullptr,
3593                                               NameInfo,
3594                                               /*TemplateArgs=*/nullptr,
3595                                               /*S=*/nullptr);
3596   }
3597 
3598   /// Build a new shuffle vector expression.
3599   ///
3600   /// By default, performs semantic analysis to build the new expression.
3601   /// Subclasses may override this routine to provide different behavior.
3602   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3603                                       MultiExprArg SubExprs,
3604                                       SourceLocation RParenLoc) {
3605     // Find the declaration for __builtin_shufflevector
3606     const IdentifierInfo &Name
3607       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3608     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3609     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3610     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3611 
3612     // Build a reference to the __builtin_shufflevector builtin
3613     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3614     Expr *Callee = new (SemaRef.Context)
3615         DeclRefExpr(SemaRef.Context, Builtin, false,
3616                     SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3617     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3618     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3619                                        CK_BuiltinFnToFnPtr).get();
3620 
3621     // Build the CallExpr
3622     ExprResult TheCall = CallExpr::Create(
3623         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3624         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3625         FPOptionsOverride());
3626 
3627     // Type-check the __builtin_shufflevector expression.
3628     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3629   }
3630 
3631   /// Build a new convert vector expression.
3632   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3633                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3634                                       SourceLocation RParenLoc) {
3635     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3636                                          BuiltinLoc, RParenLoc);
3637   }
3638 
3639   /// Build a new template argument pack expansion.
3640   ///
3641   /// By default, performs semantic analysis to build a new pack expansion
3642   /// for a template argument. Subclasses may override this routine to provide
3643   /// different behavior.
3644   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3645                                            SourceLocation EllipsisLoc,
3646                                            Optional<unsigned> NumExpansions) {
3647     switch (Pattern.getArgument().getKind()) {
3648     case TemplateArgument::Expression: {
3649       ExprResult Result
3650         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3651                                        EllipsisLoc, NumExpansions);
3652       if (Result.isInvalid())
3653         return TemplateArgumentLoc();
3654 
3655       return TemplateArgumentLoc(Result.get(), Result.get());
3656     }
3657 
3658     case TemplateArgument::Template:
3659       return TemplateArgumentLoc(
3660           SemaRef.Context,
3661           TemplateArgument(Pattern.getArgument().getAsTemplate(),
3662                            NumExpansions),
3663           Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3664           EllipsisLoc);
3665 
3666     case TemplateArgument::Null:
3667     case TemplateArgument::Integral:
3668     case TemplateArgument::Declaration:
3669     case TemplateArgument::Pack:
3670     case TemplateArgument::TemplateExpansion:
3671     case TemplateArgument::NullPtr:
3672       llvm_unreachable("Pack expansion pattern has no parameter packs");
3673 
3674     case TemplateArgument::Type:
3675       if (TypeSourceInfo *Expansion
3676             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3677                                            EllipsisLoc,
3678                                            NumExpansions))
3679         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3680                                    Expansion);
3681       break;
3682     }
3683 
3684     return TemplateArgumentLoc();
3685   }
3686 
3687   /// Build a new expression pack expansion.
3688   ///
3689   /// By default, performs semantic analysis to build a new pack expansion
3690   /// for an expression. Subclasses may override this routine to provide
3691   /// different behavior.
3692   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3693                                   Optional<unsigned> NumExpansions) {
3694     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3695   }
3696 
3697   /// Build a new C++1z fold-expression.
3698   ///
3699   /// By default, performs semantic analysis in order to build a new fold
3700   /// expression.
3701   ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3702                                 SourceLocation LParenLoc, Expr *LHS,
3703                                 BinaryOperatorKind Operator,
3704                                 SourceLocation EllipsisLoc, Expr *RHS,
3705                                 SourceLocation RParenLoc,
3706                                 Optional<unsigned> NumExpansions) {
3707     return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3708                                       EllipsisLoc, RHS, RParenLoc,
3709                                       NumExpansions);
3710   }
3711 
3712   /// Build an empty C++1z fold-expression with the given operator.
3713   ///
3714   /// By default, produces the fallback value for the fold-expression, or
3715   /// produce an error if there is no fallback value.
3716   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3717                                      BinaryOperatorKind Operator) {
3718     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3719   }
3720 
3721   /// Build a new atomic operation expression.
3722   ///
3723   /// By default, performs semantic analysis to build the new expression.
3724   /// Subclasses may override this routine to provide different behavior.
3725   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3726                                AtomicExpr::AtomicOp Op,
3727                                SourceLocation RParenLoc) {
3728     // Use this for all of the locations, since we don't know the difference
3729     // between the call and the expr at this point.
3730     SourceRange Range{BuiltinLoc, RParenLoc};
3731     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3732                                      Sema::AtomicArgumentOrder::AST);
3733   }
3734 
3735   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3736                                  ArrayRef<Expr *> SubExprs, QualType Type) {
3737     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3738   }
3739 
3740 private:
3741   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3742                                      QualType ObjectType,
3743                                      NamedDecl *FirstQualifierInScope,
3744                                      CXXScopeSpec &SS);
3745 
3746   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3747                                              QualType ObjectType,
3748                                              NamedDecl *FirstQualifierInScope,
3749                                              CXXScopeSpec &SS);
3750 
3751   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3752                                             NamedDecl *FirstQualifierInScope,
3753                                             CXXScopeSpec &SS);
3754 
3755   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3756                                       DependentNameTypeLoc TL,
3757                                       bool DeducibleTSTContext);
3758 };
3759 
3760 template <typename Derived>
3761 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3762   if (!S)
3763     return S;
3764 
3765   switch (S->getStmtClass()) {
3766   case Stmt::NoStmtClass: break;
3767 
3768   // Transform individual statement nodes
3769   // Pass SDK into statements that can produce a value
3770 #define STMT(Node, Parent)                                              \
3771   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3772 #define VALUESTMT(Node, Parent)                                         \
3773   case Stmt::Node##Class:                                               \
3774     return getDerived().Transform##Node(cast<Node>(S), SDK);
3775 #define ABSTRACT_STMT(Node)
3776 #define EXPR(Node, Parent)
3777 #include "clang/AST/StmtNodes.inc"
3778 
3779   // Transform expressions by calling TransformExpr.
3780 #define STMT(Node, Parent)
3781 #define ABSTRACT_STMT(Stmt)
3782 #define EXPR(Node, Parent) case Stmt::Node##Class:
3783 #include "clang/AST/StmtNodes.inc"
3784     {
3785       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3786 
3787       if (SDK == SDK_StmtExprResult)
3788         E = getSema().ActOnStmtExprResult(E);
3789       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3790     }
3791   }
3792 
3793   return S;
3794 }
3795 
3796 template<typename Derived>
3797 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3798   if (!S)
3799     return S;
3800 
3801   switch (S->getClauseKind()) {
3802   default: break;
3803   // Transform individual clause nodes
3804 #define GEN_CLANG_CLAUSE_CLASS
3805 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
3806   case Enum:                                                                   \
3807     return getDerived().Transform##Class(cast<Class>(S));
3808 #include "llvm/Frontend/OpenMP/OMP.inc"
3809   }
3810 
3811   return S;
3812 }
3813 
3814 
3815 template<typename Derived>
3816 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3817   if (!E)
3818     return E;
3819 
3820   switch (E->getStmtClass()) {
3821     case Stmt::NoStmtClass: break;
3822 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3823 #define ABSTRACT_STMT(Stmt)
3824 #define EXPR(Node, Parent)                                              \
3825     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3826 #include "clang/AST/StmtNodes.inc"
3827   }
3828 
3829   return E;
3830 }
3831 
3832 template<typename Derived>
3833 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3834                                                         bool NotCopyInit) {
3835   // Initializers are instantiated like expressions, except that various outer
3836   // layers are stripped.
3837   if (!Init)
3838     return Init;
3839 
3840   if (auto *FE = dyn_cast<FullExpr>(Init))
3841     Init = FE->getSubExpr();
3842 
3843   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3844     Init = AIL->getCommonExpr();
3845 
3846   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3847     Init = MTE->getSubExpr();
3848 
3849   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3850     Init = Binder->getSubExpr();
3851 
3852   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3853     Init = ICE->getSubExprAsWritten();
3854 
3855   if (CXXStdInitializerListExpr *ILE =
3856           dyn_cast<CXXStdInitializerListExpr>(Init))
3857     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3858 
3859   // If this is copy-initialization, we only need to reconstruct
3860   // InitListExprs. Other forms of copy-initialization will be a no-op if
3861   // the initializer is already the right type.
3862   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3863   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3864     return getDerived().TransformExpr(Init);
3865 
3866   // Revert value-initialization back to empty parens.
3867   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3868     SourceRange Parens = VIE->getSourceRange();
3869     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3870                                              Parens.getEnd());
3871   }
3872 
3873   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3874   if (isa<ImplicitValueInitExpr>(Init))
3875     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3876                                              SourceLocation());
3877 
3878   // Revert initialization by constructor back to a parenthesized or braced list
3879   // of expressions. Any other form of initializer can just be reused directly.
3880   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3881     return getDerived().TransformExpr(Init);
3882 
3883   // If the initialization implicitly converted an initializer list to a
3884   // std::initializer_list object, unwrap the std::initializer_list too.
3885   if (Construct && Construct->isStdInitListInitialization())
3886     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3887 
3888   // Enter a list-init context if this was list initialization.
3889   EnterExpressionEvaluationContext Context(
3890       getSema(), EnterExpressionEvaluationContext::InitList,
3891       Construct->isListInitialization());
3892 
3893   SmallVector<Expr*, 8> NewArgs;
3894   bool ArgChanged = false;
3895   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3896                                   /*IsCall*/true, NewArgs, &ArgChanged))
3897     return ExprError();
3898 
3899   // If this was list initialization, revert to syntactic list form.
3900   if (Construct->isListInitialization())
3901     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3902                                         Construct->getEndLoc());
3903 
3904   // Build a ParenListExpr to represent anything else.
3905   SourceRange Parens = Construct->getParenOrBraceRange();
3906   if (Parens.isInvalid()) {
3907     // This was a variable declaration's initialization for which no initializer
3908     // was specified.
3909     assert(NewArgs.empty() &&
3910            "no parens or braces but have direct init with arguments?");
3911     return ExprEmpty();
3912   }
3913   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3914                                            Parens.getEnd());
3915 }
3916 
3917 template<typename Derived>
3918 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3919                                             unsigned NumInputs,
3920                                             bool IsCall,
3921                                       SmallVectorImpl<Expr *> &Outputs,
3922                                             bool *ArgChanged) {
3923   for (unsigned I = 0; I != NumInputs; ++I) {
3924     // If requested, drop call arguments that need to be dropped.
3925     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3926       if (ArgChanged)
3927         *ArgChanged = true;
3928 
3929       break;
3930     }
3931 
3932     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3933       Expr *Pattern = Expansion->getPattern();
3934 
3935       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3936       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3937       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3938 
3939       // Determine whether the set of unexpanded parameter packs can and should
3940       // be expanded.
3941       bool Expand = true;
3942       bool RetainExpansion = false;
3943       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3944       Optional<unsigned> NumExpansions = OrigNumExpansions;
3945       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3946                                                Pattern->getSourceRange(),
3947                                                Unexpanded,
3948                                                Expand, RetainExpansion,
3949                                                NumExpansions))
3950         return true;
3951 
3952       if (!Expand) {
3953         // The transform has determined that we should perform a simple
3954         // transformation on the pack expansion, producing another pack
3955         // expansion.
3956         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3957         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3958         if (OutPattern.isInvalid())
3959           return true;
3960 
3961         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3962                                                 Expansion->getEllipsisLoc(),
3963                                                            NumExpansions);
3964         if (Out.isInvalid())
3965           return true;
3966 
3967         if (ArgChanged)
3968           *ArgChanged = true;
3969         Outputs.push_back(Out.get());
3970         continue;
3971       }
3972 
3973       // Record right away that the argument was changed.  This needs
3974       // to happen even if the array expands to nothing.
3975       if (ArgChanged) *ArgChanged = true;
3976 
3977       // The transform has determined that we should perform an elementwise
3978       // expansion of the pattern. Do so.
3979       for (unsigned I = 0; I != *NumExpansions; ++I) {
3980         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3981         ExprResult Out = getDerived().TransformExpr(Pattern);
3982         if (Out.isInvalid())
3983           return true;
3984 
3985         if (Out.get()->containsUnexpandedParameterPack()) {
3986           Out = getDerived().RebuildPackExpansion(
3987               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3988           if (Out.isInvalid())
3989             return true;
3990         }
3991 
3992         Outputs.push_back(Out.get());
3993       }
3994 
3995       // If we're supposed to retain a pack expansion, do so by temporarily
3996       // forgetting the partially-substituted parameter pack.
3997       if (RetainExpansion) {
3998         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3999 
4000         ExprResult Out = getDerived().TransformExpr(Pattern);
4001         if (Out.isInvalid())
4002           return true;
4003 
4004         Out = getDerived().RebuildPackExpansion(
4005             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4006         if (Out.isInvalid())
4007           return true;
4008 
4009         Outputs.push_back(Out.get());
4010       }
4011 
4012       continue;
4013     }
4014 
4015     ExprResult Result =
4016       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4017              : getDerived().TransformExpr(Inputs[I]);
4018     if (Result.isInvalid())
4019       return true;
4020 
4021     if (Result.get() != Inputs[I] && ArgChanged)
4022       *ArgChanged = true;
4023 
4024     Outputs.push_back(Result.get());
4025   }
4026 
4027   return false;
4028 }
4029 
4030 template <typename Derived>
4031 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4032     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4033   if (Var) {
4034     VarDecl *ConditionVar = cast_or_null<VarDecl>(
4035         getDerived().TransformDefinition(Var->getLocation(), Var));
4036 
4037     if (!ConditionVar)
4038       return Sema::ConditionError();
4039 
4040     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4041   }
4042 
4043   if (Expr) {
4044     ExprResult CondExpr = getDerived().TransformExpr(Expr);
4045 
4046     if (CondExpr.isInvalid())
4047       return Sema::ConditionError();
4048 
4049     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
4050   }
4051 
4052   return Sema::ConditionResult();
4053 }
4054 
4055 template <typename Derived>
4056 NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4057     NestedNameSpecifierLoc NNS, QualType ObjectType,
4058     NamedDecl *FirstQualifierInScope) {
4059   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4060   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4061        Qualifier = Qualifier.getPrefix())
4062     Qualifiers.push_back(Qualifier);
4063 
4064   CXXScopeSpec SS;
4065   while (!Qualifiers.empty()) {
4066     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4067     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4068 
4069     switch (QNNS->getKind()) {
4070     case NestedNameSpecifier::Identifier: {
4071       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4072                                       Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4073                                       ObjectType);
4074       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4075                                               SS, FirstQualifierInScope, false))
4076         return NestedNameSpecifierLoc();
4077       break;
4078     }
4079 
4080     case NestedNameSpecifier::Namespace: {
4081       NamespaceDecl *NS =
4082           cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4083               Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4084       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4085       break;
4086     }
4087 
4088     case NestedNameSpecifier::NamespaceAlias: {
4089       NamespaceAliasDecl *Alias =
4090           cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4091               Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4092       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4093                 Q.getLocalEndLoc());
4094       break;
4095     }
4096 
4097     case NestedNameSpecifier::Global:
4098       // There is no meaningful transformation that one could perform on the
4099       // global scope.
4100       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4101       break;
4102 
4103     case NestedNameSpecifier::Super: {
4104       CXXRecordDecl *RD =
4105           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4106               SourceLocation(), QNNS->getAsRecordDecl()));
4107       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4108       break;
4109     }
4110 
4111     case NestedNameSpecifier::TypeSpecWithTemplate:
4112     case NestedNameSpecifier::TypeSpec: {
4113       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4114                                               FirstQualifierInScope, SS);
4115 
4116       if (!TL)
4117         return NestedNameSpecifierLoc();
4118 
4119       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
4120           (SemaRef.getLangOpts().CPlusPlus11 &&
4121            TL.getType()->isEnumeralType())) {
4122         assert(!TL.getType().hasLocalQualifiers() &&
4123                "Can't get cv-qualifiers here");
4124         if (TL.getType()->isEnumeralType())
4125           SemaRef.Diag(TL.getBeginLoc(),
4126                        diag::warn_cxx98_compat_enum_nested_name_spec);
4127         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4128                   Q.getLocalEndLoc());
4129         break;
4130       }
4131       // If the nested-name-specifier is an invalid type def, don't emit an
4132       // error because a previous error should have already been emitted.
4133       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
4134       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4135         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4136             << TL.getType() << SS.getRange();
4137       }
4138       return NestedNameSpecifierLoc();
4139     }
4140     }
4141 
4142     // The qualifier-in-scope and object type only apply to the leftmost entity.
4143     FirstQualifierInScope = nullptr;
4144     ObjectType = QualType();
4145   }
4146 
4147   // Don't rebuild the nested-name-specifier if we don't have to.
4148   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4149       !getDerived().AlwaysRebuild())
4150     return NNS;
4151 
4152   // If we can re-use the source-location data from the original
4153   // nested-name-specifier, do so.
4154   if (SS.location_size() == NNS.getDataLength() &&
4155       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4156     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4157 
4158   // Allocate new nested-name-specifier location information.
4159   return SS.getWithLocInContext(SemaRef.Context);
4160 }
4161 
4162 template<typename Derived>
4163 DeclarationNameInfo
4164 TreeTransform<Derived>
4165 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4166   DeclarationName Name = NameInfo.getName();
4167   if (!Name)
4168     return DeclarationNameInfo();
4169 
4170   switch (Name.getNameKind()) {
4171   case DeclarationName::Identifier:
4172   case DeclarationName::ObjCZeroArgSelector:
4173   case DeclarationName::ObjCOneArgSelector:
4174   case DeclarationName::ObjCMultiArgSelector:
4175   case DeclarationName::CXXOperatorName:
4176   case DeclarationName::CXXLiteralOperatorName:
4177   case DeclarationName::CXXUsingDirective:
4178     return NameInfo;
4179 
4180   case DeclarationName::CXXDeductionGuideName: {
4181     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4182     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4183         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4184     if (!NewTemplate)
4185       return DeclarationNameInfo();
4186 
4187     DeclarationNameInfo NewNameInfo(NameInfo);
4188     NewNameInfo.setName(
4189         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4190     return NewNameInfo;
4191   }
4192 
4193   case DeclarationName::CXXConstructorName:
4194   case DeclarationName::CXXDestructorName:
4195   case DeclarationName::CXXConversionFunctionName: {
4196     TypeSourceInfo *NewTInfo;
4197     CanQualType NewCanTy;
4198     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4199       NewTInfo = getDerived().TransformType(OldTInfo);
4200       if (!NewTInfo)
4201         return DeclarationNameInfo();
4202       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4203     }
4204     else {
4205       NewTInfo = nullptr;
4206       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4207       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4208       if (NewT.isNull())
4209         return DeclarationNameInfo();
4210       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4211     }
4212 
4213     DeclarationName NewName
4214       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4215                                                            NewCanTy);
4216     DeclarationNameInfo NewNameInfo(NameInfo);
4217     NewNameInfo.setName(NewName);
4218     NewNameInfo.setNamedTypeInfo(NewTInfo);
4219     return NewNameInfo;
4220   }
4221   }
4222 
4223   llvm_unreachable("Unknown name kind.");
4224 }
4225 
4226 template<typename Derived>
4227 TemplateName
4228 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4229                                               TemplateName Name,
4230                                               SourceLocation NameLoc,
4231                                               QualType ObjectType,
4232                                               NamedDecl *FirstQualifierInScope,
4233                                               bool AllowInjectedClassName) {
4234   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4235     TemplateDecl *Template = QTN->getTemplateDecl();
4236     assert(Template && "qualified template name must refer to a template");
4237 
4238     TemplateDecl *TransTemplate
4239       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4240                                                               Template));
4241     if (!TransTemplate)
4242       return TemplateName();
4243 
4244     if (!getDerived().AlwaysRebuild() &&
4245         SS.getScopeRep() == QTN->getQualifier() &&
4246         TransTemplate == Template)
4247       return Name;
4248 
4249     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4250                                             TransTemplate);
4251   }
4252 
4253   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4254     if (SS.getScopeRep()) {
4255       // These apply to the scope specifier, not the template.
4256       ObjectType = QualType();
4257       FirstQualifierInScope = nullptr;
4258     }
4259 
4260     if (!getDerived().AlwaysRebuild() &&
4261         SS.getScopeRep() == DTN->getQualifier() &&
4262         ObjectType.isNull())
4263       return Name;
4264 
4265     // FIXME: Preserve the location of the "template" keyword.
4266     SourceLocation TemplateKWLoc = NameLoc;
4267 
4268     if (DTN->isIdentifier()) {
4269       return getDerived().RebuildTemplateName(SS,
4270                                               TemplateKWLoc,
4271                                               *DTN->getIdentifier(),
4272                                               NameLoc,
4273                                               ObjectType,
4274                                               FirstQualifierInScope,
4275                                               AllowInjectedClassName);
4276     }
4277 
4278     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4279                                             DTN->getOperator(), NameLoc,
4280                                             ObjectType, AllowInjectedClassName);
4281   }
4282 
4283   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4284     TemplateDecl *TransTemplate
4285       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4286                                                               Template));
4287     if (!TransTemplate)
4288       return TemplateName();
4289 
4290     if (!getDerived().AlwaysRebuild() &&
4291         TransTemplate == Template)
4292       return Name;
4293 
4294     return TemplateName(TransTemplate);
4295   }
4296 
4297   if (SubstTemplateTemplateParmPackStorage *SubstPack
4298       = Name.getAsSubstTemplateTemplateParmPack()) {
4299     TemplateTemplateParmDecl *TransParam
4300     = cast_or_null<TemplateTemplateParmDecl>(
4301             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
4302     if (!TransParam)
4303       return TemplateName();
4304 
4305     if (!getDerived().AlwaysRebuild() &&
4306         TransParam == SubstPack->getParameterPack())
4307       return Name;
4308 
4309     return getDerived().RebuildTemplateName(TransParam,
4310                                             SubstPack->getArgumentPack());
4311   }
4312 
4313   // These should be getting filtered out before they reach the AST.
4314   llvm_unreachable("overloaded function decl survived to here");
4315 }
4316 
4317 template<typename Derived>
4318 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4319                                          const TemplateArgument &Arg,
4320                                          TemplateArgumentLoc &Output) {
4321   Output = getSema().getTrivialTemplateArgumentLoc(
4322       Arg, QualType(), getDerived().getBaseLocation());
4323 }
4324 
4325 template <typename Derived>
4326 bool TreeTransform<Derived>::TransformTemplateArgument(
4327     const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4328     bool Uneval) {
4329   const TemplateArgument &Arg = Input.getArgument();
4330   switch (Arg.getKind()) {
4331   case TemplateArgument::Null:
4332   case TemplateArgument::Pack:
4333     llvm_unreachable("Unexpected TemplateArgument");
4334 
4335   case TemplateArgument::Integral:
4336   case TemplateArgument::NullPtr:
4337   case TemplateArgument::Declaration: {
4338     // Transform a resolved template argument straight to a resolved template
4339     // argument. We get here when substituting into an already-substituted
4340     // template type argument during concept satisfaction checking.
4341     QualType T = Arg.getNonTypeTemplateArgumentType();
4342     QualType NewT = getDerived().TransformType(T);
4343     if (NewT.isNull())
4344       return true;
4345 
4346     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4347                        ? Arg.getAsDecl()
4348                        : nullptr;
4349     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4350                               getDerived().getBaseLocation(), D))
4351                         : nullptr;
4352     if (D && !NewD)
4353       return true;
4354 
4355     if (NewT == T && D == NewD)
4356       Output = Input;
4357     else if (Arg.getKind() == TemplateArgument::Integral)
4358       Output = TemplateArgumentLoc(
4359           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4360           TemplateArgumentLocInfo());
4361     else if (Arg.getKind() == TemplateArgument::NullPtr)
4362       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4363                                    TemplateArgumentLocInfo());
4364     else
4365       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4366                                    TemplateArgumentLocInfo());
4367 
4368     return false;
4369   }
4370 
4371   case TemplateArgument::Type: {
4372     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4373     if (!DI)
4374       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4375 
4376     DI = getDerived().TransformType(DI);
4377     if (!DI)
4378       return true;
4379 
4380     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4381     return false;
4382   }
4383 
4384   case TemplateArgument::Template: {
4385     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4386     if (QualifierLoc) {
4387       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4388       if (!QualifierLoc)
4389         return true;
4390     }
4391 
4392     CXXScopeSpec SS;
4393     SS.Adopt(QualifierLoc);
4394     TemplateName Template = getDerived().TransformTemplateName(
4395         SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4396     if (Template.isNull())
4397       return true;
4398 
4399     Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4400                                  QualifierLoc, Input.getTemplateNameLoc());
4401     return false;
4402   }
4403 
4404   case TemplateArgument::TemplateExpansion:
4405     llvm_unreachable("Caller should expand pack expansions");
4406 
4407   case TemplateArgument::Expression: {
4408     // Template argument expressions are constant expressions.
4409     EnterExpressionEvaluationContext Unevaluated(
4410         getSema(),
4411         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4412                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4413         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4414         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4415 
4416     Expr *InputExpr = Input.getSourceExpression();
4417     if (!InputExpr)
4418       InputExpr = Input.getArgument().getAsExpr();
4419 
4420     ExprResult E = getDerived().TransformExpr(InputExpr);
4421     E = SemaRef.ActOnConstantExpression(E);
4422     if (E.isInvalid())
4423       return true;
4424     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4425     return false;
4426   }
4427   }
4428 
4429   // Work around bogus GCC warning
4430   return true;
4431 }
4432 
4433 /// Iterator adaptor that invents template argument location information
4434 /// for each of the template arguments in its underlying iterator.
4435 template<typename Derived, typename InputIterator>
4436 class TemplateArgumentLocInventIterator {
4437   TreeTransform<Derived> &Self;
4438   InputIterator Iter;
4439 
4440 public:
4441   typedef TemplateArgumentLoc value_type;
4442   typedef TemplateArgumentLoc reference;
4443   typedef typename std::iterator_traits<InputIterator>::difference_type
4444     difference_type;
4445   typedef std::input_iterator_tag iterator_category;
4446 
4447   class pointer {
4448     TemplateArgumentLoc Arg;
4449 
4450   public:
4451     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4452 
4453     const TemplateArgumentLoc *operator->() const { return &Arg; }
4454   };
4455 
4456   TemplateArgumentLocInventIterator() { }
4457 
4458   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4459                                              InputIterator Iter)
4460     : Self(Self), Iter(Iter) { }
4461 
4462   TemplateArgumentLocInventIterator &operator++() {
4463     ++Iter;
4464     return *this;
4465   }
4466 
4467   TemplateArgumentLocInventIterator operator++(int) {
4468     TemplateArgumentLocInventIterator Old(*this);
4469     ++(*this);
4470     return Old;
4471   }
4472 
4473   reference operator*() const {
4474     TemplateArgumentLoc Result;
4475     Self.InventTemplateArgumentLoc(*Iter, Result);
4476     return Result;
4477   }
4478 
4479   pointer operator->() const { return pointer(**this); }
4480 
4481   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4482                          const TemplateArgumentLocInventIterator &Y) {
4483     return X.Iter == Y.Iter;
4484   }
4485 
4486   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4487                          const TemplateArgumentLocInventIterator &Y) {
4488     return X.Iter != Y.Iter;
4489   }
4490 };
4491 
4492 template<typename Derived>
4493 template<typename InputIterator>
4494 bool TreeTransform<Derived>::TransformTemplateArguments(
4495     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4496     bool Uneval) {
4497   for (; First != Last; ++First) {
4498     TemplateArgumentLoc Out;
4499     TemplateArgumentLoc In = *First;
4500 
4501     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4502       // Unpack argument packs, which we translate them into separate
4503       // arguments.
4504       // FIXME: We could do much better if we could guarantee that the
4505       // TemplateArgumentLocInfo for the pack expansion would be usable for
4506       // all of the template arguments in the argument pack.
4507       typedef TemplateArgumentLocInventIterator<Derived,
4508                                                 TemplateArgument::pack_iterator>
4509         PackLocIterator;
4510       if (TransformTemplateArguments(PackLocIterator(*this,
4511                                                  In.getArgument().pack_begin()),
4512                                      PackLocIterator(*this,
4513                                                    In.getArgument().pack_end()),
4514                                      Outputs, Uneval))
4515         return true;
4516 
4517       continue;
4518     }
4519 
4520     if (In.getArgument().isPackExpansion()) {
4521       // We have a pack expansion, for which we will be substituting into
4522       // the pattern.
4523       SourceLocation Ellipsis;
4524       Optional<unsigned> OrigNumExpansions;
4525       TemplateArgumentLoc Pattern
4526         = getSema().getTemplateArgumentPackExpansionPattern(
4527               In, Ellipsis, OrigNumExpansions);
4528 
4529       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4530       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4531       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4532 
4533       // Determine whether the set of unexpanded parameter packs can and should
4534       // be expanded.
4535       bool Expand = true;
4536       bool RetainExpansion = false;
4537       Optional<unsigned> NumExpansions = OrigNumExpansions;
4538       if (getDerived().TryExpandParameterPacks(Ellipsis,
4539                                                Pattern.getSourceRange(),
4540                                                Unexpanded,
4541                                                Expand,
4542                                                RetainExpansion,
4543                                                NumExpansions))
4544         return true;
4545 
4546       if (!Expand) {
4547         // The transform has determined that we should perform a simple
4548         // transformation on the pack expansion, producing another pack
4549         // expansion.
4550         TemplateArgumentLoc OutPattern;
4551         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4552         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4553           return true;
4554 
4555         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4556                                                 NumExpansions);
4557         if (Out.getArgument().isNull())
4558           return true;
4559 
4560         Outputs.addArgument(Out);
4561         continue;
4562       }
4563 
4564       // The transform has determined that we should perform an elementwise
4565       // expansion of the pattern. Do so.
4566       for (unsigned I = 0; I != *NumExpansions; ++I) {
4567         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4568 
4569         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4570           return true;
4571 
4572         if (Out.getArgument().containsUnexpandedParameterPack()) {
4573           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4574                                                   OrigNumExpansions);
4575           if (Out.getArgument().isNull())
4576             return true;
4577         }
4578 
4579         Outputs.addArgument(Out);
4580       }
4581 
4582       // If we're supposed to retain a pack expansion, do so by temporarily
4583       // forgetting the partially-substituted parameter pack.
4584       if (RetainExpansion) {
4585         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4586 
4587         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4588           return true;
4589 
4590         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4591                                                 OrigNumExpansions);
4592         if (Out.getArgument().isNull())
4593           return true;
4594 
4595         Outputs.addArgument(Out);
4596       }
4597 
4598       continue;
4599     }
4600 
4601     // The simple case:
4602     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4603       return true;
4604 
4605     Outputs.addArgument(Out);
4606   }
4607 
4608   return false;
4609 
4610 }
4611 
4612 //===----------------------------------------------------------------------===//
4613 // Type transformation
4614 //===----------------------------------------------------------------------===//
4615 
4616 template<typename Derived>
4617 QualType TreeTransform<Derived>::TransformType(QualType T) {
4618   if (getDerived().AlreadyTransformed(T))
4619     return T;
4620 
4621   // Temporary workaround.  All of these transformations should
4622   // eventually turn into transformations on TypeLocs.
4623   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4624                                                 getDerived().getBaseLocation());
4625 
4626   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4627 
4628   if (!NewDI)
4629     return QualType();
4630 
4631   return NewDI->getType();
4632 }
4633 
4634 template<typename Derived>
4635 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4636   // Refine the base location to the type's location.
4637   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4638                        getDerived().getBaseEntity());
4639   if (getDerived().AlreadyTransformed(DI->getType()))
4640     return DI;
4641 
4642   TypeLocBuilder TLB;
4643 
4644   TypeLoc TL = DI->getTypeLoc();
4645   TLB.reserve(TL.getFullDataSize());
4646 
4647   QualType Result = getDerived().TransformType(TLB, TL);
4648   if (Result.isNull())
4649     return nullptr;
4650 
4651   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4652 }
4653 
4654 template<typename Derived>
4655 QualType
4656 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4657   switch (T.getTypeLocClass()) {
4658 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4659 #define TYPELOC(CLASS, PARENT)                                                 \
4660   case TypeLoc::CLASS:                                                         \
4661     return getDerived().Transform##CLASS##Type(TLB,                            \
4662                                                T.castAs<CLASS##TypeLoc>());
4663 #include "clang/AST/TypeLocNodes.def"
4664   }
4665 
4666   llvm_unreachable("unhandled type loc!");
4667 }
4668 
4669 template<typename Derived>
4670 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4671   if (!isa<DependentNameType>(T))
4672     return TransformType(T);
4673 
4674   if (getDerived().AlreadyTransformed(T))
4675     return T;
4676   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4677                                                 getDerived().getBaseLocation());
4678   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4679   return NewDI ? NewDI->getType() : QualType();
4680 }
4681 
4682 template<typename Derived>
4683 TypeSourceInfo *
4684 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4685   if (!isa<DependentNameType>(DI->getType()))
4686     return TransformType(DI);
4687 
4688   // Refine the base location to the type's location.
4689   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4690                        getDerived().getBaseEntity());
4691   if (getDerived().AlreadyTransformed(DI->getType()))
4692     return DI;
4693 
4694   TypeLocBuilder TLB;
4695 
4696   TypeLoc TL = DI->getTypeLoc();
4697   TLB.reserve(TL.getFullDataSize());
4698 
4699   auto QTL = TL.getAs<QualifiedTypeLoc>();
4700   if (QTL)
4701     TL = QTL.getUnqualifiedLoc();
4702 
4703   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4704 
4705   QualType Result = getDerived().TransformDependentNameType(
4706       TLB, DNTL, /*DeducedTSTContext*/true);
4707   if (Result.isNull())
4708     return nullptr;
4709 
4710   if (QTL) {
4711     Result = getDerived().RebuildQualifiedType(Result, QTL);
4712     if (Result.isNull())
4713       return nullptr;
4714     TLB.TypeWasModifiedSafely(Result);
4715   }
4716 
4717   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4718 }
4719 
4720 template<typename Derived>
4721 QualType
4722 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4723                                                QualifiedTypeLoc T) {
4724   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4725   if (Result.isNull())
4726     return QualType();
4727 
4728   Result = getDerived().RebuildQualifiedType(Result, T);
4729 
4730   if (Result.isNull())
4731     return QualType();
4732 
4733   // RebuildQualifiedType might have updated the type, but not in a way
4734   // that invalidates the TypeLoc. (There's no location information for
4735   // qualifiers.)
4736   TLB.TypeWasModifiedSafely(Result);
4737 
4738   return Result;
4739 }
4740 
4741 template <typename Derived>
4742 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4743                                                       QualifiedTypeLoc TL) {
4744 
4745   SourceLocation Loc = TL.getBeginLoc();
4746   Qualifiers Quals = TL.getType().getLocalQualifiers();
4747 
4748   if (((T.getAddressSpace() != LangAS::Default &&
4749         Quals.getAddressSpace() != LangAS::Default)) &&
4750       T.getAddressSpace() != Quals.getAddressSpace()) {
4751     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4752         << TL.getType() << T;
4753     return QualType();
4754   }
4755 
4756   // C++ [dcl.fct]p7:
4757   //   [When] adding cv-qualifications on top of the function type [...] the
4758   //   cv-qualifiers are ignored.
4759   if (T->isFunctionType()) {
4760     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4761                                                      Quals.getAddressSpace());
4762     return T;
4763   }
4764 
4765   // C++ [dcl.ref]p1:
4766   //   when the cv-qualifiers are introduced through the use of a typedef-name
4767   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4768   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4769   // applied to a reference type.
4770   if (T->isReferenceType()) {
4771     // The only qualifier that applies to a reference type is restrict.
4772     if (!Quals.hasRestrict())
4773       return T;
4774     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4775   }
4776 
4777   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4778   // resulting type.
4779   if (Quals.hasObjCLifetime()) {
4780     if (!T->isObjCLifetimeType() && !T->isDependentType())
4781       Quals.removeObjCLifetime();
4782     else if (T.getObjCLifetime()) {
4783       // Objective-C ARC:
4784       //   A lifetime qualifier applied to a substituted template parameter
4785       //   overrides the lifetime qualifier from the template argument.
4786       const AutoType *AutoTy;
4787       if (const SubstTemplateTypeParmType *SubstTypeParam
4788                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4789         QualType Replacement = SubstTypeParam->getReplacementType();
4790         Qualifiers Qs = Replacement.getQualifiers();
4791         Qs.removeObjCLifetime();
4792         Replacement = SemaRef.Context.getQualifiedType(
4793             Replacement.getUnqualifiedType(), Qs);
4794         T = SemaRef.Context.getSubstTemplateTypeParmType(
4795             SubstTypeParam->getReplacedParameter(), Replacement);
4796       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4797         // 'auto' types behave the same way as template parameters.
4798         QualType Deduced = AutoTy->getDeducedType();
4799         Qualifiers Qs = Deduced.getQualifiers();
4800         Qs.removeObjCLifetime();
4801         Deduced =
4802             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4803         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4804                                         AutoTy->isDependentType(),
4805                                         /*isPack=*/false,
4806                                         AutoTy->getTypeConstraintConcept(),
4807                                         AutoTy->getTypeConstraintArguments());
4808       } else {
4809         // Otherwise, complain about the addition of a qualifier to an
4810         // already-qualified type.
4811         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4812         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4813         Quals.removeObjCLifetime();
4814       }
4815     }
4816   }
4817 
4818   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4819 }
4820 
4821 template<typename Derived>
4822 TypeLoc
4823 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4824                                                    QualType ObjectType,
4825                                                    NamedDecl *UnqualLookup,
4826                                                    CXXScopeSpec &SS) {
4827   if (getDerived().AlreadyTransformed(TL.getType()))
4828     return TL;
4829 
4830   TypeSourceInfo *TSI =
4831       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4832   if (TSI)
4833     return TSI->getTypeLoc();
4834   return TypeLoc();
4835 }
4836 
4837 template<typename Derived>
4838 TypeSourceInfo *
4839 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4840                                                    QualType ObjectType,
4841                                                    NamedDecl *UnqualLookup,
4842                                                    CXXScopeSpec &SS) {
4843   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4844     return TSInfo;
4845 
4846   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4847                                    UnqualLookup, SS);
4848 }
4849 
4850 template <typename Derived>
4851 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4852     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4853     CXXScopeSpec &SS) {
4854   QualType T = TL.getType();
4855   assert(!getDerived().AlreadyTransformed(T));
4856 
4857   TypeLocBuilder TLB;
4858   QualType Result;
4859 
4860   if (isa<TemplateSpecializationType>(T)) {
4861     TemplateSpecializationTypeLoc SpecTL =
4862         TL.castAs<TemplateSpecializationTypeLoc>();
4863 
4864     TemplateName Template = getDerived().TransformTemplateName(
4865         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4866         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4867     if (Template.isNull())
4868       return nullptr;
4869 
4870     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4871                                                               Template);
4872   } else if (isa<DependentTemplateSpecializationType>(T)) {
4873     DependentTemplateSpecializationTypeLoc SpecTL =
4874         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4875 
4876     TemplateName Template
4877       = getDerived().RebuildTemplateName(SS,
4878                                          SpecTL.getTemplateKeywordLoc(),
4879                                          *SpecTL.getTypePtr()->getIdentifier(),
4880                                          SpecTL.getTemplateNameLoc(),
4881                                          ObjectType, UnqualLookup,
4882                                          /*AllowInjectedClassName*/true);
4883     if (Template.isNull())
4884       return nullptr;
4885 
4886     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4887                                                                        SpecTL,
4888                                                                        Template,
4889                                                                        SS);
4890   } else {
4891     // Nothing special needs to be done for these.
4892     Result = getDerived().TransformType(TLB, TL);
4893   }
4894 
4895   if (Result.isNull())
4896     return nullptr;
4897 
4898   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4899 }
4900 
4901 template <class TyLoc> static inline
4902 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4903   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4904   NewT.setNameLoc(T.getNameLoc());
4905   return T.getType();
4906 }
4907 
4908 template<typename Derived>
4909 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4910                                                       BuiltinTypeLoc T) {
4911   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4912   NewT.setBuiltinLoc(T.getBuiltinLoc());
4913   if (T.needsExtraLocalData())
4914     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4915   return T.getType();
4916 }
4917 
4918 template<typename Derived>
4919 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4920                                                       ComplexTypeLoc T) {
4921   // FIXME: recurse?
4922   return TransformTypeSpecType(TLB, T);
4923 }
4924 
4925 template <typename Derived>
4926 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4927                                                        AdjustedTypeLoc TL) {
4928   // Adjustments applied during transformation are handled elsewhere.
4929   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4930 }
4931 
4932 template<typename Derived>
4933 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4934                                                       DecayedTypeLoc TL) {
4935   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4936   if (OriginalType.isNull())
4937     return QualType();
4938 
4939   QualType Result = TL.getType();
4940   if (getDerived().AlwaysRebuild() ||
4941       OriginalType != TL.getOriginalLoc().getType())
4942     Result = SemaRef.Context.getDecayedType(OriginalType);
4943   TLB.push<DecayedTypeLoc>(Result);
4944   // Nothing to set for DecayedTypeLoc.
4945   return Result;
4946 }
4947 
4948 template<typename Derived>
4949 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4950                                                       PointerTypeLoc TL) {
4951   QualType PointeeType
4952     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4953   if (PointeeType.isNull())
4954     return QualType();
4955 
4956   QualType Result = TL.getType();
4957   if (PointeeType->getAs<ObjCObjectType>()) {
4958     // A dependent pointer type 'T *' has is being transformed such
4959     // that an Objective-C class type is being replaced for 'T'. The
4960     // resulting pointer type is an ObjCObjectPointerType, not a
4961     // PointerType.
4962     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4963 
4964     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4965     NewT.setStarLoc(TL.getStarLoc());
4966     return Result;
4967   }
4968 
4969   if (getDerived().AlwaysRebuild() ||
4970       PointeeType != TL.getPointeeLoc().getType()) {
4971     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4972     if (Result.isNull())
4973       return QualType();
4974   }
4975 
4976   // Objective-C ARC can add lifetime qualifiers to the type that we're
4977   // pointing to.
4978   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4979 
4980   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4981   NewT.setSigilLoc(TL.getSigilLoc());
4982   return Result;
4983 }
4984 
4985 template<typename Derived>
4986 QualType
4987 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4988                                                   BlockPointerTypeLoc TL) {
4989   QualType PointeeType
4990     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4991   if (PointeeType.isNull())
4992     return QualType();
4993 
4994   QualType Result = TL.getType();
4995   if (getDerived().AlwaysRebuild() ||
4996       PointeeType != TL.getPointeeLoc().getType()) {
4997     Result = getDerived().RebuildBlockPointerType(PointeeType,
4998                                                   TL.getSigilLoc());
4999     if (Result.isNull())
5000       return QualType();
5001   }
5002 
5003   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5004   NewT.setSigilLoc(TL.getSigilLoc());
5005   return Result;
5006 }
5007 
5008 /// Transforms a reference type.  Note that somewhat paradoxically we
5009 /// don't care whether the type itself is an l-value type or an r-value
5010 /// type;  we only care if the type was *written* as an l-value type
5011 /// or an r-value type.
5012 template<typename Derived>
5013 QualType
5014 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5015                                                ReferenceTypeLoc TL) {
5016   const ReferenceType *T = TL.getTypePtr();
5017 
5018   // Note that this works with the pointee-as-written.
5019   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5020   if (PointeeType.isNull())
5021     return QualType();
5022 
5023   QualType Result = TL.getType();
5024   if (getDerived().AlwaysRebuild() ||
5025       PointeeType != T->getPointeeTypeAsWritten()) {
5026     Result = getDerived().RebuildReferenceType(PointeeType,
5027                                                T->isSpelledAsLValue(),
5028                                                TL.getSigilLoc());
5029     if (Result.isNull())
5030       return QualType();
5031   }
5032 
5033   // Objective-C ARC can add lifetime qualifiers to the type that we're
5034   // referring to.
5035   TLB.TypeWasModifiedSafely(
5036       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5037 
5038   // r-value references can be rebuilt as l-value references.
5039   ReferenceTypeLoc NewTL;
5040   if (isa<LValueReferenceType>(Result))
5041     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5042   else
5043     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5044   NewTL.setSigilLoc(TL.getSigilLoc());
5045 
5046   return Result;
5047 }
5048 
5049 template<typename Derived>
5050 QualType
5051 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5052                                                  LValueReferenceTypeLoc TL) {
5053   return TransformReferenceType(TLB, TL);
5054 }
5055 
5056 template<typename Derived>
5057 QualType
5058 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5059                                                  RValueReferenceTypeLoc TL) {
5060   return TransformReferenceType(TLB, TL);
5061 }
5062 
5063 template<typename Derived>
5064 QualType
5065 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5066                                                    MemberPointerTypeLoc TL) {
5067   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5068   if (PointeeType.isNull())
5069     return QualType();
5070 
5071   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5072   TypeSourceInfo *NewClsTInfo = nullptr;
5073   if (OldClsTInfo) {
5074     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5075     if (!NewClsTInfo)
5076       return QualType();
5077   }
5078 
5079   const MemberPointerType *T = TL.getTypePtr();
5080   QualType OldClsType = QualType(T->getClass(), 0);
5081   QualType NewClsType;
5082   if (NewClsTInfo)
5083     NewClsType = NewClsTInfo->getType();
5084   else {
5085     NewClsType = getDerived().TransformType(OldClsType);
5086     if (NewClsType.isNull())
5087       return QualType();
5088   }
5089 
5090   QualType Result = TL.getType();
5091   if (getDerived().AlwaysRebuild() ||
5092       PointeeType != T->getPointeeType() ||
5093       NewClsType != OldClsType) {
5094     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5095                                                    TL.getStarLoc());
5096     if (Result.isNull())
5097       return QualType();
5098   }
5099 
5100   // If we had to adjust the pointee type when building a member pointer, make
5101   // sure to push TypeLoc info for it.
5102   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5103   if (MPT && PointeeType != MPT->getPointeeType()) {
5104     assert(isa<AdjustedType>(MPT->getPointeeType()));
5105     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5106   }
5107 
5108   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5109   NewTL.setSigilLoc(TL.getSigilLoc());
5110   NewTL.setClassTInfo(NewClsTInfo);
5111 
5112   return Result;
5113 }
5114 
5115 template<typename Derived>
5116 QualType
5117 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5118                                                    ConstantArrayTypeLoc TL) {
5119   const ConstantArrayType *T = TL.getTypePtr();
5120   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5121   if (ElementType.isNull())
5122     return QualType();
5123 
5124   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5125   Expr *OldSize = TL.getSizeExpr();
5126   if (!OldSize)
5127     OldSize = const_cast<Expr*>(T->getSizeExpr());
5128   Expr *NewSize = nullptr;
5129   if (OldSize) {
5130     EnterExpressionEvaluationContext Unevaluated(
5131         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5132     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5133     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5134   }
5135 
5136   QualType Result = TL.getType();
5137   if (getDerived().AlwaysRebuild() ||
5138       ElementType != T->getElementType() ||
5139       (T->getSizeExpr() && NewSize != OldSize)) {
5140     Result = getDerived().RebuildConstantArrayType(ElementType,
5141                                                    T->getSizeModifier(),
5142                                                    T->getSize(), NewSize,
5143                                              T->getIndexTypeCVRQualifiers(),
5144                                                    TL.getBracketsRange());
5145     if (Result.isNull())
5146       return QualType();
5147   }
5148 
5149   // We might have either a ConstantArrayType or a VariableArrayType now:
5150   // a ConstantArrayType is allowed to have an element type which is a
5151   // VariableArrayType if the type is dependent.  Fortunately, all array
5152   // types 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(NewSize);
5157 
5158   return Result;
5159 }
5160 
5161 template<typename Derived>
5162 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5163                                               TypeLocBuilder &TLB,
5164                                               IncompleteArrayTypeLoc TL) {
5165   const IncompleteArrayType *T = TL.getTypePtr();
5166   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5167   if (ElementType.isNull())
5168     return QualType();
5169 
5170   QualType Result = TL.getType();
5171   if (getDerived().AlwaysRebuild() ||
5172       ElementType != T->getElementType()) {
5173     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5174                                                      T->getSizeModifier(),
5175                                            T->getIndexTypeCVRQualifiers(),
5176                                                      TL.getBracketsRange());
5177     if (Result.isNull())
5178       return QualType();
5179   }
5180 
5181   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5182   NewTL.setLBracketLoc(TL.getLBracketLoc());
5183   NewTL.setRBracketLoc(TL.getRBracketLoc());
5184   NewTL.setSizeExpr(nullptr);
5185 
5186   return Result;
5187 }
5188 
5189 template<typename Derived>
5190 QualType
5191 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5192                                                    VariableArrayTypeLoc TL) {
5193   const VariableArrayType *T = TL.getTypePtr();
5194   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5195   if (ElementType.isNull())
5196     return QualType();
5197 
5198   ExprResult SizeResult;
5199   {
5200     EnterExpressionEvaluationContext Context(
5201         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5202     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5203   }
5204   if (SizeResult.isInvalid())
5205     return QualType();
5206   SizeResult =
5207       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5208   if (SizeResult.isInvalid())
5209     return QualType();
5210 
5211   Expr *Size = SizeResult.get();
5212 
5213   QualType Result = TL.getType();
5214   if (getDerived().AlwaysRebuild() ||
5215       ElementType != T->getElementType() ||
5216       Size != T->getSizeExpr()) {
5217     Result = getDerived().RebuildVariableArrayType(ElementType,
5218                                                    T->getSizeModifier(),
5219                                                    Size,
5220                                              T->getIndexTypeCVRQualifiers(),
5221                                                    TL.getBracketsRange());
5222     if (Result.isNull())
5223       return QualType();
5224   }
5225 
5226   // We might have constant size array now, but fortunately it has the same
5227   // location layout.
5228   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5229   NewTL.setLBracketLoc(TL.getLBracketLoc());
5230   NewTL.setRBracketLoc(TL.getRBracketLoc());
5231   NewTL.setSizeExpr(Size);
5232 
5233   return Result;
5234 }
5235 
5236 template<typename Derived>
5237 QualType
5238 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5239                                              DependentSizedArrayTypeLoc TL) {
5240   const DependentSizedArrayType *T = TL.getTypePtr();
5241   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5242   if (ElementType.isNull())
5243     return QualType();
5244 
5245   // Array bounds are constant expressions.
5246   EnterExpressionEvaluationContext Unevaluated(
5247       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5248 
5249   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5250   Expr *origSize = TL.getSizeExpr();
5251   if (!origSize) origSize = T->getSizeExpr();
5252 
5253   ExprResult sizeResult
5254     = getDerived().TransformExpr(origSize);
5255   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5256   if (sizeResult.isInvalid())
5257     return QualType();
5258 
5259   Expr *size = sizeResult.get();
5260 
5261   QualType Result = TL.getType();
5262   if (getDerived().AlwaysRebuild() ||
5263       ElementType != T->getElementType() ||
5264       size != origSize) {
5265     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5266                                                          T->getSizeModifier(),
5267                                                          size,
5268                                                 T->getIndexTypeCVRQualifiers(),
5269                                                         TL.getBracketsRange());
5270     if (Result.isNull())
5271       return QualType();
5272   }
5273 
5274   // We might have any sort of array type now, but fortunately they
5275   // all have the same location layout.
5276   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5277   NewTL.setLBracketLoc(TL.getLBracketLoc());
5278   NewTL.setRBracketLoc(TL.getRBracketLoc());
5279   NewTL.setSizeExpr(size);
5280 
5281   return Result;
5282 }
5283 
5284 template <typename Derived>
5285 QualType TreeTransform<Derived>::TransformDependentVectorType(
5286     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5287   const DependentVectorType *T = TL.getTypePtr();
5288   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5289   if (ElementType.isNull())
5290     return QualType();
5291 
5292   EnterExpressionEvaluationContext Unevaluated(
5293       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5294 
5295   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5296   Size = SemaRef.ActOnConstantExpression(Size);
5297   if (Size.isInvalid())
5298     return QualType();
5299 
5300   QualType Result = TL.getType();
5301   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5302       Size.get() != T->getSizeExpr()) {
5303     Result = getDerived().RebuildDependentVectorType(
5304         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5305     if (Result.isNull())
5306       return QualType();
5307   }
5308 
5309   // Result might be dependent or not.
5310   if (isa<DependentVectorType>(Result)) {
5311     DependentVectorTypeLoc NewTL =
5312         TLB.push<DependentVectorTypeLoc>(Result);
5313     NewTL.setNameLoc(TL.getNameLoc());
5314   } else {
5315     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5316     NewTL.setNameLoc(TL.getNameLoc());
5317   }
5318 
5319   return Result;
5320 }
5321 
5322 template<typename Derived>
5323 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5324                                       TypeLocBuilder &TLB,
5325                                       DependentSizedExtVectorTypeLoc TL) {
5326   const DependentSizedExtVectorType *T = TL.getTypePtr();
5327 
5328   // FIXME: ext vector locs should be nested
5329   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5330   if (ElementType.isNull())
5331     return QualType();
5332 
5333   // Vector sizes are constant expressions.
5334   EnterExpressionEvaluationContext Unevaluated(
5335       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5336 
5337   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5338   Size = SemaRef.ActOnConstantExpression(Size);
5339   if (Size.isInvalid())
5340     return QualType();
5341 
5342   QualType Result = TL.getType();
5343   if (getDerived().AlwaysRebuild() ||
5344       ElementType != T->getElementType() ||
5345       Size.get() != T->getSizeExpr()) {
5346     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5347                                                              Size.get(),
5348                                                          T->getAttributeLoc());
5349     if (Result.isNull())
5350       return QualType();
5351   }
5352 
5353   // Result might be dependent or not.
5354   if (isa<DependentSizedExtVectorType>(Result)) {
5355     DependentSizedExtVectorTypeLoc NewTL
5356       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5357     NewTL.setNameLoc(TL.getNameLoc());
5358   } else {
5359     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5360     NewTL.setNameLoc(TL.getNameLoc());
5361   }
5362 
5363   return Result;
5364 }
5365 
5366 template <typename Derived>
5367 QualType
5368 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5369                                                     ConstantMatrixTypeLoc TL) {
5370   const ConstantMatrixType *T = TL.getTypePtr();
5371   QualType ElementType = getDerived().TransformType(T->getElementType());
5372   if (ElementType.isNull())
5373     return QualType();
5374 
5375   QualType Result = TL.getType();
5376   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5377     Result = getDerived().RebuildConstantMatrixType(
5378         ElementType, T->getNumRows(), T->getNumColumns());
5379     if (Result.isNull())
5380       return QualType();
5381   }
5382 
5383   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5384   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5385   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5386   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5387   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5388 
5389   return Result;
5390 }
5391 
5392 template <typename Derived>
5393 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5394     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5395   const DependentSizedMatrixType *T = TL.getTypePtr();
5396 
5397   QualType ElementType = getDerived().TransformType(T->getElementType());
5398   if (ElementType.isNull()) {
5399     return QualType();
5400   }
5401 
5402   // Matrix dimensions are constant expressions.
5403   EnterExpressionEvaluationContext Unevaluated(
5404       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5405 
5406   Expr *origRows = TL.getAttrRowOperand();
5407   if (!origRows)
5408     origRows = T->getRowExpr();
5409   Expr *origColumns = TL.getAttrColumnOperand();
5410   if (!origColumns)
5411     origColumns = T->getColumnExpr();
5412 
5413   ExprResult rowResult = getDerived().TransformExpr(origRows);
5414   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5415   if (rowResult.isInvalid())
5416     return QualType();
5417 
5418   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5419   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5420   if (columnResult.isInvalid())
5421     return QualType();
5422 
5423   Expr *rows = rowResult.get();
5424   Expr *columns = columnResult.get();
5425 
5426   QualType Result = TL.getType();
5427   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5428       rows != origRows || columns != origColumns) {
5429     Result = getDerived().RebuildDependentSizedMatrixType(
5430         ElementType, rows, columns, T->getAttributeLoc());
5431 
5432     if (Result.isNull())
5433       return QualType();
5434   }
5435 
5436   // We might have any sort of matrix type now, but fortunately they
5437   // all have the same location layout.
5438   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5439   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5440   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5441   NewTL.setAttrRowOperand(rows);
5442   NewTL.setAttrColumnOperand(columns);
5443   return Result;
5444 }
5445 
5446 template <typename Derived>
5447 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5448     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5449   const DependentAddressSpaceType *T = TL.getTypePtr();
5450 
5451   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5452 
5453   if (pointeeType.isNull())
5454     return QualType();
5455 
5456   // Address spaces are constant expressions.
5457   EnterExpressionEvaluationContext Unevaluated(
5458       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5459 
5460   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5461   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5462   if (AddrSpace.isInvalid())
5463     return QualType();
5464 
5465   QualType Result = TL.getType();
5466   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5467       AddrSpace.get() != T->getAddrSpaceExpr()) {
5468     Result = getDerived().RebuildDependentAddressSpaceType(
5469         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5470     if (Result.isNull())
5471       return QualType();
5472   }
5473 
5474   // Result might be dependent or not.
5475   if (isa<DependentAddressSpaceType>(Result)) {
5476     DependentAddressSpaceTypeLoc NewTL =
5477         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5478 
5479     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5480     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5481     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5482 
5483   } else {
5484     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5485         Result, getDerived().getBaseLocation());
5486     TransformType(TLB, DI->getTypeLoc());
5487   }
5488 
5489   return Result;
5490 }
5491 
5492 template <typename Derived>
5493 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5494                                                      VectorTypeLoc TL) {
5495   const VectorType *T = TL.getTypePtr();
5496   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5497   if (ElementType.isNull())
5498     return QualType();
5499 
5500   QualType Result = TL.getType();
5501   if (getDerived().AlwaysRebuild() ||
5502       ElementType != T->getElementType()) {
5503     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5504                                             T->getVectorKind());
5505     if (Result.isNull())
5506       return QualType();
5507   }
5508 
5509   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5510   NewTL.setNameLoc(TL.getNameLoc());
5511 
5512   return Result;
5513 }
5514 
5515 template<typename Derived>
5516 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5517                                                         ExtVectorTypeLoc TL) {
5518   const VectorType *T = TL.getTypePtr();
5519   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5520   if (ElementType.isNull())
5521     return QualType();
5522 
5523   QualType Result = TL.getType();
5524   if (getDerived().AlwaysRebuild() ||
5525       ElementType != T->getElementType()) {
5526     Result = getDerived().RebuildExtVectorType(ElementType,
5527                                                T->getNumElements(),
5528                                                /*FIXME*/ SourceLocation());
5529     if (Result.isNull())
5530       return QualType();
5531   }
5532 
5533   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5534   NewTL.setNameLoc(TL.getNameLoc());
5535 
5536   return Result;
5537 }
5538 
5539 template <typename Derived>
5540 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5541     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5542     bool ExpectParameterPack) {
5543   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5544   TypeSourceInfo *NewDI = nullptr;
5545 
5546   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5547     // If we're substituting into a pack expansion type and we know the
5548     // length we want to expand to, just substitute for the pattern.
5549     TypeLoc OldTL = OldDI->getTypeLoc();
5550     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5551 
5552     TypeLocBuilder TLB;
5553     TypeLoc NewTL = OldDI->getTypeLoc();
5554     TLB.reserve(NewTL.getFullDataSize());
5555 
5556     QualType Result = getDerived().TransformType(TLB,
5557                                                OldExpansionTL.getPatternLoc());
5558     if (Result.isNull())
5559       return nullptr;
5560 
5561     Result = RebuildPackExpansionType(Result,
5562                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5563                                       OldExpansionTL.getEllipsisLoc(),
5564                                       NumExpansions);
5565     if (Result.isNull())
5566       return nullptr;
5567 
5568     PackExpansionTypeLoc NewExpansionTL
5569       = TLB.push<PackExpansionTypeLoc>(Result);
5570     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5571     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5572   } else
5573     NewDI = getDerived().TransformType(OldDI);
5574   if (!NewDI)
5575     return nullptr;
5576 
5577   if (NewDI == OldDI && indexAdjustment == 0)
5578     return OldParm;
5579 
5580   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5581                                              OldParm->getDeclContext(),
5582                                              OldParm->getInnerLocStart(),
5583                                              OldParm->getLocation(),
5584                                              OldParm->getIdentifier(),
5585                                              NewDI->getType(),
5586                                              NewDI,
5587                                              OldParm->getStorageClass(),
5588                                              /* DefArg */ nullptr);
5589   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5590                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5591   transformedLocalDecl(OldParm, {newParm});
5592   return newParm;
5593 }
5594 
5595 template <typename Derived>
5596 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5597     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5598     const QualType *ParamTypes,
5599     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5600     SmallVectorImpl<QualType> &OutParamTypes,
5601     SmallVectorImpl<ParmVarDecl *> *PVars,
5602     Sema::ExtParameterInfoBuilder &PInfos) {
5603   int indexAdjustment = 0;
5604 
5605   unsigned NumParams = Params.size();
5606   for (unsigned i = 0; i != NumParams; ++i) {
5607     if (ParmVarDecl *OldParm = Params[i]) {
5608       assert(OldParm->getFunctionScopeIndex() == i);
5609 
5610       Optional<unsigned> NumExpansions;
5611       ParmVarDecl *NewParm = nullptr;
5612       if (OldParm->isParameterPack()) {
5613         // We have a function parameter pack that may need to be expanded.
5614         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5615 
5616         // Find the parameter packs that could be expanded.
5617         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5618         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5619         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5620         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5621 
5622         // Determine whether we should expand the parameter packs.
5623         bool ShouldExpand = false;
5624         bool RetainExpansion = false;
5625         Optional<unsigned> OrigNumExpansions;
5626         if (Unexpanded.size() > 0) {
5627           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5628           NumExpansions = OrigNumExpansions;
5629           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5630                                                    Pattern.getSourceRange(),
5631                                                    Unexpanded,
5632                                                    ShouldExpand,
5633                                                    RetainExpansion,
5634                                                    NumExpansions)) {
5635             return true;
5636           }
5637         } else {
5638 #ifndef NDEBUG
5639           const AutoType *AT =
5640               Pattern.getType().getTypePtr()->getContainedAutoType();
5641           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5642                  "Could not find parameter packs or undeduced auto type!");
5643 #endif
5644         }
5645 
5646         if (ShouldExpand) {
5647           // Expand the function parameter pack into multiple, separate
5648           // parameters.
5649           getDerived().ExpandingFunctionParameterPack(OldParm);
5650           for (unsigned I = 0; I != *NumExpansions; ++I) {
5651             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5652             ParmVarDecl *NewParm
5653               = getDerived().TransformFunctionTypeParam(OldParm,
5654                                                         indexAdjustment++,
5655                                                         OrigNumExpansions,
5656                                                 /*ExpectParameterPack=*/false);
5657             if (!NewParm)
5658               return true;
5659 
5660             if (ParamInfos)
5661               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5662             OutParamTypes.push_back(NewParm->getType());
5663             if (PVars)
5664               PVars->push_back(NewParm);
5665           }
5666 
5667           // If we're supposed to retain a pack expansion, do so by temporarily
5668           // forgetting the partially-substituted parameter pack.
5669           if (RetainExpansion) {
5670             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5671             ParmVarDecl *NewParm
5672               = getDerived().TransformFunctionTypeParam(OldParm,
5673                                                         indexAdjustment++,
5674                                                         OrigNumExpansions,
5675                                                 /*ExpectParameterPack=*/false);
5676             if (!NewParm)
5677               return true;
5678 
5679             if (ParamInfos)
5680               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5681             OutParamTypes.push_back(NewParm->getType());
5682             if (PVars)
5683               PVars->push_back(NewParm);
5684           }
5685 
5686           // The next parameter should have the same adjustment as the
5687           // last thing we pushed, but we post-incremented indexAdjustment
5688           // on every push.  Also, if we push nothing, the adjustment should
5689           // go down by one.
5690           indexAdjustment--;
5691 
5692           // We're done with the pack expansion.
5693           continue;
5694         }
5695 
5696         // We'll substitute the parameter now without expanding the pack
5697         // expansion.
5698         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5699         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5700                                                           indexAdjustment,
5701                                                           NumExpansions,
5702                                                   /*ExpectParameterPack=*/true);
5703         assert(NewParm->isParameterPack() &&
5704                "Parameter pack no longer a parameter pack after "
5705                "transformation.");
5706       } else {
5707         NewParm = getDerived().TransformFunctionTypeParam(
5708             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5709       }
5710 
5711       if (!NewParm)
5712         return true;
5713 
5714       if (ParamInfos)
5715         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5716       OutParamTypes.push_back(NewParm->getType());
5717       if (PVars)
5718         PVars->push_back(NewParm);
5719       continue;
5720     }
5721 
5722     // Deal with the possibility that we don't have a parameter
5723     // declaration for this parameter.
5724     QualType OldType = ParamTypes[i];
5725     bool IsPackExpansion = false;
5726     Optional<unsigned> NumExpansions;
5727     QualType NewType;
5728     if (const PackExpansionType *Expansion
5729                                        = dyn_cast<PackExpansionType>(OldType)) {
5730       // We have a function parameter pack that may need to be expanded.
5731       QualType Pattern = Expansion->getPattern();
5732       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5733       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5734 
5735       // Determine whether we should expand the parameter packs.
5736       bool ShouldExpand = false;
5737       bool RetainExpansion = false;
5738       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5739                                                Unexpanded,
5740                                                ShouldExpand,
5741                                                RetainExpansion,
5742                                                NumExpansions)) {
5743         return true;
5744       }
5745 
5746       if (ShouldExpand) {
5747         // Expand the function parameter pack into multiple, separate
5748         // parameters.
5749         for (unsigned I = 0; I != *NumExpansions; ++I) {
5750           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5751           QualType NewType = getDerived().TransformType(Pattern);
5752           if (NewType.isNull())
5753             return true;
5754 
5755           if (NewType->containsUnexpandedParameterPack()) {
5756             NewType =
5757                 getSema().getASTContext().getPackExpansionType(NewType, None);
5758 
5759             if (NewType.isNull())
5760               return true;
5761           }
5762 
5763           if (ParamInfos)
5764             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5765           OutParamTypes.push_back(NewType);
5766           if (PVars)
5767             PVars->push_back(nullptr);
5768         }
5769 
5770         // We're done with the pack expansion.
5771         continue;
5772       }
5773 
5774       // If we're supposed to retain a pack expansion, do so by temporarily
5775       // forgetting the partially-substituted parameter pack.
5776       if (RetainExpansion) {
5777         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5778         QualType NewType = getDerived().TransformType(Pattern);
5779         if (NewType.isNull())
5780           return true;
5781 
5782         if (ParamInfos)
5783           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5784         OutParamTypes.push_back(NewType);
5785         if (PVars)
5786           PVars->push_back(nullptr);
5787       }
5788 
5789       // We'll substitute the parameter now without expanding the pack
5790       // expansion.
5791       OldType = Expansion->getPattern();
5792       IsPackExpansion = true;
5793       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5794       NewType = getDerived().TransformType(OldType);
5795     } else {
5796       NewType = getDerived().TransformType(OldType);
5797     }
5798 
5799     if (NewType.isNull())
5800       return true;
5801 
5802     if (IsPackExpansion)
5803       NewType = getSema().Context.getPackExpansionType(NewType,
5804                                                        NumExpansions);
5805 
5806     if (ParamInfos)
5807       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5808     OutParamTypes.push_back(NewType);
5809     if (PVars)
5810       PVars->push_back(nullptr);
5811   }
5812 
5813 #ifndef NDEBUG
5814   if (PVars) {
5815     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5816       if (ParmVarDecl *parm = (*PVars)[i])
5817         assert(parm->getFunctionScopeIndex() == i);
5818   }
5819 #endif
5820 
5821   return false;
5822 }
5823 
5824 template<typename Derived>
5825 QualType
5826 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5827                                                    FunctionProtoTypeLoc TL) {
5828   SmallVector<QualType, 4> ExceptionStorage;
5829   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5830   return getDerived().TransformFunctionProtoType(
5831       TLB, TL, nullptr, Qualifiers(),
5832       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5833         return This->getDerived().TransformExceptionSpec(
5834             TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
5835       });
5836 }
5837 
5838 template<typename Derived> template<typename Fn>
5839 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5840     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5841     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5842 
5843   // Transform the parameters and return type.
5844   //
5845   // We are required to instantiate the params and return type in source order.
5846   // When the function has a trailing return type, we instantiate the
5847   // parameters before the return type,  since the return type can then refer
5848   // to the parameters themselves (via decltype, sizeof, etc.).
5849   //
5850   SmallVector<QualType, 4> ParamTypes;
5851   SmallVector<ParmVarDecl*, 4> ParamDecls;
5852   Sema::ExtParameterInfoBuilder ExtParamInfos;
5853   const FunctionProtoType *T = TL.getTypePtr();
5854 
5855   QualType ResultType;
5856 
5857   if (T->hasTrailingReturn()) {
5858     if (getDerived().TransformFunctionTypeParams(
5859             TL.getBeginLoc(), TL.getParams(),
5860             TL.getTypePtr()->param_type_begin(),
5861             T->getExtParameterInfosOrNull(),
5862             ParamTypes, &ParamDecls, ExtParamInfos))
5863       return QualType();
5864 
5865     {
5866       // C++11 [expr.prim.general]p3:
5867       //   If a declaration declares a member function or member function
5868       //   template of a class X, the expression this is a prvalue of type
5869       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5870       //   and the end of the function-definition, member-declarator, or
5871       //   declarator.
5872       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5873 
5874       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5875       if (ResultType.isNull())
5876         return QualType();
5877     }
5878   }
5879   else {
5880     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5881     if (ResultType.isNull())
5882       return QualType();
5883 
5884     if (getDerived().TransformFunctionTypeParams(
5885             TL.getBeginLoc(), TL.getParams(),
5886             TL.getTypePtr()->param_type_begin(),
5887             T->getExtParameterInfosOrNull(),
5888             ParamTypes, &ParamDecls, ExtParamInfos))
5889       return QualType();
5890   }
5891 
5892   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5893 
5894   bool EPIChanged = false;
5895   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5896     return QualType();
5897 
5898   // Handle extended parameter information.
5899   if (auto NewExtParamInfos =
5900         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5901     if (!EPI.ExtParameterInfos ||
5902         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5903           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5904       EPIChanged = true;
5905     }
5906     EPI.ExtParameterInfos = NewExtParamInfos;
5907   } else if (EPI.ExtParameterInfos) {
5908     EPIChanged = true;
5909     EPI.ExtParameterInfos = nullptr;
5910   }
5911 
5912   QualType Result = TL.getType();
5913   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5914       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5915     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5916     if (Result.isNull())
5917       return QualType();
5918   }
5919 
5920   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5921   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5922   NewTL.setLParenLoc(TL.getLParenLoc());
5923   NewTL.setRParenLoc(TL.getRParenLoc());
5924   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5925   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5926   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5927     NewTL.setParam(i, ParamDecls[i]);
5928 
5929   return Result;
5930 }
5931 
5932 template<typename Derived>
5933 bool TreeTransform<Derived>::TransformExceptionSpec(
5934     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5935     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5936   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5937 
5938   // Instantiate a dynamic noexcept expression, if any.
5939   if (isComputedNoexcept(ESI.Type)) {
5940     EnterExpressionEvaluationContext Unevaluated(
5941         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5942     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5943     if (NoexceptExpr.isInvalid())
5944       return true;
5945 
5946     ExceptionSpecificationType EST = ESI.Type;
5947     NoexceptExpr =
5948         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5949     if (NoexceptExpr.isInvalid())
5950       return true;
5951 
5952     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5953       Changed = true;
5954     ESI.NoexceptExpr = NoexceptExpr.get();
5955     ESI.Type = EST;
5956   }
5957 
5958   if (ESI.Type != EST_Dynamic)
5959     return false;
5960 
5961   // Instantiate a dynamic exception specification's type.
5962   for (QualType T : ESI.Exceptions) {
5963     if (const PackExpansionType *PackExpansion =
5964             T->getAs<PackExpansionType>()) {
5965       Changed = true;
5966 
5967       // We have a pack expansion. Instantiate it.
5968       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5969       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5970                                               Unexpanded);
5971       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5972 
5973       // Determine whether the set of unexpanded parameter packs can and
5974       // should
5975       // be expanded.
5976       bool Expand = false;
5977       bool RetainExpansion = false;
5978       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5979       // FIXME: Track the location of the ellipsis (and track source location
5980       // information for the types in the exception specification in general).
5981       if (getDerived().TryExpandParameterPacks(
5982               Loc, SourceRange(), Unexpanded, Expand,
5983               RetainExpansion, NumExpansions))
5984         return true;
5985 
5986       if (!Expand) {
5987         // We can't expand this pack expansion into separate arguments yet;
5988         // just substitute into the pattern and create a new pack expansion
5989         // type.
5990         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5991         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5992         if (U.isNull())
5993           return true;
5994 
5995         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5996         Exceptions.push_back(U);
5997         continue;
5998       }
5999 
6000       // Substitute into the pack expansion pattern for each slice of the
6001       // pack.
6002       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6003         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6004 
6005         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6006         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6007           return true;
6008 
6009         Exceptions.push_back(U);
6010       }
6011     } else {
6012       QualType U = getDerived().TransformType(T);
6013       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6014         return true;
6015       if (T != U)
6016         Changed = true;
6017 
6018       Exceptions.push_back(U);
6019     }
6020   }
6021 
6022   ESI.Exceptions = Exceptions;
6023   if (ESI.Exceptions.empty())
6024     ESI.Type = EST_DynamicNone;
6025   return false;
6026 }
6027 
6028 template<typename Derived>
6029 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6030                                                  TypeLocBuilder &TLB,
6031                                                  FunctionNoProtoTypeLoc TL) {
6032   const FunctionNoProtoType *T = TL.getTypePtr();
6033   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6034   if (ResultType.isNull())
6035     return QualType();
6036 
6037   QualType Result = TL.getType();
6038   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6039     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6040 
6041   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6042   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6043   NewTL.setLParenLoc(TL.getLParenLoc());
6044   NewTL.setRParenLoc(TL.getRParenLoc());
6045   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6046 
6047   return Result;
6048 }
6049 
6050 template<typename Derived> QualType
6051 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
6052                                                  UnresolvedUsingTypeLoc TL) {
6053   const UnresolvedUsingType *T = TL.getTypePtr();
6054   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6055   if (!D)
6056     return QualType();
6057 
6058   QualType Result = TL.getType();
6059   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6060     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6061     if (Result.isNull())
6062       return QualType();
6063   }
6064 
6065   // We might get an arbitrary type spec type back.  We should at
6066   // least always get a type spec type, though.
6067   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6068   NewTL.setNameLoc(TL.getNameLoc());
6069 
6070   return Result;
6071 }
6072 
6073 template<typename Derived>
6074 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6075                                                       TypedefTypeLoc TL) {
6076   const TypedefType *T = TL.getTypePtr();
6077   TypedefNameDecl *Typedef
6078     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6079                                                                T->getDecl()));
6080   if (!Typedef)
6081     return QualType();
6082 
6083   QualType Result = TL.getType();
6084   if (getDerived().AlwaysRebuild() ||
6085       Typedef != T->getDecl()) {
6086     Result = getDerived().RebuildTypedefType(Typedef);
6087     if (Result.isNull())
6088       return QualType();
6089   }
6090 
6091   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6092   NewTL.setNameLoc(TL.getNameLoc());
6093 
6094   return Result;
6095 }
6096 
6097 template<typename Derived>
6098 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6099                                                       TypeOfExprTypeLoc TL) {
6100   // typeof expressions are not potentially evaluated contexts
6101   EnterExpressionEvaluationContext Unevaluated(
6102       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6103       Sema::ReuseLambdaContextDecl);
6104 
6105   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6106   if (E.isInvalid())
6107     return QualType();
6108 
6109   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6110   if (E.isInvalid())
6111     return QualType();
6112 
6113   QualType Result = TL.getType();
6114   if (getDerived().AlwaysRebuild() ||
6115       E.get() != TL.getUnderlyingExpr()) {
6116     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
6117     if (Result.isNull())
6118       return QualType();
6119   }
6120   else E.get();
6121 
6122   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6123   NewTL.setTypeofLoc(TL.getTypeofLoc());
6124   NewTL.setLParenLoc(TL.getLParenLoc());
6125   NewTL.setRParenLoc(TL.getRParenLoc());
6126 
6127   return Result;
6128 }
6129 
6130 template<typename Derived>
6131 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6132                                                      TypeOfTypeLoc TL) {
6133   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
6134   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6135   if (!New_Under_TI)
6136     return QualType();
6137 
6138   QualType Result = TL.getType();
6139   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6140     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
6141     if (Result.isNull())
6142       return QualType();
6143   }
6144 
6145   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6146   NewTL.setTypeofLoc(TL.getTypeofLoc());
6147   NewTL.setLParenLoc(TL.getLParenLoc());
6148   NewTL.setRParenLoc(TL.getRParenLoc());
6149   NewTL.setUnderlyingTInfo(New_Under_TI);
6150 
6151   return Result;
6152 }
6153 
6154 template<typename Derived>
6155 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6156                                                        DecltypeTypeLoc TL) {
6157   const DecltypeType *T = TL.getTypePtr();
6158 
6159   // decltype expressions are not potentially evaluated contexts
6160   EnterExpressionEvaluationContext Unevaluated(
6161       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6162       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6163 
6164   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6165   if (E.isInvalid())
6166     return QualType();
6167 
6168   E = getSema().ActOnDecltypeExpression(E.get());
6169   if (E.isInvalid())
6170     return QualType();
6171 
6172   QualType Result = TL.getType();
6173   if (getDerived().AlwaysRebuild() ||
6174       E.get() != T->getUnderlyingExpr()) {
6175     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
6176     if (Result.isNull())
6177       return QualType();
6178   }
6179   else E.get();
6180 
6181   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6182   NewTL.setNameLoc(TL.getNameLoc());
6183 
6184   return Result;
6185 }
6186 
6187 template<typename Derived>
6188 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6189                                                             TypeLocBuilder &TLB,
6190                                                      UnaryTransformTypeLoc TL) {
6191   QualType Result = TL.getType();
6192   if (Result->isDependentType()) {
6193     const UnaryTransformType *T = TL.getTypePtr();
6194     QualType NewBase =
6195       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6196     Result = getDerived().RebuildUnaryTransformType(NewBase,
6197                                                     T->getUTTKind(),
6198                                                     TL.getKWLoc());
6199     if (Result.isNull())
6200       return QualType();
6201   }
6202 
6203   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6204   NewTL.setKWLoc(TL.getKWLoc());
6205   NewTL.setParensRange(TL.getParensRange());
6206   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6207   return Result;
6208 }
6209 
6210 template<typename Derived>
6211 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6212     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6213   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6214 
6215   CXXScopeSpec SS;
6216   TemplateName TemplateName = getDerived().TransformTemplateName(
6217       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6218   if (TemplateName.isNull())
6219     return QualType();
6220 
6221   QualType OldDeduced = T->getDeducedType();
6222   QualType NewDeduced;
6223   if (!OldDeduced.isNull()) {
6224     NewDeduced = getDerived().TransformType(OldDeduced);
6225     if (NewDeduced.isNull())
6226       return QualType();
6227   }
6228 
6229   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6230       TemplateName, NewDeduced);
6231   if (Result.isNull())
6232     return QualType();
6233 
6234   DeducedTemplateSpecializationTypeLoc NewTL =
6235       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6236   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6237 
6238   return Result;
6239 }
6240 
6241 template<typename Derived>
6242 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6243                                                      RecordTypeLoc TL) {
6244   const RecordType *T = TL.getTypePtr();
6245   RecordDecl *Record
6246     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6247                                                           T->getDecl()));
6248   if (!Record)
6249     return QualType();
6250 
6251   QualType Result = TL.getType();
6252   if (getDerived().AlwaysRebuild() ||
6253       Record != T->getDecl()) {
6254     Result = getDerived().RebuildRecordType(Record);
6255     if (Result.isNull())
6256       return QualType();
6257   }
6258 
6259   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6260   NewTL.setNameLoc(TL.getNameLoc());
6261 
6262   return Result;
6263 }
6264 
6265 template<typename Derived>
6266 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6267                                                    EnumTypeLoc TL) {
6268   const EnumType *T = TL.getTypePtr();
6269   EnumDecl *Enum
6270     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6271                                                         T->getDecl()));
6272   if (!Enum)
6273     return QualType();
6274 
6275   QualType Result = TL.getType();
6276   if (getDerived().AlwaysRebuild() ||
6277       Enum != T->getDecl()) {
6278     Result = getDerived().RebuildEnumType(Enum);
6279     if (Result.isNull())
6280       return QualType();
6281   }
6282 
6283   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6284   NewTL.setNameLoc(TL.getNameLoc());
6285 
6286   return Result;
6287 }
6288 
6289 template<typename Derived>
6290 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6291                                          TypeLocBuilder &TLB,
6292                                          InjectedClassNameTypeLoc TL) {
6293   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6294                                        TL.getTypePtr()->getDecl());
6295   if (!D) return QualType();
6296 
6297   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6298   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6299   return T;
6300 }
6301 
6302 template<typename Derived>
6303 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6304                                                 TypeLocBuilder &TLB,
6305                                                 TemplateTypeParmTypeLoc TL) {
6306   return TransformTypeSpecType(TLB, TL);
6307 }
6308 
6309 template<typename Derived>
6310 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6311                                          TypeLocBuilder &TLB,
6312                                          SubstTemplateTypeParmTypeLoc TL) {
6313   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6314 
6315   // Substitute into the replacement type, which itself might involve something
6316   // that needs to be transformed. This only tends to occur with default
6317   // template arguments of template template parameters.
6318   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6319   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6320   if (Replacement.isNull())
6321     return QualType();
6322 
6323   // Always canonicalize the replacement type.
6324   Replacement = SemaRef.Context.getCanonicalType(Replacement);
6325   QualType Result
6326     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
6327                                                    Replacement);
6328 
6329   // Propagate type-source information.
6330   SubstTemplateTypeParmTypeLoc NewTL
6331     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6332   NewTL.setNameLoc(TL.getNameLoc());
6333   return Result;
6334 
6335 }
6336 
6337 template<typename Derived>
6338 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6339                                           TypeLocBuilder &TLB,
6340                                           SubstTemplateTypeParmPackTypeLoc TL) {
6341   return TransformTypeSpecType(TLB, TL);
6342 }
6343 
6344 template<typename Derived>
6345 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6346                                                         TypeLocBuilder &TLB,
6347                                            TemplateSpecializationTypeLoc TL) {
6348   const TemplateSpecializationType *T = TL.getTypePtr();
6349 
6350   // The nested-name-specifier never matters in a TemplateSpecializationType,
6351   // because we can't have a dependent nested-name-specifier anyway.
6352   CXXScopeSpec SS;
6353   TemplateName Template
6354     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6355                                          TL.getTemplateNameLoc());
6356   if (Template.isNull())
6357     return QualType();
6358 
6359   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6360 }
6361 
6362 template<typename Derived>
6363 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6364                                                      AtomicTypeLoc TL) {
6365   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6366   if (ValueType.isNull())
6367     return QualType();
6368 
6369   QualType Result = TL.getType();
6370   if (getDerived().AlwaysRebuild() ||
6371       ValueType != TL.getValueLoc().getType()) {
6372     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6373     if (Result.isNull())
6374       return QualType();
6375   }
6376 
6377   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6378   NewTL.setKWLoc(TL.getKWLoc());
6379   NewTL.setLParenLoc(TL.getLParenLoc());
6380   NewTL.setRParenLoc(TL.getRParenLoc());
6381 
6382   return Result;
6383 }
6384 
6385 template <typename Derived>
6386 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6387                                                    PipeTypeLoc TL) {
6388   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6389   if (ValueType.isNull())
6390     return QualType();
6391 
6392   QualType Result = TL.getType();
6393   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6394     const PipeType *PT = Result->castAs<PipeType>();
6395     bool isReadPipe = PT->isReadOnly();
6396     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6397     if (Result.isNull())
6398       return QualType();
6399   }
6400 
6401   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6402   NewTL.setKWLoc(TL.getKWLoc());
6403 
6404   return Result;
6405 }
6406 
6407 template <typename Derived>
6408 QualType TreeTransform<Derived>::TransformExtIntType(TypeLocBuilder &TLB,
6409                                                      ExtIntTypeLoc TL) {
6410   const ExtIntType *EIT = TL.getTypePtr();
6411   QualType Result = TL.getType();
6412 
6413   if (getDerived().AlwaysRebuild()) {
6414     Result = getDerived().RebuildExtIntType(EIT->isUnsigned(),
6415                                             EIT->getNumBits(), TL.getNameLoc());
6416     if (Result.isNull())
6417       return QualType();
6418   }
6419 
6420   ExtIntTypeLoc NewTL = TLB.push<ExtIntTypeLoc>(Result);
6421   NewTL.setNameLoc(TL.getNameLoc());
6422   return Result;
6423 }
6424 
6425 template <typename Derived>
6426 QualType TreeTransform<Derived>::TransformDependentExtIntType(
6427     TypeLocBuilder &TLB, DependentExtIntTypeLoc TL) {
6428   const DependentExtIntType *EIT = TL.getTypePtr();
6429 
6430   EnterExpressionEvaluationContext Unevaluated(
6431       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6432   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6433   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6434 
6435   if (BitsExpr.isInvalid())
6436     return QualType();
6437 
6438   QualType Result = TL.getType();
6439 
6440   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6441     Result = getDerived().RebuildDependentExtIntType(
6442         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6443 
6444     if (Result.isNull())
6445       return QualType();
6446   }
6447 
6448   if (isa<DependentExtIntType>(Result)) {
6449     DependentExtIntTypeLoc NewTL = TLB.push<DependentExtIntTypeLoc>(Result);
6450     NewTL.setNameLoc(TL.getNameLoc());
6451   } else {
6452     ExtIntTypeLoc NewTL = TLB.push<ExtIntTypeLoc>(Result);
6453     NewTL.setNameLoc(TL.getNameLoc());
6454   }
6455   return Result;
6456 }
6457 
6458   /// Simple iterator that traverses the template arguments in a
6459   /// container that provides a \c getArgLoc() member function.
6460   ///
6461   /// This iterator is intended to be used with the iterator form of
6462   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6463   template<typename ArgLocContainer>
6464   class TemplateArgumentLocContainerIterator {
6465     ArgLocContainer *Container;
6466     unsigned Index;
6467 
6468   public:
6469     typedef TemplateArgumentLoc value_type;
6470     typedef TemplateArgumentLoc reference;
6471     typedef int difference_type;
6472     typedef std::input_iterator_tag iterator_category;
6473 
6474     class pointer {
6475       TemplateArgumentLoc Arg;
6476 
6477     public:
6478       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6479 
6480       const TemplateArgumentLoc *operator->() const {
6481         return &Arg;
6482       }
6483     };
6484 
6485 
6486     TemplateArgumentLocContainerIterator() {}
6487 
6488     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6489                                  unsigned Index)
6490       : Container(&Container), Index(Index) { }
6491 
6492     TemplateArgumentLocContainerIterator &operator++() {
6493       ++Index;
6494       return *this;
6495     }
6496 
6497     TemplateArgumentLocContainerIterator operator++(int) {
6498       TemplateArgumentLocContainerIterator Old(*this);
6499       ++(*this);
6500       return Old;
6501     }
6502 
6503     TemplateArgumentLoc operator*() const {
6504       return Container->getArgLoc(Index);
6505     }
6506 
6507     pointer operator->() const {
6508       return pointer(Container->getArgLoc(Index));
6509     }
6510 
6511     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6512                            const TemplateArgumentLocContainerIterator &Y) {
6513       return X.Container == Y.Container && X.Index == Y.Index;
6514     }
6515 
6516     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6517                            const TemplateArgumentLocContainerIterator &Y) {
6518       return !(X == Y);
6519     }
6520   };
6521 
6522 template<typename Derived>
6523 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6524                                                    AutoTypeLoc TL) {
6525   const AutoType *T = TL.getTypePtr();
6526   QualType OldDeduced = T->getDeducedType();
6527   QualType NewDeduced;
6528   if (!OldDeduced.isNull()) {
6529     NewDeduced = getDerived().TransformType(OldDeduced);
6530     if (NewDeduced.isNull())
6531       return QualType();
6532   }
6533 
6534   ConceptDecl *NewCD = nullptr;
6535   TemplateArgumentListInfo NewTemplateArgs;
6536   NestedNameSpecifierLoc NewNestedNameSpec;
6537   if (T->isConstrained()) {
6538     NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6539         TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6540 
6541     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6542     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6543     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6544     if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6545                                                 ArgIterator(TL,
6546                                                             TL.getNumArgs()),
6547                                                 NewTemplateArgs))
6548       return QualType();
6549 
6550     if (TL.getNestedNameSpecifierLoc()) {
6551       NewNestedNameSpec
6552         = getDerived().TransformNestedNameSpecifierLoc(
6553             TL.getNestedNameSpecifierLoc());
6554       if (!NewNestedNameSpec)
6555         return QualType();
6556     }
6557   }
6558 
6559   QualType Result = TL.getType();
6560   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6561       T->isDependentType() || T->isConstrained()) {
6562     // FIXME: Maybe don't rebuild if all template arguments are the same.
6563     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6564     NewArgList.reserve(NewArgList.size());
6565     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6566       NewArgList.push_back(ArgLoc.getArgument());
6567     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6568                                           NewArgList);
6569     if (Result.isNull())
6570       return QualType();
6571   }
6572 
6573   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6574   NewTL.setNameLoc(TL.getNameLoc());
6575   NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6576   NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6577   NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6578   NewTL.setFoundDecl(TL.getFoundDecl());
6579   NewTL.setLAngleLoc(TL.getLAngleLoc());
6580   NewTL.setRAngleLoc(TL.getRAngleLoc());
6581   for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6582     NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6583 
6584   return Result;
6585 }
6586 
6587 template <typename Derived>
6588 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6589                                                         TypeLocBuilder &TLB,
6590                                            TemplateSpecializationTypeLoc TL,
6591                                                       TemplateName Template) {
6592   TemplateArgumentListInfo NewTemplateArgs;
6593   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6594   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6595   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6596     ArgIterator;
6597   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6598                                               ArgIterator(TL, TL.getNumArgs()),
6599                                               NewTemplateArgs))
6600     return QualType();
6601 
6602   // FIXME: maybe don't rebuild if all the template arguments are the same.
6603 
6604   QualType Result =
6605     getDerived().RebuildTemplateSpecializationType(Template,
6606                                                    TL.getTemplateNameLoc(),
6607                                                    NewTemplateArgs);
6608 
6609   if (!Result.isNull()) {
6610     // Specializations of template template parameters are represented as
6611     // TemplateSpecializationTypes, and substitution of type alias templates
6612     // within a dependent context can transform them into
6613     // DependentTemplateSpecializationTypes.
6614     if (isa<DependentTemplateSpecializationType>(Result)) {
6615       DependentTemplateSpecializationTypeLoc NewTL
6616         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6617       NewTL.setElaboratedKeywordLoc(SourceLocation());
6618       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6619       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6620       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6621       NewTL.setLAngleLoc(TL.getLAngleLoc());
6622       NewTL.setRAngleLoc(TL.getRAngleLoc());
6623       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6624         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6625       return Result;
6626     }
6627 
6628     TemplateSpecializationTypeLoc NewTL
6629       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6630     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6631     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6632     NewTL.setLAngleLoc(TL.getLAngleLoc());
6633     NewTL.setRAngleLoc(TL.getRAngleLoc());
6634     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6635       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6636   }
6637 
6638   return Result;
6639 }
6640 
6641 template <typename Derived>
6642 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6643                                      TypeLocBuilder &TLB,
6644                                      DependentTemplateSpecializationTypeLoc TL,
6645                                      TemplateName Template,
6646                                      CXXScopeSpec &SS) {
6647   TemplateArgumentListInfo NewTemplateArgs;
6648   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6649   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6650   typedef TemplateArgumentLocContainerIterator<
6651             DependentTemplateSpecializationTypeLoc> ArgIterator;
6652   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6653                                               ArgIterator(TL, TL.getNumArgs()),
6654                                               NewTemplateArgs))
6655     return QualType();
6656 
6657   // FIXME: maybe don't rebuild if all the template arguments are the same.
6658 
6659   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6660     QualType Result
6661       = getSema().Context.getDependentTemplateSpecializationType(
6662                                                 TL.getTypePtr()->getKeyword(),
6663                                                          DTN->getQualifier(),
6664                                                          DTN->getIdentifier(),
6665                                                                NewTemplateArgs);
6666 
6667     DependentTemplateSpecializationTypeLoc NewTL
6668       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6669     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6670     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6671     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6672     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6673     NewTL.setLAngleLoc(TL.getLAngleLoc());
6674     NewTL.setRAngleLoc(TL.getRAngleLoc());
6675     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6676       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6677     return Result;
6678   }
6679 
6680   QualType Result
6681     = getDerived().RebuildTemplateSpecializationType(Template,
6682                                                      TL.getTemplateNameLoc(),
6683                                                      NewTemplateArgs);
6684 
6685   if (!Result.isNull()) {
6686     /// FIXME: Wrap this in an elaborated-type-specifier?
6687     TemplateSpecializationTypeLoc NewTL
6688       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6689     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6690     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6691     NewTL.setLAngleLoc(TL.getLAngleLoc());
6692     NewTL.setRAngleLoc(TL.getRAngleLoc());
6693     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6694       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6695   }
6696 
6697   return Result;
6698 }
6699 
6700 template<typename Derived>
6701 QualType
6702 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6703                                                 ElaboratedTypeLoc TL) {
6704   const ElaboratedType *T = TL.getTypePtr();
6705 
6706   NestedNameSpecifierLoc QualifierLoc;
6707   // NOTE: the qualifier in an ElaboratedType is optional.
6708   if (TL.getQualifierLoc()) {
6709     QualifierLoc
6710       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6711     if (!QualifierLoc)
6712       return QualType();
6713   }
6714 
6715   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6716   if (NamedT.isNull())
6717     return QualType();
6718 
6719   // C++0x [dcl.type.elab]p2:
6720   //   If the identifier resolves to a typedef-name or the simple-template-id
6721   //   resolves to an alias template specialization, the
6722   //   elaborated-type-specifier is ill-formed.
6723   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6724     if (const TemplateSpecializationType *TST =
6725           NamedT->getAs<TemplateSpecializationType>()) {
6726       TemplateName Template = TST->getTemplateName();
6727       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6728               Template.getAsTemplateDecl())) {
6729         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6730                      diag::err_tag_reference_non_tag)
6731             << TAT << Sema::NTK_TypeAliasTemplate
6732             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6733         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6734       }
6735     }
6736   }
6737 
6738   QualType Result = TL.getType();
6739   if (getDerived().AlwaysRebuild() ||
6740       QualifierLoc != TL.getQualifierLoc() ||
6741       NamedT != T->getNamedType()) {
6742     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6743                                                 T->getKeyword(),
6744                                                 QualifierLoc, NamedT);
6745     if (Result.isNull())
6746       return QualType();
6747   }
6748 
6749   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6750   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6751   NewTL.setQualifierLoc(QualifierLoc);
6752   return Result;
6753 }
6754 
6755 template<typename Derived>
6756 QualType TreeTransform<Derived>::TransformAttributedType(
6757                                                 TypeLocBuilder &TLB,
6758                                                 AttributedTypeLoc TL) {
6759   const AttributedType *oldType = TL.getTypePtr();
6760   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6761   if (modifiedType.isNull())
6762     return QualType();
6763 
6764   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6765   const Attr *oldAttr = TL.getAttr();
6766   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6767   if (oldAttr && !newAttr)
6768     return QualType();
6769 
6770   QualType result = TL.getType();
6771 
6772   // FIXME: dependent operand expressions?
6773   if (getDerived().AlwaysRebuild() ||
6774       modifiedType != oldType->getModifiedType()) {
6775     // TODO: this is really lame; we should really be rebuilding the
6776     // equivalent type from first principles.
6777     QualType equivalentType
6778       = getDerived().TransformType(oldType->getEquivalentType());
6779     if (equivalentType.isNull())
6780       return QualType();
6781 
6782     // Check whether we can add nullability; it is only represented as
6783     // type sugar, and therefore cannot be diagnosed in any other way.
6784     if (auto nullability = oldType->getImmediateNullability()) {
6785       if (!modifiedType->canHaveNullability()) {
6786         SemaRef.Diag(TL.getAttr()->getLocation(),
6787                      diag::err_nullability_nonpointer)
6788             << DiagNullabilityKind(*nullability, false) << modifiedType;
6789         return QualType();
6790       }
6791     }
6792 
6793     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6794                                                modifiedType,
6795                                                equivalentType);
6796   }
6797 
6798   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6799   newTL.setAttr(newAttr);
6800   return result;
6801 }
6802 
6803 template<typename Derived>
6804 QualType
6805 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6806                                            ParenTypeLoc TL) {
6807   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6808   if (Inner.isNull())
6809     return QualType();
6810 
6811   QualType Result = TL.getType();
6812   if (getDerived().AlwaysRebuild() ||
6813       Inner != TL.getInnerLoc().getType()) {
6814     Result = getDerived().RebuildParenType(Inner);
6815     if (Result.isNull())
6816       return QualType();
6817   }
6818 
6819   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6820   NewTL.setLParenLoc(TL.getLParenLoc());
6821   NewTL.setRParenLoc(TL.getRParenLoc());
6822   return Result;
6823 }
6824 
6825 template <typename Derived>
6826 QualType
6827 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6828                                                     MacroQualifiedTypeLoc TL) {
6829   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6830   if (Inner.isNull())
6831     return QualType();
6832 
6833   QualType Result = TL.getType();
6834   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6835     Result =
6836         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6837     if (Result.isNull())
6838       return QualType();
6839   }
6840 
6841   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6842   NewTL.setExpansionLoc(TL.getExpansionLoc());
6843   return Result;
6844 }
6845 
6846 template<typename Derived>
6847 QualType TreeTransform<Derived>::TransformDependentNameType(
6848     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6849   return TransformDependentNameType(TLB, TL, false);
6850 }
6851 
6852 template<typename Derived>
6853 QualType TreeTransform<Derived>::TransformDependentNameType(
6854     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6855   const DependentNameType *T = TL.getTypePtr();
6856 
6857   NestedNameSpecifierLoc QualifierLoc
6858     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6859   if (!QualifierLoc)
6860     return QualType();
6861 
6862   QualType Result
6863     = getDerived().RebuildDependentNameType(T->getKeyword(),
6864                                             TL.getElaboratedKeywordLoc(),
6865                                             QualifierLoc,
6866                                             T->getIdentifier(),
6867                                             TL.getNameLoc(),
6868                                             DeducedTSTContext);
6869   if (Result.isNull())
6870     return QualType();
6871 
6872   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6873     QualType NamedT = ElabT->getNamedType();
6874     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6875 
6876     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6877     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6878     NewTL.setQualifierLoc(QualifierLoc);
6879   } else {
6880     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6881     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6882     NewTL.setQualifierLoc(QualifierLoc);
6883     NewTL.setNameLoc(TL.getNameLoc());
6884   }
6885   return Result;
6886 }
6887 
6888 template<typename Derived>
6889 QualType TreeTransform<Derived>::
6890           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6891                                  DependentTemplateSpecializationTypeLoc TL) {
6892   NestedNameSpecifierLoc QualifierLoc;
6893   if (TL.getQualifierLoc()) {
6894     QualifierLoc
6895       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6896     if (!QualifierLoc)
6897       return QualType();
6898   }
6899 
6900   return getDerived()
6901            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6902 }
6903 
6904 template<typename Derived>
6905 QualType TreeTransform<Derived>::
6906 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6907                                    DependentTemplateSpecializationTypeLoc TL,
6908                                        NestedNameSpecifierLoc QualifierLoc) {
6909   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6910 
6911   TemplateArgumentListInfo NewTemplateArgs;
6912   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6913   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6914 
6915   typedef TemplateArgumentLocContainerIterator<
6916   DependentTemplateSpecializationTypeLoc> ArgIterator;
6917   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6918                                               ArgIterator(TL, TL.getNumArgs()),
6919                                               NewTemplateArgs))
6920     return QualType();
6921 
6922   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6923       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6924       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6925       /*AllowInjectedClassName*/ false);
6926   if (Result.isNull())
6927     return QualType();
6928 
6929   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6930     QualType NamedT = ElabT->getNamedType();
6931 
6932     // Copy information relevant to the template specialization.
6933     TemplateSpecializationTypeLoc NamedTL
6934       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6935     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6936     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6937     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6938     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6939     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6940       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6941 
6942     // Copy information relevant to the elaborated type.
6943     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6944     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6945     NewTL.setQualifierLoc(QualifierLoc);
6946   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6947     DependentTemplateSpecializationTypeLoc SpecTL
6948       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6949     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6950     SpecTL.setQualifierLoc(QualifierLoc);
6951     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6952     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6953     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6954     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6955     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6956       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6957   } else {
6958     TemplateSpecializationTypeLoc SpecTL
6959       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6960     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6961     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6962     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6963     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6964     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6965       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6966   }
6967   return Result;
6968 }
6969 
6970 template<typename Derived>
6971 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6972                                                       PackExpansionTypeLoc TL) {
6973   QualType Pattern
6974     = getDerived().TransformType(TLB, TL.getPatternLoc());
6975   if (Pattern.isNull())
6976     return QualType();
6977 
6978   QualType Result = TL.getType();
6979   if (getDerived().AlwaysRebuild() ||
6980       Pattern != TL.getPatternLoc().getType()) {
6981     Result = getDerived().RebuildPackExpansionType(Pattern,
6982                                            TL.getPatternLoc().getSourceRange(),
6983                                                    TL.getEllipsisLoc(),
6984                                            TL.getTypePtr()->getNumExpansions());
6985     if (Result.isNull())
6986       return QualType();
6987   }
6988 
6989   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6990   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6991   return Result;
6992 }
6993 
6994 template<typename Derived>
6995 QualType
6996 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6997                                                    ObjCInterfaceTypeLoc TL) {
6998   // ObjCInterfaceType is never dependent.
6999   TLB.pushFullCopy(TL);
7000   return TL.getType();
7001 }
7002 
7003 template<typename Derived>
7004 QualType
7005 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7006                                                    ObjCTypeParamTypeLoc TL) {
7007   const ObjCTypeParamType *T = TL.getTypePtr();
7008   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7009       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7010   if (!OTP)
7011     return QualType();
7012 
7013   QualType Result = TL.getType();
7014   if (getDerived().AlwaysRebuild() ||
7015       OTP != T->getDecl()) {
7016     Result = getDerived().RebuildObjCTypeParamType(OTP,
7017                  TL.getProtocolLAngleLoc(),
7018                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
7019                                     TL.getNumProtocols()),
7020                  TL.getProtocolLocs(),
7021                  TL.getProtocolRAngleLoc());
7022     if (Result.isNull())
7023       return QualType();
7024   }
7025 
7026   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7027   if (TL.getNumProtocols()) {
7028     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7029     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7030       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7031     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7032   }
7033   return Result;
7034 }
7035 
7036 template<typename Derived>
7037 QualType
7038 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7039                                                 ObjCObjectTypeLoc TL) {
7040   // Transform base type.
7041   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7042   if (BaseType.isNull())
7043     return QualType();
7044 
7045   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7046 
7047   // Transform type arguments.
7048   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7049   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7050     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7051     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7052     QualType TypeArg = TypeArgInfo->getType();
7053     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7054       AnyChanged = true;
7055 
7056       // We have a pack expansion. Instantiate it.
7057       const auto *PackExpansion = PackExpansionLoc.getType()
7058                                     ->castAs<PackExpansionType>();
7059       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7060       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7061                                               Unexpanded);
7062       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
7063 
7064       // Determine whether the set of unexpanded parameter packs can
7065       // and should be expanded.
7066       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7067       bool Expand = false;
7068       bool RetainExpansion = false;
7069       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7070       if (getDerived().TryExpandParameterPacks(
7071             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7072             Unexpanded, Expand, RetainExpansion, NumExpansions))
7073         return QualType();
7074 
7075       if (!Expand) {
7076         // We can't expand this pack expansion into separate arguments yet;
7077         // just substitute into the pattern and create a new pack expansion
7078         // type.
7079         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7080 
7081         TypeLocBuilder TypeArgBuilder;
7082         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7083         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7084                                                              PatternLoc);
7085         if (NewPatternType.isNull())
7086           return QualType();
7087 
7088         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7089                                       NewPatternType, NumExpansions);
7090         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7091         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7092         NewTypeArgInfos.push_back(
7093           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7094         continue;
7095       }
7096 
7097       // Substitute into the pack expansion pattern for each slice of the
7098       // pack.
7099       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7100         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7101 
7102         TypeLocBuilder TypeArgBuilder;
7103         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7104 
7105         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7106                                                          PatternLoc);
7107         if (NewTypeArg.isNull())
7108           return QualType();
7109 
7110         NewTypeArgInfos.push_back(
7111           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7112       }
7113 
7114       continue;
7115     }
7116 
7117     TypeLocBuilder TypeArgBuilder;
7118     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7119     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7120     if (NewTypeArg.isNull())
7121       return QualType();
7122 
7123     // If nothing changed, just keep the old TypeSourceInfo.
7124     if (NewTypeArg == TypeArg) {
7125       NewTypeArgInfos.push_back(TypeArgInfo);
7126       continue;
7127     }
7128 
7129     NewTypeArgInfos.push_back(
7130       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7131     AnyChanged = true;
7132   }
7133 
7134   QualType Result = TL.getType();
7135   if (getDerived().AlwaysRebuild() || AnyChanged) {
7136     // Rebuild the type.
7137     Result = getDerived().RebuildObjCObjectType(
7138         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7139         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7140         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7141         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7142 
7143     if (Result.isNull())
7144       return QualType();
7145   }
7146 
7147   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7148   NewT.setHasBaseTypeAsWritten(true);
7149   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7150   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7151     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7152   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7153   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7154   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7155     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7156   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7157   return Result;
7158 }
7159 
7160 template<typename Derived>
7161 QualType
7162 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7163                                                ObjCObjectPointerTypeLoc TL) {
7164   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7165   if (PointeeType.isNull())
7166     return QualType();
7167 
7168   QualType Result = TL.getType();
7169   if (getDerived().AlwaysRebuild() ||
7170       PointeeType != TL.getPointeeLoc().getType()) {
7171     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7172                                                        TL.getStarLoc());
7173     if (Result.isNull())
7174       return QualType();
7175   }
7176 
7177   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7178   NewT.setStarLoc(TL.getStarLoc());
7179   return Result;
7180 }
7181 
7182 //===----------------------------------------------------------------------===//
7183 // Statement transformation
7184 //===----------------------------------------------------------------------===//
7185 template<typename Derived>
7186 StmtResult
7187 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7188   return S;
7189 }
7190 
7191 template<typename Derived>
7192 StmtResult
7193 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7194   return getDerived().TransformCompoundStmt(S, false);
7195 }
7196 
7197 template<typename Derived>
7198 StmtResult
7199 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7200                                               bool IsStmtExpr) {
7201   Sema::CompoundScopeRAII CompoundScope(getSema());
7202 
7203   const Stmt *ExprResult = S->getStmtExprResult();
7204   bool SubStmtInvalid = false;
7205   bool SubStmtChanged = false;
7206   SmallVector<Stmt*, 8> Statements;
7207   for (auto *B : S->body()) {
7208     StmtResult Result = getDerived().TransformStmt(
7209         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7210 
7211     if (Result.isInvalid()) {
7212       // Immediately fail if this was a DeclStmt, since it's very
7213       // likely that this will cause problems for future statements.
7214       if (isa<DeclStmt>(B))
7215         return StmtError();
7216 
7217       // Otherwise, just keep processing substatements and fail later.
7218       SubStmtInvalid = true;
7219       continue;
7220     }
7221 
7222     SubStmtChanged = SubStmtChanged || Result.get() != B;
7223     Statements.push_back(Result.getAs<Stmt>());
7224   }
7225 
7226   if (SubStmtInvalid)
7227     return StmtError();
7228 
7229   if (!getDerived().AlwaysRebuild() &&
7230       !SubStmtChanged)
7231     return S;
7232 
7233   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7234                                           Statements,
7235                                           S->getRBracLoc(),
7236                                           IsStmtExpr);
7237 }
7238 
7239 template<typename Derived>
7240 StmtResult
7241 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7242   ExprResult LHS, RHS;
7243   {
7244     EnterExpressionEvaluationContext Unevaluated(
7245         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7246 
7247     // Transform the left-hand case value.
7248     LHS = getDerived().TransformExpr(S->getLHS());
7249     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7250     if (LHS.isInvalid())
7251       return StmtError();
7252 
7253     // Transform the right-hand case value (for the GNU case-range extension).
7254     RHS = getDerived().TransformExpr(S->getRHS());
7255     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7256     if (RHS.isInvalid())
7257       return StmtError();
7258   }
7259 
7260   // Build the case statement.
7261   // Case statements are always rebuilt so that they will attached to their
7262   // transformed switch statement.
7263   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7264                                                        LHS.get(),
7265                                                        S->getEllipsisLoc(),
7266                                                        RHS.get(),
7267                                                        S->getColonLoc());
7268   if (Case.isInvalid())
7269     return StmtError();
7270 
7271   // Transform the statement following the case
7272   StmtResult SubStmt =
7273       getDerived().TransformStmt(S->getSubStmt());
7274   if (SubStmt.isInvalid())
7275     return StmtError();
7276 
7277   // Attach the body to the case statement
7278   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7279 }
7280 
7281 template <typename Derived>
7282 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7283   // Transform the statement following the default case
7284   StmtResult SubStmt =
7285       getDerived().TransformStmt(S->getSubStmt());
7286   if (SubStmt.isInvalid())
7287     return StmtError();
7288 
7289   // Default statements are always rebuilt
7290   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7291                                          SubStmt.get());
7292 }
7293 
7294 template<typename Derived>
7295 StmtResult
7296 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7297   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7298   if (SubStmt.isInvalid())
7299     return StmtError();
7300 
7301   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7302                                         S->getDecl());
7303   if (!LD)
7304     return StmtError();
7305 
7306   // If we're transforming "in-place" (we're not creating new local
7307   // declarations), assume we're replacing the old label statement
7308   // and clear out the reference to it.
7309   if (LD == S->getDecl())
7310     S->getDecl()->setStmt(nullptr);
7311 
7312   // FIXME: Pass the real colon location in.
7313   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7314                                        cast<LabelDecl>(LD), SourceLocation(),
7315                                        SubStmt.get());
7316 }
7317 
7318 template <typename Derived>
7319 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7320   if (!R)
7321     return R;
7322 
7323   switch (R->getKind()) {
7324 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
7325 #define ATTR(X)
7326 #define PRAGMA_SPELLING_ATTR(X)                                                \
7327   case attr::X:                                                                \
7328     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7329 #include "clang/Basic/AttrList.inc"
7330   default:
7331     return R;
7332   }
7333 }
7334 
7335 template <typename Derived>
7336 StmtResult
7337 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7338                                                 StmtDiscardKind SDK) {
7339   bool AttrsChanged = false;
7340   SmallVector<const Attr *, 1> Attrs;
7341 
7342   // Visit attributes and keep track if any are transformed.
7343   for (const auto *I : S->getAttrs()) {
7344     const Attr *R = getDerived().TransformAttr(I);
7345     AttrsChanged |= (I != R);
7346     if (R)
7347       Attrs.push_back(R);
7348   }
7349 
7350   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7351   if (SubStmt.isInvalid())
7352     return StmtError();
7353 
7354   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7355     return S;
7356 
7357   // If transforming the attributes failed for all of the attributes in the
7358   // statement, don't make an AttributedStmt without attributes.
7359   if (Attrs.empty())
7360     return SubStmt;
7361 
7362   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7363                                             SubStmt.get());
7364 }
7365 
7366 template<typename Derived>
7367 StmtResult
7368 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7369   // Transform the initialization statement
7370   StmtResult Init = getDerived().TransformStmt(S->getInit());
7371   if (Init.isInvalid())
7372     return StmtError();
7373 
7374   // Transform the condition
7375   Sema::ConditionResult Cond = getDerived().TransformCondition(
7376       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7377       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7378                        : Sema::ConditionKind::Boolean);
7379   if (Cond.isInvalid())
7380     return StmtError();
7381 
7382   // If this is a constexpr if, determine which arm we should instantiate.
7383   llvm::Optional<bool> ConstexprConditionValue;
7384   if (S->isConstexpr())
7385     ConstexprConditionValue = Cond.getKnownValue();
7386 
7387   // Transform the "then" branch.
7388   StmtResult Then;
7389   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7390     Then = getDerived().TransformStmt(S->getThen());
7391     if (Then.isInvalid())
7392       return StmtError();
7393   } else {
7394     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7395   }
7396 
7397   // Transform the "else" branch.
7398   StmtResult Else;
7399   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7400     Else = getDerived().TransformStmt(S->getElse());
7401     if (Else.isInvalid())
7402       return StmtError();
7403   }
7404 
7405   if (!getDerived().AlwaysRebuild() &&
7406       Init.get() == S->getInit() &&
7407       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7408       Then.get() == S->getThen() &&
7409       Else.get() == S->getElse())
7410     return S;
7411 
7412   return getDerived().RebuildIfStmt(
7413       S->getIfLoc(), S->isConstexpr(), S->getLParenLoc(), Cond,
7414       S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7415 }
7416 
7417 template<typename Derived>
7418 StmtResult
7419 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7420   // Transform the initialization statement
7421   StmtResult Init = getDerived().TransformStmt(S->getInit());
7422   if (Init.isInvalid())
7423     return StmtError();
7424 
7425   // Transform the condition.
7426   Sema::ConditionResult Cond = getDerived().TransformCondition(
7427       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7428       Sema::ConditionKind::Switch);
7429   if (Cond.isInvalid())
7430     return StmtError();
7431 
7432   // Rebuild the switch statement.
7433   StmtResult Switch =
7434       getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7435                                           Init.get(), Cond, S->getRParenLoc());
7436   if (Switch.isInvalid())
7437     return StmtError();
7438 
7439   // Transform the body of the switch statement.
7440   StmtResult Body = getDerived().TransformStmt(S->getBody());
7441   if (Body.isInvalid())
7442     return StmtError();
7443 
7444   // Complete the switch statement.
7445   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7446                                             Body.get());
7447 }
7448 
7449 template<typename Derived>
7450 StmtResult
7451 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7452   // Transform the condition
7453   Sema::ConditionResult Cond = getDerived().TransformCondition(
7454       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7455       Sema::ConditionKind::Boolean);
7456   if (Cond.isInvalid())
7457     return StmtError();
7458 
7459   // Transform the body
7460   StmtResult Body = getDerived().TransformStmt(S->getBody());
7461   if (Body.isInvalid())
7462     return StmtError();
7463 
7464   if (!getDerived().AlwaysRebuild() &&
7465       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7466       Body.get() == S->getBody())
7467     return Owned(S);
7468 
7469   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7470                                        Cond, S->getRParenLoc(), Body.get());
7471 }
7472 
7473 template<typename Derived>
7474 StmtResult
7475 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7476   // Transform the body
7477   StmtResult Body = getDerived().TransformStmt(S->getBody());
7478   if (Body.isInvalid())
7479     return StmtError();
7480 
7481   // Transform the condition
7482   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7483   if (Cond.isInvalid())
7484     return StmtError();
7485 
7486   if (!getDerived().AlwaysRebuild() &&
7487       Cond.get() == S->getCond() &&
7488       Body.get() == S->getBody())
7489     return S;
7490 
7491   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7492                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7493                                     S->getRParenLoc());
7494 }
7495 
7496 template<typename Derived>
7497 StmtResult
7498 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7499   if (getSema().getLangOpts().OpenMP)
7500     getSema().startOpenMPLoop();
7501 
7502   // Transform the initialization statement
7503   StmtResult Init = getDerived().TransformStmt(S->getInit());
7504   if (Init.isInvalid())
7505     return StmtError();
7506 
7507   // In OpenMP loop region loop control variable must be captured and be
7508   // private. Perform analysis of first part (if any).
7509   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7510     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7511 
7512   // Transform the condition
7513   Sema::ConditionResult Cond = getDerived().TransformCondition(
7514       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7515       Sema::ConditionKind::Boolean);
7516   if (Cond.isInvalid())
7517     return StmtError();
7518 
7519   // Transform the increment
7520   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7521   if (Inc.isInvalid())
7522     return StmtError();
7523 
7524   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7525   if (S->getInc() && !FullInc.get())
7526     return StmtError();
7527 
7528   // Transform the body
7529   StmtResult Body = getDerived().TransformStmt(S->getBody());
7530   if (Body.isInvalid())
7531     return StmtError();
7532 
7533   if (!getDerived().AlwaysRebuild() &&
7534       Init.get() == S->getInit() &&
7535       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7536       Inc.get() == S->getInc() &&
7537       Body.get() == S->getBody())
7538     return S;
7539 
7540   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7541                                      Init.get(), Cond, FullInc,
7542                                      S->getRParenLoc(), Body.get());
7543 }
7544 
7545 template<typename Derived>
7546 StmtResult
7547 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7548   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7549                                         S->getLabel());
7550   if (!LD)
7551     return StmtError();
7552 
7553   // Goto statements must always be rebuilt, to resolve the label.
7554   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7555                                       cast<LabelDecl>(LD));
7556 }
7557 
7558 template<typename Derived>
7559 StmtResult
7560 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7561   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7562   if (Target.isInvalid())
7563     return StmtError();
7564   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7565 
7566   if (!getDerived().AlwaysRebuild() &&
7567       Target.get() == S->getTarget())
7568     return S;
7569 
7570   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7571                                               Target.get());
7572 }
7573 
7574 template<typename Derived>
7575 StmtResult
7576 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7577   return S;
7578 }
7579 
7580 template<typename Derived>
7581 StmtResult
7582 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7583   return S;
7584 }
7585 
7586 template<typename Derived>
7587 StmtResult
7588 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7589   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7590                                                         /*NotCopyInit*/false);
7591   if (Result.isInvalid())
7592     return StmtError();
7593 
7594   // FIXME: We always rebuild the return statement because there is no way
7595   // to tell whether the return type of the function has changed.
7596   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7597 }
7598 
7599 template<typename Derived>
7600 StmtResult
7601 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7602   bool DeclChanged = false;
7603   SmallVector<Decl *, 4> Decls;
7604   for (auto *D : S->decls()) {
7605     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7606     if (!Transformed)
7607       return StmtError();
7608 
7609     if (Transformed != D)
7610       DeclChanged = true;
7611 
7612     Decls.push_back(Transformed);
7613   }
7614 
7615   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7616     return S;
7617 
7618   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7619 }
7620 
7621 template<typename Derived>
7622 StmtResult
7623 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7624 
7625   SmallVector<Expr*, 8> Constraints;
7626   SmallVector<Expr*, 8> Exprs;
7627   SmallVector<IdentifierInfo *, 4> Names;
7628 
7629   ExprResult AsmString;
7630   SmallVector<Expr*, 8> Clobbers;
7631 
7632   bool ExprsChanged = false;
7633 
7634   // Go through the outputs.
7635   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7636     Names.push_back(S->getOutputIdentifier(I));
7637 
7638     // No need to transform the constraint literal.
7639     Constraints.push_back(S->getOutputConstraintLiteral(I));
7640 
7641     // Transform the output expr.
7642     Expr *OutputExpr = S->getOutputExpr(I);
7643     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7644     if (Result.isInvalid())
7645       return StmtError();
7646 
7647     ExprsChanged |= Result.get() != OutputExpr;
7648 
7649     Exprs.push_back(Result.get());
7650   }
7651 
7652   // Go through the inputs.
7653   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7654     Names.push_back(S->getInputIdentifier(I));
7655 
7656     // No need to transform the constraint literal.
7657     Constraints.push_back(S->getInputConstraintLiteral(I));
7658 
7659     // Transform the input expr.
7660     Expr *InputExpr = S->getInputExpr(I);
7661     ExprResult Result = getDerived().TransformExpr(InputExpr);
7662     if (Result.isInvalid())
7663       return StmtError();
7664 
7665     ExprsChanged |= Result.get() != InputExpr;
7666 
7667     Exprs.push_back(Result.get());
7668   }
7669 
7670   // Go through the Labels.
7671   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7672     Names.push_back(S->getLabelIdentifier(I));
7673 
7674     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7675     if (Result.isInvalid())
7676       return StmtError();
7677     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7678     Exprs.push_back(Result.get());
7679   }
7680   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7681     return S;
7682 
7683   // Go through the clobbers.
7684   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7685     Clobbers.push_back(S->getClobberStringLiteral(I));
7686 
7687   // No need to transform the asm string literal.
7688   AsmString = S->getAsmString();
7689   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7690                                         S->isVolatile(), S->getNumOutputs(),
7691                                         S->getNumInputs(), Names.data(),
7692                                         Constraints, Exprs, AsmString.get(),
7693                                         Clobbers, S->getNumLabels(),
7694                                         S->getRParenLoc());
7695 }
7696 
7697 template<typename Derived>
7698 StmtResult
7699 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7700   ArrayRef<Token> AsmToks =
7701     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7702 
7703   bool HadError = false, HadChange = false;
7704 
7705   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7706   SmallVector<Expr*, 8> TransformedExprs;
7707   TransformedExprs.reserve(SrcExprs.size());
7708   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7709     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7710     if (!Result.isUsable()) {
7711       HadError = true;
7712     } else {
7713       HadChange |= (Result.get() != SrcExprs[i]);
7714       TransformedExprs.push_back(Result.get());
7715     }
7716   }
7717 
7718   if (HadError) return StmtError();
7719   if (!HadChange && !getDerived().AlwaysRebuild())
7720     return Owned(S);
7721 
7722   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7723                                        AsmToks, S->getAsmString(),
7724                                        S->getNumOutputs(), S->getNumInputs(),
7725                                        S->getAllConstraints(), S->getClobbers(),
7726                                        TransformedExprs, S->getEndLoc());
7727 }
7728 
7729 // C++ Coroutines TS
7730 
7731 template<typename Derived>
7732 StmtResult
7733 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7734   auto *ScopeInfo = SemaRef.getCurFunction();
7735   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7736   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7737          ScopeInfo->NeedsCoroutineSuspends &&
7738          ScopeInfo->CoroutineSuspends.first == nullptr &&
7739          ScopeInfo->CoroutineSuspends.second == nullptr &&
7740          "expected clean scope info");
7741 
7742   // Set that we have (possibly-invalid) suspend points before we do anything
7743   // that may fail.
7744   ScopeInfo->setNeedsCoroutineSuspends(false);
7745 
7746   // We re-build the coroutine promise object (and the coroutine parameters its
7747   // type and constructor depend on) based on the types used in our current
7748   // function. We must do so, and set it on the current FunctionScopeInfo,
7749   // before attempting to transform the other parts of the coroutine body
7750   // statement, such as the implicit suspend statements (because those
7751   // statements reference the FunctionScopeInfo::CoroutinePromise).
7752   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7753     return StmtError();
7754   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7755   if (!Promise)
7756     return StmtError();
7757   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7758   ScopeInfo->CoroutinePromise = Promise;
7759 
7760   // Transform the implicit coroutine statements constructed using dependent
7761   // types during the previous parse: initial and final suspensions, the return
7762   // object, and others. We also transform the coroutine function's body.
7763   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7764   if (InitSuspend.isInvalid())
7765     return StmtError();
7766   StmtResult FinalSuspend =
7767       getDerived().TransformStmt(S->getFinalSuspendStmt());
7768   if (FinalSuspend.isInvalid() ||
7769       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
7770     return StmtError();
7771   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7772   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7773 
7774   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7775   if (BodyRes.isInvalid())
7776     return StmtError();
7777 
7778   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7779   if (Builder.isInvalid())
7780     return StmtError();
7781 
7782   Expr *ReturnObject = S->getReturnValueInit();
7783   assert(ReturnObject && "the return object is expected to be valid");
7784   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7785                                                      /*NoCopyInit*/ false);
7786   if (Res.isInvalid())
7787     return StmtError();
7788   Builder.ReturnValue = Res.get();
7789 
7790   // If during the previous parse the coroutine still had a dependent promise
7791   // statement, we may need to build some implicit coroutine statements
7792   // (such as exception and fallthrough handlers) for the first time.
7793   if (S->hasDependentPromiseType()) {
7794     // We can only build these statements, however, if the current promise type
7795     // is not dependent.
7796     if (!Promise->getType()->isDependentType()) {
7797       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7798              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7799              "these nodes should not have been built yet");
7800       if (!Builder.buildDependentStatements())
7801         return StmtError();
7802     }
7803   } else {
7804     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7805       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7806       if (Res.isInvalid())
7807         return StmtError();
7808       Builder.OnFallthrough = Res.get();
7809     }
7810 
7811     if (auto *OnException = S->getExceptionHandler()) {
7812       StmtResult Res = getDerived().TransformStmt(OnException);
7813       if (Res.isInvalid())
7814         return StmtError();
7815       Builder.OnException = Res.get();
7816     }
7817 
7818     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7819       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7820       if (Res.isInvalid())
7821         return StmtError();
7822       Builder.ReturnStmtOnAllocFailure = Res.get();
7823     }
7824 
7825     // Transform any additional statements we may have already built
7826     assert(S->getAllocate() && S->getDeallocate() &&
7827            "allocation and deallocation calls must already be built");
7828     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7829     if (AllocRes.isInvalid())
7830       return StmtError();
7831     Builder.Allocate = AllocRes.get();
7832 
7833     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7834     if (DeallocRes.isInvalid())
7835       return StmtError();
7836     Builder.Deallocate = DeallocRes.get();
7837 
7838     assert(S->getResultDecl() && "ResultDecl must already be built");
7839     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7840     if (ResultDecl.isInvalid())
7841       return StmtError();
7842     Builder.ResultDecl = ResultDecl.get();
7843 
7844     if (auto *ReturnStmt = S->getReturnStmt()) {
7845       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7846       if (Res.isInvalid())
7847         return StmtError();
7848       Builder.ReturnStmt = Res.get();
7849     }
7850   }
7851 
7852   return getDerived().RebuildCoroutineBodyStmt(Builder);
7853 }
7854 
7855 template<typename Derived>
7856 StmtResult
7857 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7858   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7859                                                         /*NotCopyInit*/false);
7860   if (Result.isInvalid())
7861     return StmtError();
7862 
7863   // Always rebuild; we don't know if this needs to be injected into a new
7864   // context or if the promise type has changed.
7865   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7866                                           S->isImplicit());
7867 }
7868 
7869 template<typename Derived>
7870 ExprResult
7871 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7872   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7873                                                         /*NotCopyInit*/false);
7874   if (Result.isInvalid())
7875     return ExprError();
7876 
7877   // Always rebuild; we don't know if this needs to be injected into a new
7878   // context or if the promise type has changed.
7879   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7880                                          E->isImplicit());
7881 }
7882 
7883 template <typename Derived>
7884 ExprResult
7885 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7886   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7887                                                         /*NotCopyInit*/ false);
7888   if (OperandResult.isInvalid())
7889     return ExprError();
7890 
7891   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7892           E->getOperatorCoawaitLookup());
7893 
7894   if (LookupResult.isInvalid())
7895     return ExprError();
7896 
7897   // Always rebuild; we don't know if this needs to be injected into a new
7898   // context or if the promise type has changed.
7899   return getDerived().RebuildDependentCoawaitExpr(
7900       E->getKeywordLoc(), OperandResult.get(),
7901       cast<UnresolvedLookupExpr>(LookupResult.get()));
7902 }
7903 
7904 template<typename Derived>
7905 ExprResult
7906 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7907   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7908                                                         /*NotCopyInit*/false);
7909   if (Result.isInvalid())
7910     return ExprError();
7911 
7912   // Always rebuild; we don't know if this needs to be injected into a new
7913   // context or if the promise type has changed.
7914   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7915 }
7916 
7917 // Objective-C Statements.
7918 
7919 template<typename Derived>
7920 StmtResult
7921 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7922   // Transform the body of the @try.
7923   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7924   if (TryBody.isInvalid())
7925     return StmtError();
7926 
7927   // Transform the @catch statements (if present).
7928   bool AnyCatchChanged = false;
7929   SmallVector<Stmt*, 8> CatchStmts;
7930   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7931     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7932     if (Catch.isInvalid())
7933       return StmtError();
7934     if (Catch.get() != S->getCatchStmt(I))
7935       AnyCatchChanged = true;
7936     CatchStmts.push_back(Catch.get());
7937   }
7938 
7939   // Transform the @finally statement (if present).
7940   StmtResult Finally;
7941   if (S->getFinallyStmt()) {
7942     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7943     if (Finally.isInvalid())
7944       return StmtError();
7945   }
7946 
7947   // If nothing changed, just retain this statement.
7948   if (!getDerived().AlwaysRebuild() &&
7949       TryBody.get() == S->getTryBody() &&
7950       !AnyCatchChanged &&
7951       Finally.get() == S->getFinallyStmt())
7952     return S;
7953 
7954   // Build a new statement.
7955   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7956                                            CatchStmts, Finally.get());
7957 }
7958 
7959 template<typename Derived>
7960 StmtResult
7961 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7962   // Transform the @catch parameter, if there is one.
7963   VarDecl *Var = nullptr;
7964   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7965     TypeSourceInfo *TSInfo = nullptr;
7966     if (FromVar->getTypeSourceInfo()) {
7967       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7968       if (!TSInfo)
7969         return StmtError();
7970     }
7971 
7972     QualType T;
7973     if (TSInfo)
7974       T = TSInfo->getType();
7975     else {
7976       T = getDerived().TransformType(FromVar->getType());
7977       if (T.isNull())
7978         return StmtError();
7979     }
7980 
7981     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7982     if (!Var)
7983       return StmtError();
7984   }
7985 
7986   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7987   if (Body.isInvalid())
7988     return StmtError();
7989 
7990   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7991                                              S->getRParenLoc(),
7992                                              Var, Body.get());
7993 }
7994 
7995 template<typename Derived>
7996 StmtResult
7997 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7998   // Transform the body.
7999   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8000   if (Body.isInvalid())
8001     return StmtError();
8002 
8003   // If nothing changed, just retain this statement.
8004   if (!getDerived().AlwaysRebuild() &&
8005       Body.get() == S->getFinallyBody())
8006     return S;
8007 
8008   // Build a new statement.
8009   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8010                                                Body.get());
8011 }
8012 
8013 template<typename Derived>
8014 StmtResult
8015 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8016   ExprResult Operand;
8017   if (S->getThrowExpr()) {
8018     Operand = getDerived().TransformExpr(S->getThrowExpr());
8019     if (Operand.isInvalid())
8020       return StmtError();
8021   }
8022 
8023   if (!getDerived().AlwaysRebuild() &&
8024       Operand.get() == S->getThrowExpr())
8025     return S;
8026 
8027   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8028 }
8029 
8030 template<typename Derived>
8031 StmtResult
8032 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8033                                                   ObjCAtSynchronizedStmt *S) {
8034   // Transform the object we are locking.
8035   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8036   if (Object.isInvalid())
8037     return StmtError();
8038   Object =
8039     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8040                                                   Object.get());
8041   if (Object.isInvalid())
8042     return StmtError();
8043 
8044   // Transform the body.
8045   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8046   if (Body.isInvalid())
8047     return StmtError();
8048 
8049   // If nothing change, just retain the current statement.
8050   if (!getDerived().AlwaysRebuild() &&
8051       Object.get() == S->getSynchExpr() &&
8052       Body.get() == S->getSynchBody())
8053     return S;
8054 
8055   // Build a new statement.
8056   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8057                                                     Object.get(), Body.get());
8058 }
8059 
8060 template<typename Derived>
8061 StmtResult
8062 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8063                                               ObjCAutoreleasePoolStmt *S) {
8064   // Transform the body.
8065   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8066   if (Body.isInvalid())
8067     return StmtError();
8068 
8069   // If nothing changed, just retain this statement.
8070   if (!getDerived().AlwaysRebuild() &&
8071       Body.get() == S->getSubStmt())
8072     return S;
8073 
8074   // Build a new statement.
8075   return getDerived().RebuildObjCAutoreleasePoolStmt(
8076                         S->getAtLoc(), Body.get());
8077 }
8078 
8079 template<typename Derived>
8080 StmtResult
8081 TreeTransform<Derived>::TransformObjCForCollectionStmt(
8082                                                   ObjCForCollectionStmt *S) {
8083   // Transform the element statement.
8084   StmtResult Element =
8085       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8086   if (Element.isInvalid())
8087     return StmtError();
8088 
8089   // Transform the collection expression.
8090   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8091   if (Collection.isInvalid())
8092     return StmtError();
8093 
8094   // Transform the body.
8095   StmtResult Body = getDerived().TransformStmt(S->getBody());
8096   if (Body.isInvalid())
8097     return StmtError();
8098 
8099   // If nothing changed, just retain this statement.
8100   if (!getDerived().AlwaysRebuild() &&
8101       Element.get() == S->getElement() &&
8102       Collection.get() == S->getCollection() &&
8103       Body.get() == S->getBody())
8104     return S;
8105 
8106   // Build a new statement.
8107   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8108                                                    Element.get(),
8109                                                    Collection.get(),
8110                                                    S->getRParenLoc(),
8111                                                    Body.get());
8112 }
8113 
8114 template <typename Derived>
8115 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8116   // Transform the exception declaration, if any.
8117   VarDecl *Var = nullptr;
8118   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8119     TypeSourceInfo *T =
8120         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8121     if (!T)
8122       return StmtError();
8123 
8124     Var = getDerived().RebuildExceptionDecl(
8125         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8126         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8127     if (!Var || Var->isInvalidDecl())
8128       return StmtError();
8129   }
8130 
8131   // Transform the actual exception handler.
8132   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8133   if (Handler.isInvalid())
8134     return StmtError();
8135 
8136   if (!getDerived().AlwaysRebuild() && !Var &&
8137       Handler.get() == S->getHandlerBlock())
8138     return S;
8139 
8140   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8141 }
8142 
8143 template <typename Derived>
8144 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8145   // Transform the try block itself.
8146   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8147   if (TryBlock.isInvalid())
8148     return StmtError();
8149 
8150   // Transform the handlers.
8151   bool HandlerChanged = false;
8152   SmallVector<Stmt *, 8> Handlers;
8153   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8154     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8155     if (Handler.isInvalid())
8156       return StmtError();
8157 
8158     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8159     Handlers.push_back(Handler.getAs<Stmt>());
8160   }
8161 
8162   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8163       !HandlerChanged)
8164     return S;
8165 
8166   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8167                                         Handlers);
8168 }
8169 
8170 template<typename Derived>
8171 StmtResult
8172 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8173   StmtResult Init =
8174       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8175   if (Init.isInvalid())
8176     return StmtError();
8177 
8178   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8179   if (Range.isInvalid())
8180     return StmtError();
8181 
8182   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8183   if (Begin.isInvalid())
8184     return StmtError();
8185   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8186   if (End.isInvalid())
8187     return StmtError();
8188 
8189   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8190   if (Cond.isInvalid())
8191     return StmtError();
8192   if (Cond.get())
8193     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8194   if (Cond.isInvalid())
8195     return StmtError();
8196   if (Cond.get())
8197     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8198 
8199   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8200   if (Inc.isInvalid())
8201     return StmtError();
8202   if (Inc.get())
8203     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8204 
8205   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8206   if (LoopVar.isInvalid())
8207     return StmtError();
8208 
8209   StmtResult NewStmt = S;
8210   if (getDerived().AlwaysRebuild() ||
8211       Init.get() != S->getInit() ||
8212       Range.get() != S->getRangeStmt() ||
8213       Begin.get() != S->getBeginStmt() ||
8214       End.get() != S->getEndStmt() ||
8215       Cond.get() != S->getCond() ||
8216       Inc.get() != S->getInc() ||
8217       LoopVar.get() != S->getLoopVarStmt()) {
8218     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8219                                                   S->getCoawaitLoc(), Init.get(),
8220                                                   S->getColonLoc(), Range.get(),
8221                                                   Begin.get(), End.get(),
8222                                                   Cond.get(),
8223                                                   Inc.get(), LoopVar.get(),
8224                                                   S->getRParenLoc());
8225     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8226       // Might not have attached any initializer to the loop variable.
8227       getSema().ActOnInitializerError(
8228           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8229       return StmtError();
8230     }
8231   }
8232 
8233   StmtResult Body = getDerived().TransformStmt(S->getBody());
8234   if (Body.isInvalid())
8235     return StmtError();
8236 
8237   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8238   // it now so we have a new statement to attach the body to.
8239   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8240     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8241                                                   S->getCoawaitLoc(), Init.get(),
8242                                                   S->getColonLoc(), Range.get(),
8243                                                   Begin.get(), End.get(),
8244                                                   Cond.get(),
8245                                                   Inc.get(), LoopVar.get(),
8246                                                   S->getRParenLoc());
8247     if (NewStmt.isInvalid())
8248       return StmtError();
8249   }
8250 
8251   if (NewStmt.get() == S)
8252     return S;
8253 
8254   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8255 }
8256 
8257 template<typename Derived>
8258 StmtResult
8259 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8260                                                     MSDependentExistsStmt *S) {
8261   // Transform the nested-name-specifier, if any.
8262   NestedNameSpecifierLoc QualifierLoc;
8263   if (S->getQualifierLoc()) {
8264     QualifierLoc
8265       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8266     if (!QualifierLoc)
8267       return StmtError();
8268   }
8269 
8270   // Transform the declaration name.
8271   DeclarationNameInfo NameInfo = S->getNameInfo();
8272   if (NameInfo.getName()) {
8273     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8274     if (!NameInfo.getName())
8275       return StmtError();
8276   }
8277 
8278   // Check whether anything changed.
8279   if (!getDerived().AlwaysRebuild() &&
8280       QualifierLoc == S->getQualifierLoc() &&
8281       NameInfo.getName() == S->getNameInfo().getName())
8282     return S;
8283 
8284   // Determine whether this name exists, if we can.
8285   CXXScopeSpec SS;
8286   SS.Adopt(QualifierLoc);
8287   bool Dependent = false;
8288   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8289   case Sema::IER_Exists:
8290     if (S->isIfExists())
8291       break;
8292 
8293     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8294 
8295   case Sema::IER_DoesNotExist:
8296     if (S->isIfNotExists())
8297       break;
8298 
8299     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8300 
8301   case Sema::IER_Dependent:
8302     Dependent = true;
8303     break;
8304 
8305   case Sema::IER_Error:
8306     return StmtError();
8307   }
8308 
8309   // We need to continue with the instantiation, so do so now.
8310   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8311   if (SubStmt.isInvalid())
8312     return StmtError();
8313 
8314   // If we have resolved the name, just transform to the substatement.
8315   if (!Dependent)
8316     return SubStmt;
8317 
8318   // The name is still dependent, so build a dependent expression again.
8319   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8320                                                    S->isIfExists(),
8321                                                    QualifierLoc,
8322                                                    NameInfo,
8323                                                    SubStmt.get());
8324 }
8325 
8326 template<typename Derived>
8327 ExprResult
8328 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8329   NestedNameSpecifierLoc QualifierLoc;
8330   if (E->getQualifierLoc()) {
8331     QualifierLoc
8332     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8333     if (!QualifierLoc)
8334       return ExprError();
8335   }
8336 
8337   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8338     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8339   if (!PD)
8340     return ExprError();
8341 
8342   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8343   if (Base.isInvalid())
8344     return ExprError();
8345 
8346   return new (SemaRef.getASTContext())
8347       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8348                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8349                         QualifierLoc, E->getMemberLoc());
8350 }
8351 
8352 template <typename Derived>
8353 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8354     MSPropertySubscriptExpr *E) {
8355   auto BaseRes = getDerived().TransformExpr(E->getBase());
8356   if (BaseRes.isInvalid())
8357     return ExprError();
8358   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8359   if (IdxRes.isInvalid())
8360     return ExprError();
8361 
8362   if (!getDerived().AlwaysRebuild() &&
8363       BaseRes.get() == E->getBase() &&
8364       IdxRes.get() == E->getIdx())
8365     return E;
8366 
8367   return getDerived().RebuildArraySubscriptExpr(
8368       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8369 }
8370 
8371 template <typename Derived>
8372 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8373   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8374   if (TryBlock.isInvalid())
8375     return StmtError();
8376 
8377   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8378   if (Handler.isInvalid())
8379     return StmtError();
8380 
8381   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8382       Handler.get() == S->getHandler())
8383     return S;
8384 
8385   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8386                                         TryBlock.get(), Handler.get());
8387 }
8388 
8389 template <typename Derived>
8390 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8391   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8392   if (Block.isInvalid())
8393     return StmtError();
8394 
8395   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8396 }
8397 
8398 template <typename Derived>
8399 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8400   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8401   if (FilterExpr.isInvalid())
8402     return StmtError();
8403 
8404   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8405   if (Block.isInvalid())
8406     return StmtError();
8407 
8408   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8409                                            Block.get());
8410 }
8411 
8412 template <typename Derived>
8413 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8414   if (isa<SEHFinallyStmt>(Handler))
8415     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8416   else
8417     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8418 }
8419 
8420 template<typename Derived>
8421 StmtResult
8422 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8423   return S;
8424 }
8425 
8426 //===----------------------------------------------------------------------===//
8427 // OpenMP directive transformation
8428 //===----------------------------------------------------------------------===//
8429 
8430 template <typename Derived>
8431 StmtResult
8432 TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8433   // OMPCanonicalLoops are eliminated during transformation, since they will be
8434   // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8435   // after transformation.
8436   return getDerived().TransformStmt(L->getLoopStmt());
8437 }
8438 
8439 template <typename Derived>
8440 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8441     OMPExecutableDirective *D) {
8442 
8443   // Transform the clauses
8444   llvm::SmallVector<OMPClause *, 16> TClauses;
8445   ArrayRef<OMPClause *> Clauses = D->clauses();
8446   TClauses.reserve(Clauses.size());
8447   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8448        I != E; ++I) {
8449     if (*I) {
8450       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8451       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8452       getDerived().getSema().EndOpenMPClause();
8453       if (Clause)
8454         TClauses.push_back(Clause);
8455     } else {
8456       TClauses.push_back(nullptr);
8457     }
8458   }
8459   StmtResult AssociatedStmt;
8460   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8461     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8462                                                   /*CurScope=*/nullptr);
8463     StmtResult Body;
8464     {
8465       Sema::CompoundScopeRAII CompoundScope(getSema());
8466       Stmt *CS;
8467       if (D->getDirectiveKind() == OMPD_atomic ||
8468           D->getDirectiveKind() == OMPD_critical ||
8469           D->getDirectiveKind() == OMPD_section ||
8470           D->getDirectiveKind() == OMPD_master)
8471         CS = D->getAssociatedStmt();
8472       else
8473         CS = D->getRawStmt();
8474       Body = getDerived().TransformStmt(CS);
8475       if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8476           getSema().getLangOpts().OpenMPIRBuilder)
8477         Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8478     }
8479     AssociatedStmt =
8480         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8481     if (AssociatedStmt.isInvalid()) {
8482       return StmtError();
8483     }
8484   }
8485   if (TClauses.size() != Clauses.size()) {
8486     return StmtError();
8487   }
8488 
8489   // Transform directive name for 'omp critical' directive.
8490   DeclarationNameInfo DirName;
8491   if (D->getDirectiveKind() == OMPD_critical) {
8492     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8493     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8494   }
8495   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8496   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8497     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8498   } else if (D->getDirectiveKind() == OMPD_cancel) {
8499     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8500   }
8501 
8502   return getDerived().RebuildOMPExecutableDirective(
8503       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8504       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8505 }
8506 
8507 template <typename Derived>
8508 StmtResult
8509 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8510   DeclarationNameInfo DirName;
8511   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8512                                              D->getBeginLoc());
8513   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8514   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8515   return Res;
8516 }
8517 
8518 template <typename Derived>
8519 StmtResult
8520 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8521   DeclarationNameInfo DirName;
8522   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8523                                              D->getBeginLoc());
8524   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8525   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8526   return Res;
8527 }
8528 
8529 template <typename Derived>
8530 StmtResult
8531 TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8532   DeclarationNameInfo DirName;
8533   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8534                                              nullptr, D->getBeginLoc());
8535   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8536   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8537   return Res;
8538 }
8539 
8540 template <typename Derived>
8541 StmtResult
8542 TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8543   DeclarationNameInfo DirName;
8544   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8545                                              nullptr, D->getBeginLoc());
8546   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8547   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8548   return Res;
8549 }
8550 
8551 template <typename Derived>
8552 StmtResult
8553 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8554   DeclarationNameInfo DirName;
8555   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8556                                              D->getBeginLoc());
8557   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8558   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8559   return Res;
8560 }
8561 
8562 template <typename Derived>
8563 StmtResult
8564 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8565   DeclarationNameInfo DirName;
8566   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8567                                              D->getBeginLoc());
8568   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8569   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8570   return Res;
8571 }
8572 
8573 template <typename Derived>
8574 StmtResult
8575 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8576   DeclarationNameInfo DirName;
8577   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8578                                              D->getBeginLoc());
8579   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8580   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8581   return Res;
8582 }
8583 
8584 template <typename Derived>
8585 StmtResult
8586 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8587   DeclarationNameInfo DirName;
8588   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8589                                              D->getBeginLoc());
8590   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8591   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8592   return Res;
8593 }
8594 
8595 template <typename Derived>
8596 StmtResult
8597 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8598   DeclarationNameInfo DirName;
8599   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8600                                              D->getBeginLoc());
8601   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8602   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8603   return Res;
8604 }
8605 
8606 template <typename Derived>
8607 StmtResult
8608 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8609   DeclarationNameInfo DirName;
8610   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8611                                              D->getBeginLoc());
8612   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8613   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8614   return Res;
8615 }
8616 
8617 template <typename Derived>
8618 StmtResult
8619 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8620   getDerived().getSema().StartOpenMPDSABlock(
8621       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8622   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8623   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8624   return Res;
8625 }
8626 
8627 template <typename Derived>
8628 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8629     OMPParallelForDirective *D) {
8630   DeclarationNameInfo DirName;
8631   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8632                                              nullptr, D->getBeginLoc());
8633   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8634   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8635   return Res;
8636 }
8637 
8638 template <typename Derived>
8639 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8640     OMPParallelForSimdDirective *D) {
8641   DeclarationNameInfo DirName;
8642   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8643                                              nullptr, D->getBeginLoc());
8644   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8645   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8646   return Res;
8647 }
8648 
8649 template <typename Derived>
8650 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8651     OMPParallelMasterDirective *D) {
8652   DeclarationNameInfo DirName;
8653   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8654                                              nullptr, D->getBeginLoc());
8655   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8656   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8657   return Res;
8658 }
8659 
8660 template <typename Derived>
8661 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8662     OMPParallelSectionsDirective *D) {
8663   DeclarationNameInfo DirName;
8664   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8665                                              nullptr, D->getBeginLoc());
8666   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8667   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8668   return Res;
8669 }
8670 
8671 template <typename Derived>
8672 StmtResult
8673 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8674   DeclarationNameInfo DirName;
8675   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8676                                              D->getBeginLoc());
8677   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8678   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8679   return Res;
8680 }
8681 
8682 template <typename Derived>
8683 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8684     OMPTaskyieldDirective *D) {
8685   DeclarationNameInfo DirName;
8686   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8687                                              D->getBeginLoc());
8688   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8689   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8690   return Res;
8691 }
8692 
8693 template <typename Derived>
8694 StmtResult
8695 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8696   DeclarationNameInfo DirName;
8697   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8698                                              D->getBeginLoc());
8699   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8700   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8701   return Res;
8702 }
8703 
8704 template <typename Derived>
8705 StmtResult
8706 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8707   DeclarationNameInfo DirName;
8708   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8709                                              D->getBeginLoc());
8710   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8711   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8712   return Res;
8713 }
8714 
8715 template <typename Derived>
8716 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8717     OMPTaskgroupDirective *D) {
8718   DeclarationNameInfo DirName;
8719   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8720                                              D->getBeginLoc());
8721   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8722   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8723   return Res;
8724 }
8725 
8726 template <typename Derived>
8727 StmtResult
8728 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8729   DeclarationNameInfo DirName;
8730   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8731                                              D->getBeginLoc());
8732   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8733   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8734   return Res;
8735 }
8736 
8737 template <typename Derived>
8738 StmtResult
8739 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
8740   DeclarationNameInfo DirName;
8741   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
8742                                              D->getBeginLoc());
8743   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8744   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8745   return Res;
8746 }
8747 
8748 template <typename Derived>
8749 StmtResult
8750 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
8751   DeclarationNameInfo DirName;
8752   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
8753                                              D->getBeginLoc());
8754   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8755   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8756   return Res;
8757 }
8758 
8759 template <typename Derived>
8760 StmtResult
8761 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8762   DeclarationNameInfo DirName;
8763   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8764                                              D->getBeginLoc());
8765   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8766   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8767   return Res;
8768 }
8769 
8770 template <typename Derived>
8771 StmtResult
8772 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8773   DeclarationNameInfo DirName;
8774   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8775                                              D->getBeginLoc());
8776   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8777   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8778   return Res;
8779 }
8780 
8781 template <typename Derived>
8782 StmtResult
8783 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8784   DeclarationNameInfo DirName;
8785   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8786                                              D->getBeginLoc());
8787   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8788   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8789   return Res;
8790 }
8791 
8792 template <typename Derived>
8793 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8794     OMPTargetDataDirective *D) {
8795   DeclarationNameInfo DirName;
8796   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8797                                              D->getBeginLoc());
8798   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8799   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8800   return Res;
8801 }
8802 
8803 template <typename Derived>
8804 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8805     OMPTargetEnterDataDirective *D) {
8806   DeclarationNameInfo DirName;
8807   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8808                                              nullptr, D->getBeginLoc());
8809   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8810   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8811   return Res;
8812 }
8813 
8814 template <typename Derived>
8815 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8816     OMPTargetExitDataDirective *D) {
8817   DeclarationNameInfo DirName;
8818   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8819                                              nullptr, D->getBeginLoc());
8820   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8821   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8822   return Res;
8823 }
8824 
8825 template <typename Derived>
8826 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8827     OMPTargetParallelDirective *D) {
8828   DeclarationNameInfo DirName;
8829   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8830                                              nullptr, D->getBeginLoc());
8831   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8832   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8833   return Res;
8834 }
8835 
8836 template <typename Derived>
8837 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8838     OMPTargetParallelForDirective *D) {
8839   DeclarationNameInfo DirName;
8840   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8841                                              nullptr, D->getBeginLoc());
8842   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8843   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8844   return Res;
8845 }
8846 
8847 template <typename Derived>
8848 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8849     OMPTargetUpdateDirective *D) {
8850   DeclarationNameInfo DirName;
8851   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8852                                              nullptr, D->getBeginLoc());
8853   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8854   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8855   return Res;
8856 }
8857 
8858 template <typename Derived>
8859 StmtResult
8860 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8861   DeclarationNameInfo DirName;
8862   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8863                                              D->getBeginLoc());
8864   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8865   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8866   return Res;
8867 }
8868 
8869 template <typename Derived>
8870 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8871     OMPCancellationPointDirective *D) {
8872   DeclarationNameInfo DirName;
8873   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8874                                              nullptr, D->getBeginLoc());
8875   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8876   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8877   return Res;
8878 }
8879 
8880 template <typename Derived>
8881 StmtResult
8882 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8883   DeclarationNameInfo DirName;
8884   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8885                                              D->getBeginLoc());
8886   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8887   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8888   return Res;
8889 }
8890 
8891 template <typename Derived>
8892 StmtResult
8893 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8894   DeclarationNameInfo DirName;
8895   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8896                                              D->getBeginLoc());
8897   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8898   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8899   return Res;
8900 }
8901 
8902 template <typename Derived>
8903 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8904     OMPTaskLoopSimdDirective *D) {
8905   DeclarationNameInfo DirName;
8906   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8907                                              nullptr, D->getBeginLoc());
8908   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8909   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8910   return Res;
8911 }
8912 
8913 template <typename Derived>
8914 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8915     OMPMasterTaskLoopDirective *D) {
8916   DeclarationNameInfo DirName;
8917   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8918                                              nullptr, D->getBeginLoc());
8919   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8920   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8921   return Res;
8922 }
8923 
8924 template <typename Derived>
8925 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
8926     OMPMasterTaskLoopSimdDirective *D) {
8927   DeclarationNameInfo DirName;
8928   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8929                                              nullptr, D->getBeginLoc());
8930   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8931   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8932   return Res;
8933 }
8934 
8935 template <typename Derived>
8936 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8937     OMPParallelMasterTaskLoopDirective *D) {
8938   DeclarationNameInfo DirName;
8939   getDerived().getSema().StartOpenMPDSABlock(
8940       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
8941   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8942   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8943   return Res;
8944 }
8945 
8946 template <typename Derived>
8947 StmtResult
8948 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
8949     OMPParallelMasterTaskLoopSimdDirective *D) {
8950   DeclarationNameInfo DirName;
8951   getDerived().getSema().StartOpenMPDSABlock(
8952       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
8953   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8954   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8955   return Res;
8956 }
8957 
8958 template <typename Derived>
8959 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8960     OMPDistributeDirective *D) {
8961   DeclarationNameInfo DirName;
8962   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8963                                              D->getBeginLoc());
8964   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8965   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8966   return Res;
8967 }
8968 
8969 template <typename Derived>
8970 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8971     OMPDistributeParallelForDirective *D) {
8972   DeclarationNameInfo DirName;
8973   getDerived().getSema().StartOpenMPDSABlock(
8974       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8975   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8976   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8977   return Res;
8978 }
8979 
8980 template <typename Derived>
8981 StmtResult
8982 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8983     OMPDistributeParallelForSimdDirective *D) {
8984   DeclarationNameInfo DirName;
8985   getDerived().getSema().StartOpenMPDSABlock(
8986       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8987   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8988   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8989   return Res;
8990 }
8991 
8992 template <typename Derived>
8993 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8994     OMPDistributeSimdDirective *D) {
8995   DeclarationNameInfo DirName;
8996   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8997                                              nullptr, D->getBeginLoc());
8998   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8999   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9000   return Res;
9001 }
9002 
9003 template <typename Derived>
9004 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9005     OMPTargetParallelForSimdDirective *D) {
9006   DeclarationNameInfo DirName;
9007   getDerived().getSema().StartOpenMPDSABlock(
9008       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9009   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9010   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9011   return Res;
9012 }
9013 
9014 template <typename Derived>
9015 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9016     OMPTargetSimdDirective *D) {
9017   DeclarationNameInfo DirName;
9018   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9019                                              D->getBeginLoc());
9020   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9021   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9022   return Res;
9023 }
9024 
9025 template <typename Derived>
9026 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9027     OMPTeamsDistributeDirective *D) {
9028   DeclarationNameInfo DirName;
9029   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9030                                              nullptr, D->getBeginLoc());
9031   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9032   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9033   return Res;
9034 }
9035 
9036 template <typename Derived>
9037 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9038     OMPTeamsDistributeSimdDirective *D) {
9039   DeclarationNameInfo DirName;
9040   getDerived().getSema().StartOpenMPDSABlock(
9041       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9042   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9043   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9044   return Res;
9045 }
9046 
9047 template <typename Derived>
9048 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9049     OMPTeamsDistributeParallelForSimdDirective *D) {
9050   DeclarationNameInfo DirName;
9051   getDerived().getSema().StartOpenMPDSABlock(
9052       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9053       D->getBeginLoc());
9054   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9055   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9056   return Res;
9057 }
9058 
9059 template <typename Derived>
9060 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9061     OMPTeamsDistributeParallelForDirective *D) {
9062   DeclarationNameInfo DirName;
9063   getDerived().getSema().StartOpenMPDSABlock(
9064       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9065   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9066   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9067   return Res;
9068 }
9069 
9070 template <typename Derived>
9071 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9072     OMPTargetTeamsDirective *D) {
9073   DeclarationNameInfo DirName;
9074   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9075                                              nullptr, D->getBeginLoc());
9076   auto Res = getDerived().TransformOMPExecutableDirective(D);
9077   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9078   return Res;
9079 }
9080 
9081 template <typename Derived>
9082 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9083     OMPTargetTeamsDistributeDirective *D) {
9084   DeclarationNameInfo DirName;
9085   getDerived().getSema().StartOpenMPDSABlock(
9086       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9087   auto Res = getDerived().TransformOMPExecutableDirective(D);
9088   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9089   return Res;
9090 }
9091 
9092 template <typename Derived>
9093 StmtResult
9094 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9095     OMPTargetTeamsDistributeParallelForDirective *D) {
9096   DeclarationNameInfo DirName;
9097   getDerived().getSema().StartOpenMPDSABlock(
9098       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9099       D->getBeginLoc());
9100   auto Res = getDerived().TransformOMPExecutableDirective(D);
9101   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9102   return Res;
9103 }
9104 
9105 template <typename Derived>
9106 StmtResult TreeTransform<Derived>::
9107     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9108         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9109   DeclarationNameInfo DirName;
9110   getDerived().getSema().StartOpenMPDSABlock(
9111       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9112       D->getBeginLoc());
9113   auto Res = getDerived().TransformOMPExecutableDirective(D);
9114   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9115   return Res;
9116 }
9117 
9118 template <typename Derived>
9119 StmtResult
9120 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9121     OMPTargetTeamsDistributeSimdDirective *D) {
9122   DeclarationNameInfo DirName;
9123   getDerived().getSema().StartOpenMPDSABlock(
9124       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9125   auto Res = getDerived().TransformOMPExecutableDirective(D);
9126   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9127   return Res;
9128 }
9129 
9130 template <typename Derived>
9131 StmtResult
9132 TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9133   DeclarationNameInfo DirName;
9134   getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9135                                              D->getBeginLoc());
9136   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9137   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9138   return Res;
9139 }
9140 
9141 template <typename Derived>
9142 StmtResult
9143 TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9144   DeclarationNameInfo DirName;
9145   getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9146                                              D->getBeginLoc());
9147   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9148   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9149   return Res;
9150 }
9151 
9152 template <typename Derived>
9153 StmtResult
9154 TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9155   DeclarationNameInfo DirName;
9156   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9157                                              D->getBeginLoc());
9158   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9159   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9160   return Res;
9161 }
9162 
9163 //===----------------------------------------------------------------------===//
9164 // OpenMP clause transformation
9165 //===----------------------------------------------------------------------===//
9166 template <typename Derived>
9167 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9168   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9169   if (Cond.isInvalid())
9170     return nullptr;
9171   return getDerived().RebuildOMPIfClause(
9172       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9173       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9174 }
9175 
9176 template <typename Derived>
9177 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9178   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9179   if (Cond.isInvalid())
9180     return nullptr;
9181   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9182                                             C->getLParenLoc(), C->getEndLoc());
9183 }
9184 
9185 template <typename Derived>
9186 OMPClause *
9187 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9188   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9189   if (NumThreads.isInvalid())
9190     return nullptr;
9191   return getDerived().RebuildOMPNumThreadsClause(
9192       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9193 }
9194 
9195 template <typename Derived>
9196 OMPClause *
9197 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9198   ExprResult E = getDerived().TransformExpr(C->getSafelen());
9199   if (E.isInvalid())
9200     return nullptr;
9201   return getDerived().RebuildOMPSafelenClause(
9202       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9203 }
9204 
9205 template <typename Derived>
9206 OMPClause *
9207 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9208   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9209   if (E.isInvalid())
9210     return nullptr;
9211   return getDerived().RebuildOMPAllocatorClause(
9212       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9213 }
9214 
9215 template <typename Derived>
9216 OMPClause *
9217 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9218   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9219   if (E.isInvalid())
9220     return nullptr;
9221   return getDerived().RebuildOMPSimdlenClause(
9222       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9223 }
9224 
9225 template <typename Derived>
9226 OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9227   SmallVector<Expr *, 4> TransformedSizes;
9228   TransformedSizes.reserve(C->getNumSizes());
9229   bool Changed = false;
9230   for (Expr *E : C->getSizesRefs()) {
9231     if (!E) {
9232       TransformedSizes.push_back(nullptr);
9233       continue;
9234     }
9235 
9236     ExprResult T = getDerived().TransformExpr(E);
9237     if (T.isInvalid())
9238       return nullptr;
9239     if (E != T.get())
9240       Changed = true;
9241     TransformedSizes.push_back(T.get());
9242   }
9243 
9244   if (!Changed && !getDerived().AlwaysRebuild())
9245     return C;
9246   return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9247                                C->getLParenLoc(), C->getEndLoc());
9248 }
9249 
9250 template <typename Derived>
9251 OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9252   if (!getDerived().AlwaysRebuild())
9253     return C;
9254   return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9255 }
9256 
9257 template <typename Derived>
9258 OMPClause *
9259 TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9260   ExprResult T = getDerived().TransformExpr(C->getFactor());
9261   if (T.isInvalid())
9262     return nullptr;
9263   Expr *Factor = T.get();
9264   bool Changed = Factor != C->getFactor();
9265 
9266   if (!Changed && !getDerived().AlwaysRebuild())
9267     return C;
9268   return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9269                                  C->getEndLoc());
9270 }
9271 
9272 template <typename Derived>
9273 OMPClause *
9274 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9275   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9276   if (E.isInvalid())
9277     return nullptr;
9278   return getDerived().RebuildOMPCollapseClause(
9279       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9280 }
9281 
9282 template <typename Derived>
9283 OMPClause *
9284 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9285   return getDerived().RebuildOMPDefaultClause(
9286       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9287       C->getLParenLoc(), C->getEndLoc());
9288 }
9289 
9290 template <typename Derived>
9291 OMPClause *
9292 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9293   return getDerived().RebuildOMPProcBindClause(
9294       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9295       C->getLParenLoc(), C->getEndLoc());
9296 }
9297 
9298 template <typename Derived>
9299 OMPClause *
9300 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9301   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9302   if (E.isInvalid())
9303     return nullptr;
9304   return getDerived().RebuildOMPScheduleClause(
9305       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9306       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9307       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9308       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9309 }
9310 
9311 template <typename Derived>
9312 OMPClause *
9313 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9314   ExprResult E;
9315   if (auto *Num = C->getNumForLoops()) {
9316     E = getDerived().TransformExpr(Num);
9317     if (E.isInvalid())
9318       return nullptr;
9319   }
9320   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9321                                               C->getLParenLoc(), E.get());
9322 }
9323 
9324 template <typename Derived>
9325 OMPClause *
9326 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9327   ExprResult E;
9328   if (Expr *Evt = C->getEventHandler()) {
9329     E = getDerived().TransformExpr(Evt);
9330     if (E.isInvalid())
9331       return nullptr;
9332   }
9333   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9334                                              C->getLParenLoc(), C->getEndLoc());
9335 }
9336 
9337 template <typename Derived>
9338 OMPClause *
9339 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9340   // No need to rebuild this clause, no template-dependent parameters.
9341   return C;
9342 }
9343 
9344 template <typename Derived>
9345 OMPClause *
9346 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9347   // No need to rebuild this clause, no template-dependent parameters.
9348   return C;
9349 }
9350 
9351 template <typename Derived>
9352 OMPClause *
9353 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9354   // No need to rebuild this clause, no template-dependent parameters.
9355   return C;
9356 }
9357 
9358 template <typename Derived>
9359 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9360   // No need to rebuild this clause, no template-dependent parameters.
9361   return C;
9362 }
9363 
9364 template <typename Derived>
9365 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9366   // No need to rebuild this clause, no template-dependent parameters.
9367   return C;
9368 }
9369 
9370 template <typename Derived>
9371 OMPClause *
9372 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9373   // No need to rebuild this clause, no template-dependent parameters.
9374   return C;
9375 }
9376 
9377 template <typename Derived>
9378 OMPClause *
9379 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9380   // No need to rebuild this clause, no template-dependent parameters.
9381   return C;
9382 }
9383 
9384 template <typename Derived>
9385 OMPClause *
9386 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9387   // No need to rebuild this clause, no template-dependent parameters.
9388   return C;
9389 }
9390 
9391 template <typename Derived>
9392 OMPClause *
9393 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9394   // No need to rebuild this clause, no template-dependent parameters.
9395   return C;
9396 }
9397 
9398 template <typename Derived>
9399 OMPClause *
9400 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9401   // No need to rebuild this clause, no template-dependent parameters.
9402   return C;
9403 }
9404 
9405 template <typename Derived>
9406 OMPClause *
9407 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9408   // No need to rebuild this clause, no template-dependent parameters.
9409   return C;
9410 }
9411 
9412 template <typename Derived>
9413 OMPClause *
9414 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9415   // No need to rebuild this clause, no template-dependent parameters.
9416   return C;
9417 }
9418 
9419 template <typename Derived>
9420 OMPClause *
9421 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9422   // No need to rebuild this clause, no template-dependent parameters.
9423   return C;
9424 }
9425 
9426 template <typename Derived>
9427 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9428   // No need to rebuild this clause, no template-dependent parameters.
9429   return C;
9430 }
9431 
9432 template <typename Derived>
9433 OMPClause *
9434 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9435   // No need to rebuild this clause, no template-dependent parameters.
9436   return C;
9437 }
9438 
9439 template <typename Derived>
9440 OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9441   ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9442   if (IVR.isInvalid())
9443     return nullptr;
9444 
9445   llvm::SmallVector<Expr *, 8> PrefExprs;
9446   PrefExprs.reserve(C->varlist_size() - 1);
9447   for (Expr *E : llvm::drop_begin(C->varlists())) {
9448     ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9449     if (ER.isInvalid())
9450       return nullptr;
9451     PrefExprs.push_back(ER.get());
9452   }
9453   return getDerived().RebuildOMPInitClause(
9454       IVR.get(), PrefExprs, C->getIsTarget(), C->getIsTargetSync(),
9455       C->getBeginLoc(), C->getLParenLoc(), C->getVarLoc(), C->getEndLoc());
9456 }
9457 
9458 template <typename Derived>
9459 OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9460   ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9461   if (ER.isInvalid())
9462     return nullptr;
9463   return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9464                                           C->getLParenLoc(), C->getVarLoc(),
9465                                           C->getEndLoc());
9466 }
9467 
9468 template <typename Derived>
9469 OMPClause *
9470 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9471   ExprResult ER;
9472   if (Expr *IV = C->getInteropVar()) {
9473     ER = getDerived().TransformExpr(IV);
9474     if (ER.isInvalid())
9475       return nullptr;
9476   }
9477   return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9478                                               C->getLParenLoc(), C->getVarLoc(),
9479                                               C->getEndLoc());
9480 }
9481 
9482 template <typename Derived>
9483 OMPClause *
9484 TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9485   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9486   if (Cond.isInvalid())
9487     return nullptr;
9488   return getDerived().RebuildOMPNovariantsClause(
9489       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9490 }
9491 
9492 template <typename Derived>
9493 OMPClause *
9494 TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9495   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9496   if (Cond.isInvalid())
9497     return nullptr;
9498   return getDerived().RebuildOMPNocontextClause(
9499       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9500 }
9501 
9502 template <typename Derived>
9503 OMPClause *
9504 TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9505   ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9506   if (ThreadID.isInvalid())
9507     return nullptr;
9508   return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9509                                              C->getLParenLoc(), C->getEndLoc());
9510 }
9511 
9512 template <typename Derived>
9513 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9514     OMPUnifiedAddressClause *C) {
9515   llvm_unreachable("unified_address clause cannot appear in dependent context");
9516 }
9517 
9518 template <typename Derived>
9519 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9520     OMPUnifiedSharedMemoryClause *C) {
9521   llvm_unreachable(
9522       "unified_shared_memory clause cannot appear in dependent context");
9523 }
9524 
9525 template <typename Derived>
9526 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9527     OMPReverseOffloadClause *C) {
9528   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
9529 }
9530 
9531 template <typename Derived>
9532 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9533     OMPDynamicAllocatorsClause *C) {
9534   llvm_unreachable(
9535       "dynamic_allocators clause cannot appear in dependent context");
9536 }
9537 
9538 template <typename Derived>
9539 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9540     OMPAtomicDefaultMemOrderClause *C) {
9541   llvm_unreachable(
9542       "atomic_default_mem_order clause cannot appear in dependent context");
9543 }
9544 
9545 template <typename Derived>
9546 OMPClause *
9547 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9548   llvm::SmallVector<Expr *, 16> Vars;
9549   Vars.reserve(C->varlist_size());
9550   for (auto *VE : C->varlists()) {
9551     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9552     if (EVar.isInvalid())
9553       return nullptr;
9554     Vars.push_back(EVar.get());
9555   }
9556   return getDerived().RebuildOMPPrivateClause(
9557       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9558 }
9559 
9560 template <typename Derived>
9561 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
9562     OMPFirstprivateClause *C) {
9563   llvm::SmallVector<Expr *, 16> Vars;
9564   Vars.reserve(C->varlist_size());
9565   for (auto *VE : C->varlists()) {
9566     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9567     if (EVar.isInvalid())
9568       return nullptr;
9569     Vars.push_back(EVar.get());
9570   }
9571   return getDerived().RebuildOMPFirstprivateClause(
9572       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9573 }
9574 
9575 template <typename Derived>
9576 OMPClause *
9577 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
9578   llvm::SmallVector<Expr *, 16> Vars;
9579   Vars.reserve(C->varlist_size());
9580   for (auto *VE : C->varlists()) {
9581     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9582     if (EVar.isInvalid())
9583       return nullptr;
9584     Vars.push_back(EVar.get());
9585   }
9586   return getDerived().RebuildOMPLastprivateClause(
9587       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
9588       C->getLParenLoc(), C->getEndLoc());
9589 }
9590 
9591 template <typename Derived>
9592 OMPClause *
9593 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
9594   llvm::SmallVector<Expr *, 16> Vars;
9595   Vars.reserve(C->varlist_size());
9596   for (auto *VE : C->varlists()) {
9597     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9598     if (EVar.isInvalid())
9599       return nullptr;
9600     Vars.push_back(EVar.get());
9601   }
9602   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
9603                                              C->getLParenLoc(), C->getEndLoc());
9604 }
9605 
9606 template <typename Derived>
9607 OMPClause *
9608 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
9609   llvm::SmallVector<Expr *, 16> Vars;
9610   Vars.reserve(C->varlist_size());
9611   for (auto *VE : C->varlists()) {
9612     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9613     if (EVar.isInvalid())
9614       return nullptr;
9615     Vars.push_back(EVar.get());
9616   }
9617   CXXScopeSpec ReductionIdScopeSpec;
9618   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9619 
9620   DeclarationNameInfo NameInfo = C->getNameInfo();
9621   if (NameInfo.getName()) {
9622     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9623     if (!NameInfo.getName())
9624       return nullptr;
9625   }
9626   // Build a list of all UDR decls with the same names ranged by the Scopes.
9627   // The Scope boundary is a duplication of the previous decl.
9628   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9629   for (auto *E : C->reduction_ops()) {
9630     // Transform all the decls.
9631     if (E) {
9632       auto *ULE = cast<UnresolvedLookupExpr>(E);
9633       UnresolvedSet<8> Decls;
9634       for (auto *D : ULE->decls()) {
9635         NamedDecl *InstD =
9636             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9637         Decls.addDecl(InstD, InstD->getAccess());
9638       }
9639       UnresolvedReductions.push_back(
9640        UnresolvedLookupExpr::Create(
9641           SemaRef.Context, /*NamingClass=*/nullptr,
9642           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
9643           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
9644           Decls.begin(), Decls.end()));
9645     } else
9646       UnresolvedReductions.push_back(nullptr);
9647   }
9648   return getDerived().RebuildOMPReductionClause(
9649       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
9650       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
9651       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9652 }
9653 
9654 template <typename Derived>
9655 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
9656     OMPTaskReductionClause *C) {
9657   llvm::SmallVector<Expr *, 16> Vars;
9658   Vars.reserve(C->varlist_size());
9659   for (auto *VE : C->varlists()) {
9660     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9661     if (EVar.isInvalid())
9662       return nullptr;
9663     Vars.push_back(EVar.get());
9664   }
9665   CXXScopeSpec ReductionIdScopeSpec;
9666   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9667 
9668   DeclarationNameInfo NameInfo = C->getNameInfo();
9669   if (NameInfo.getName()) {
9670     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9671     if (!NameInfo.getName())
9672       return nullptr;
9673   }
9674   // Build a list of all UDR decls with the same names ranged by the Scopes.
9675   // The Scope boundary is a duplication of the previous decl.
9676   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9677   for (auto *E : C->reduction_ops()) {
9678     // Transform all the decls.
9679     if (E) {
9680       auto *ULE = cast<UnresolvedLookupExpr>(E);
9681       UnresolvedSet<8> Decls;
9682       for (auto *D : ULE->decls()) {
9683         NamedDecl *InstD =
9684             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9685         Decls.addDecl(InstD, InstD->getAccess());
9686       }
9687       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9688           SemaRef.Context, /*NamingClass=*/nullptr,
9689           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9690           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9691     } else
9692       UnresolvedReductions.push_back(nullptr);
9693   }
9694   return getDerived().RebuildOMPTaskReductionClause(
9695       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9696       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9697 }
9698 
9699 template <typename Derived>
9700 OMPClause *
9701 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
9702   llvm::SmallVector<Expr *, 16> Vars;
9703   Vars.reserve(C->varlist_size());
9704   for (auto *VE : C->varlists()) {
9705     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9706     if (EVar.isInvalid())
9707       return nullptr;
9708     Vars.push_back(EVar.get());
9709   }
9710   CXXScopeSpec ReductionIdScopeSpec;
9711   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9712 
9713   DeclarationNameInfo NameInfo = C->getNameInfo();
9714   if (NameInfo.getName()) {
9715     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9716     if (!NameInfo.getName())
9717       return nullptr;
9718   }
9719   // Build a list of all UDR decls with the same names ranged by the Scopes.
9720   // The Scope boundary is a duplication of the previous decl.
9721   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9722   for (auto *E : C->reduction_ops()) {
9723     // Transform all the decls.
9724     if (E) {
9725       auto *ULE = cast<UnresolvedLookupExpr>(E);
9726       UnresolvedSet<8> Decls;
9727       for (auto *D : ULE->decls()) {
9728         NamedDecl *InstD =
9729             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9730         Decls.addDecl(InstD, InstD->getAccess());
9731       }
9732       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9733           SemaRef.Context, /*NamingClass=*/nullptr,
9734           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9735           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9736     } else
9737       UnresolvedReductions.push_back(nullptr);
9738   }
9739   return getDerived().RebuildOMPInReductionClause(
9740       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9741       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9742 }
9743 
9744 template <typename Derived>
9745 OMPClause *
9746 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
9747   llvm::SmallVector<Expr *, 16> Vars;
9748   Vars.reserve(C->varlist_size());
9749   for (auto *VE : C->varlists()) {
9750     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9751     if (EVar.isInvalid())
9752       return nullptr;
9753     Vars.push_back(EVar.get());
9754   }
9755   ExprResult Step = getDerived().TransformExpr(C->getStep());
9756   if (Step.isInvalid())
9757     return nullptr;
9758   return getDerived().RebuildOMPLinearClause(
9759       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
9760       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
9761 }
9762 
9763 template <typename Derived>
9764 OMPClause *
9765 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
9766   llvm::SmallVector<Expr *, 16> Vars;
9767   Vars.reserve(C->varlist_size());
9768   for (auto *VE : C->varlists()) {
9769     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9770     if (EVar.isInvalid())
9771       return nullptr;
9772     Vars.push_back(EVar.get());
9773   }
9774   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
9775   if (Alignment.isInvalid())
9776     return nullptr;
9777   return getDerived().RebuildOMPAlignedClause(
9778       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
9779       C->getColonLoc(), C->getEndLoc());
9780 }
9781 
9782 template <typename Derived>
9783 OMPClause *
9784 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
9785   llvm::SmallVector<Expr *, 16> Vars;
9786   Vars.reserve(C->varlist_size());
9787   for (auto *VE : C->varlists()) {
9788     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9789     if (EVar.isInvalid())
9790       return nullptr;
9791     Vars.push_back(EVar.get());
9792   }
9793   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
9794                                              C->getLParenLoc(), C->getEndLoc());
9795 }
9796 
9797 template <typename Derived>
9798 OMPClause *
9799 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
9800   llvm::SmallVector<Expr *, 16> Vars;
9801   Vars.reserve(C->varlist_size());
9802   for (auto *VE : C->varlists()) {
9803     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9804     if (EVar.isInvalid())
9805       return nullptr;
9806     Vars.push_back(EVar.get());
9807   }
9808   return getDerived().RebuildOMPCopyprivateClause(
9809       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9810 }
9811 
9812 template <typename Derived>
9813 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
9814   llvm::SmallVector<Expr *, 16> Vars;
9815   Vars.reserve(C->varlist_size());
9816   for (auto *VE : C->varlists()) {
9817     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9818     if (EVar.isInvalid())
9819       return nullptr;
9820     Vars.push_back(EVar.get());
9821   }
9822   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9823                                             C->getLParenLoc(), C->getEndLoc());
9824 }
9825 
9826 template <typename Derived>
9827 OMPClause *
9828 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
9829   ExprResult E = getDerived().TransformExpr(C->getDepobj());
9830   if (E.isInvalid())
9831     return nullptr;
9832   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
9833                                              C->getLParenLoc(), C->getEndLoc());
9834 }
9835 
9836 template <typename Derived>
9837 OMPClause *
9838 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9839   llvm::SmallVector<Expr *, 16> Vars;
9840   Expr *DepModifier = C->getModifier();
9841   if (DepModifier) {
9842     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
9843     if (DepModRes.isInvalid())
9844       return nullptr;
9845     DepModifier = DepModRes.get();
9846   }
9847   Vars.reserve(C->varlist_size());
9848   for (auto *VE : C->varlists()) {
9849     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9850     if (EVar.isInvalid())
9851       return nullptr;
9852     Vars.push_back(EVar.get());
9853   }
9854   return getDerived().RebuildOMPDependClause(
9855       DepModifier, C->getDependencyKind(), C->getDependencyLoc(),
9856       C->getColonLoc(), Vars, C->getBeginLoc(), C->getLParenLoc(),
9857       C->getEndLoc());
9858 }
9859 
9860 template <typename Derived>
9861 OMPClause *
9862 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9863   ExprResult E = getDerived().TransformExpr(C->getDevice());
9864   if (E.isInvalid())
9865     return nullptr;
9866   return getDerived().RebuildOMPDeviceClause(
9867       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9868       C->getModifierLoc(), C->getEndLoc());
9869 }
9870 
9871 template <typename Derived, class T>
9872 bool transformOMPMappableExprListClause(
9873     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9874     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9875     DeclarationNameInfo &MapperIdInfo,
9876     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9877   // Transform expressions in the list.
9878   Vars.reserve(C->varlist_size());
9879   for (auto *VE : C->varlists()) {
9880     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9881     if (EVar.isInvalid())
9882       return true;
9883     Vars.push_back(EVar.get());
9884   }
9885   // Transform mapper scope specifier and identifier.
9886   NestedNameSpecifierLoc QualifierLoc;
9887   if (C->getMapperQualifierLoc()) {
9888     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9889         C->getMapperQualifierLoc());
9890     if (!QualifierLoc)
9891       return true;
9892   }
9893   MapperIdScopeSpec.Adopt(QualifierLoc);
9894   MapperIdInfo = C->getMapperIdInfo();
9895   if (MapperIdInfo.getName()) {
9896     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9897     if (!MapperIdInfo.getName())
9898       return true;
9899   }
9900   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9901   // the previous user-defined mapper lookup in dependent environment.
9902   for (auto *E : C->mapperlists()) {
9903     // Transform all the decls.
9904     if (E) {
9905       auto *ULE = cast<UnresolvedLookupExpr>(E);
9906       UnresolvedSet<8> Decls;
9907       for (auto *D : ULE->decls()) {
9908         NamedDecl *InstD =
9909             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9910         Decls.addDecl(InstD, InstD->getAccess());
9911       }
9912       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9913           TT.getSema().Context, /*NamingClass=*/nullptr,
9914           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9915           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9916           Decls.end()));
9917     } else {
9918       UnresolvedMappers.push_back(nullptr);
9919     }
9920   }
9921   return false;
9922 }
9923 
9924 template <typename Derived>
9925 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9926   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9927   llvm::SmallVector<Expr *, 16> Vars;
9928   CXXScopeSpec MapperIdScopeSpec;
9929   DeclarationNameInfo MapperIdInfo;
9930   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9931   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9932           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9933     return nullptr;
9934   return getDerived().RebuildOMPMapClause(
9935       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9936       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9937       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9938 }
9939 
9940 template <typename Derived>
9941 OMPClause *
9942 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9943   Expr *Allocator = C->getAllocator();
9944   if (Allocator) {
9945     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9946     if (AllocatorRes.isInvalid())
9947       return nullptr;
9948     Allocator = AllocatorRes.get();
9949   }
9950   llvm::SmallVector<Expr *, 16> Vars;
9951   Vars.reserve(C->varlist_size());
9952   for (auto *VE : C->varlists()) {
9953     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9954     if (EVar.isInvalid())
9955       return nullptr;
9956     Vars.push_back(EVar.get());
9957   }
9958   return getDerived().RebuildOMPAllocateClause(
9959       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9960       C->getEndLoc());
9961 }
9962 
9963 template <typename Derived>
9964 OMPClause *
9965 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9966   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9967   if (E.isInvalid())
9968     return nullptr;
9969   return getDerived().RebuildOMPNumTeamsClause(
9970       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9971 }
9972 
9973 template <typename Derived>
9974 OMPClause *
9975 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9976   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9977   if (E.isInvalid())
9978     return nullptr;
9979   return getDerived().RebuildOMPThreadLimitClause(
9980       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9981 }
9982 
9983 template <typename Derived>
9984 OMPClause *
9985 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9986   ExprResult E = getDerived().TransformExpr(C->getPriority());
9987   if (E.isInvalid())
9988     return nullptr;
9989   return getDerived().RebuildOMPPriorityClause(
9990       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9991 }
9992 
9993 template <typename Derived>
9994 OMPClause *
9995 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9996   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9997   if (E.isInvalid())
9998     return nullptr;
9999   return getDerived().RebuildOMPGrainsizeClause(
10000       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10001 }
10002 
10003 template <typename Derived>
10004 OMPClause *
10005 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10006   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10007   if (E.isInvalid())
10008     return nullptr;
10009   return getDerived().RebuildOMPNumTasksClause(
10010       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10011 }
10012 
10013 template <typename Derived>
10014 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10015   ExprResult E = getDerived().TransformExpr(C->getHint());
10016   if (E.isInvalid())
10017     return nullptr;
10018   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10019                                            C->getLParenLoc(), C->getEndLoc());
10020 }
10021 
10022 template <typename Derived>
10023 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10024     OMPDistScheduleClause *C) {
10025   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10026   if (E.isInvalid())
10027     return nullptr;
10028   return getDerived().RebuildOMPDistScheduleClause(
10029       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10030       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10031 }
10032 
10033 template <typename Derived>
10034 OMPClause *
10035 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10036   // Rebuild Defaultmap Clause since we need to invoke the checking of
10037   // defaultmap(none:variable-category) after template initialization.
10038   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10039                                                  C->getDefaultmapKind(),
10040                                                  C->getBeginLoc(),
10041                                                  C->getLParenLoc(),
10042                                                  C->getDefaultmapModifierLoc(),
10043                                                  C->getDefaultmapKindLoc(),
10044                                                  C->getEndLoc());
10045 }
10046 
10047 template <typename Derived>
10048 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10049   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10050   llvm::SmallVector<Expr *, 16> Vars;
10051   CXXScopeSpec MapperIdScopeSpec;
10052   DeclarationNameInfo MapperIdInfo;
10053   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10054   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10055           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10056     return nullptr;
10057   return getDerived().RebuildOMPToClause(
10058       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10059       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10060 }
10061 
10062 template <typename Derived>
10063 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10064   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10065   llvm::SmallVector<Expr *, 16> Vars;
10066   CXXScopeSpec MapperIdScopeSpec;
10067   DeclarationNameInfo MapperIdInfo;
10068   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10069   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10070           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10071     return nullptr;
10072   return getDerived().RebuildOMPFromClause(
10073       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10074       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10075 }
10076 
10077 template <typename Derived>
10078 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10079     OMPUseDevicePtrClause *C) {
10080   llvm::SmallVector<Expr *, 16> Vars;
10081   Vars.reserve(C->varlist_size());
10082   for (auto *VE : C->varlists()) {
10083     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10084     if (EVar.isInvalid())
10085       return nullptr;
10086     Vars.push_back(EVar.get());
10087   }
10088   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10089   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10090 }
10091 
10092 template <typename Derived>
10093 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10094     OMPUseDeviceAddrClause *C) {
10095   llvm::SmallVector<Expr *, 16> Vars;
10096   Vars.reserve(C->varlist_size());
10097   for (auto *VE : C->varlists()) {
10098     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10099     if (EVar.isInvalid())
10100       return nullptr;
10101     Vars.push_back(EVar.get());
10102   }
10103   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10104   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10105 }
10106 
10107 template <typename Derived>
10108 OMPClause *
10109 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10110   llvm::SmallVector<Expr *, 16> Vars;
10111   Vars.reserve(C->varlist_size());
10112   for (auto *VE : C->varlists()) {
10113     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10114     if (EVar.isInvalid())
10115       return nullptr;
10116     Vars.push_back(EVar.get());
10117   }
10118   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10119   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10120 }
10121 
10122 template <typename Derived>
10123 OMPClause *
10124 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10125   llvm::SmallVector<Expr *, 16> Vars;
10126   Vars.reserve(C->varlist_size());
10127   for (auto *VE : C->varlists()) {
10128     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10129     if (EVar.isInvalid())
10130       return nullptr;
10131     Vars.push_back(EVar.get());
10132   }
10133   return getDerived().RebuildOMPNontemporalClause(
10134       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10135 }
10136 
10137 template <typename Derived>
10138 OMPClause *
10139 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10140   llvm::SmallVector<Expr *, 16> Vars;
10141   Vars.reserve(C->varlist_size());
10142   for (auto *VE : C->varlists()) {
10143     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10144     if (EVar.isInvalid())
10145       return nullptr;
10146     Vars.push_back(EVar.get());
10147   }
10148   return getDerived().RebuildOMPInclusiveClause(
10149       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10150 }
10151 
10152 template <typename Derived>
10153 OMPClause *
10154 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10155   llvm::SmallVector<Expr *, 16> Vars;
10156   Vars.reserve(C->varlist_size());
10157   for (auto *VE : C->varlists()) {
10158     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10159     if (EVar.isInvalid())
10160       return nullptr;
10161     Vars.push_back(EVar.get());
10162   }
10163   return getDerived().RebuildOMPExclusiveClause(
10164       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10165 }
10166 
10167 template <typename Derived>
10168 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10169     OMPUsesAllocatorsClause *C) {
10170   SmallVector<Sema::UsesAllocatorsData, 16> Data;
10171   Data.reserve(C->getNumberOfAllocators());
10172   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10173     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10174     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10175     if (Allocator.isInvalid())
10176       continue;
10177     ExprResult AllocatorTraits;
10178     if (Expr *AT = D.AllocatorTraits) {
10179       AllocatorTraits = getDerived().TransformExpr(AT);
10180       if (AllocatorTraits.isInvalid())
10181         continue;
10182     }
10183     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10184     NewD.Allocator = Allocator.get();
10185     NewD.AllocatorTraits = AllocatorTraits.get();
10186     NewD.LParenLoc = D.LParenLoc;
10187     NewD.RParenLoc = D.RParenLoc;
10188   }
10189   return getDerived().RebuildOMPUsesAllocatorsClause(
10190       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10191 }
10192 
10193 template <typename Derived>
10194 OMPClause *
10195 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10196   SmallVector<Expr *, 4> Locators;
10197   Locators.reserve(C->varlist_size());
10198   ExprResult ModifierRes;
10199   if (Expr *Modifier = C->getModifier()) {
10200     ModifierRes = getDerived().TransformExpr(Modifier);
10201     if (ModifierRes.isInvalid())
10202       return nullptr;
10203   }
10204   for (Expr *E : C->varlists()) {
10205     ExprResult Locator = getDerived().TransformExpr(E);
10206     if (Locator.isInvalid())
10207       continue;
10208     Locators.push_back(Locator.get());
10209   }
10210   return getDerived().RebuildOMPAffinityClause(
10211       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10212       ModifierRes.get(), Locators);
10213 }
10214 
10215 template <typename Derived>
10216 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10217   return getDerived().RebuildOMPOrderClause(C->getKind(), C->getKindKwLoc(),
10218                                             C->getBeginLoc(), C->getLParenLoc(),
10219                                             C->getEndLoc());
10220 }
10221 
10222 //===----------------------------------------------------------------------===//
10223 // Expression transformation
10224 //===----------------------------------------------------------------------===//
10225 template<typename Derived>
10226 ExprResult
10227 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10228   return TransformExpr(E->getSubExpr());
10229 }
10230 
10231 template <typename Derived>
10232 ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10233     SYCLUniqueStableNameExpr *E) {
10234   if (!E->isTypeDependent())
10235     return E;
10236 
10237   TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10238 
10239   if (!NewT)
10240     return ExprError();
10241 
10242   if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10243     return E;
10244 
10245   return getDerived().RebuildSYCLUniqueStableNameExpr(
10246       E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10247 }
10248 
10249 template<typename Derived>
10250 ExprResult
10251 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10252   if (!E->isTypeDependent())
10253     return E;
10254 
10255   return getDerived().RebuildPredefinedExpr(E->getLocation(),
10256                                             E->getIdentKind());
10257 }
10258 
10259 template<typename Derived>
10260 ExprResult
10261 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10262   NestedNameSpecifierLoc QualifierLoc;
10263   if (E->getQualifierLoc()) {
10264     QualifierLoc
10265       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10266     if (!QualifierLoc)
10267       return ExprError();
10268   }
10269 
10270   ValueDecl *ND
10271     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10272                                                          E->getDecl()));
10273   if (!ND)
10274     return ExprError();
10275 
10276   NamedDecl *Found = ND;
10277   if (E->getFoundDecl() != E->getDecl()) {
10278     Found = cast_or_null<NamedDecl>(
10279         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10280     if (!Found)
10281       return ExprError();
10282   }
10283 
10284   DeclarationNameInfo NameInfo = E->getNameInfo();
10285   if (NameInfo.getName()) {
10286     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10287     if (!NameInfo.getName())
10288       return ExprError();
10289   }
10290 
10291   if (!getDerived().AlwaysRebuild() &&
10292       QualifierLoc == E->getQualifierLoc() &&
10293       ND == E->getDecl() &&
10294       Found == E->getFoundDecl() &&
10295       NameInfo.getName() == E->getDecl()->getDeclName() &&
10296       !E->hasExplicitTemplateArgs()) {
10297 
10298     // Mark it referenced in the new context regardless.
10299     // FIXME: this is a bit instantiation-specific.
10300     SemaRef.MarkDeclRefReferenced(E);
10301 
10302     return E;
10303   }
10304 
10305   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10306   if (E->hasExplicitTemplateArgs()) {
10307     TemplateArgs = &TransArgs;
10308     TransArgs.setLAngleLoc(E->getLAngleLoc());
10309     TransArgs.setRAngleLoc(E->getRAngleLoc());
10310     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10311                                                 E->getNumTemplateArgs(),
10312                                                 TransArgs))
10313       return ExprError();
10314   }
10315 
10316   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10317                                          Found, TemplateArgs);
10318 }
10319 
10320 template<typename Derived>
10321 ExprResult
10322 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10323   return E;
10324 }
10325 
10326 template <typename Derived>
10327 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10328     FixedPointLiteral *E) {
10329   return E;
10330 }
10331 
10332 template<typename Derived>
10333 ExprResult
10334 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10335   return E;
10336 }
10337 
10338 template<typename Derived>
10339 ExprResult
10340 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10341   return E;
10342 }
10343 
10344 template<typename Derived>
10345 ExprResult
10346 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10347   return E;
10348 }
10349 
10350 template<typename Derived>
10351 ExprResult
10352 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10353   return E;
10354 }
10355 
10356 template<typename Derived>
10357 ExprResult
10358 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10359   if (FunctionDecl *FD = E->getDirectCallee())
10360     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
10361   return SemaRef.MaybeBindToTemporary(E);
10362 }
10363 
10364 template<typename Derived>
10365 ExprResult
10366 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10367   ExprResult ControllingExpr =
10368     getDerived().TransformExpr(E->getControllingExpr());
10369   if (ControllingExpr.isInvalid())
10370     return ExprError();
10371 
10372   SmallVector<Expr *, 4> AssocExprs;
10373   SmallVector<TypeSourceInfo *, 4> AssocTypes;
10374   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10375     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10376     if (TSI) {
10377       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10378       if (!AssocType)
10379         return ExprError();
10380       AssocTypes.push_back(AssocType);
10381     } else {
10382       AssocTypes.push_back(nullptr);
10383     }
10384 
10385     ExprResult AssocExpr =
10386         getDerived().TransformExpr(Assoc.getAssociationExpr());
10387     if (AssocExpr.isInvalid())
10388       return ExprError();
10389     AssocExprs.push_back(AssocExpr.get());
10390   }
10391 
10392   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10393                                                   E->getDefaultLoc(),
10394                                                   E->getRParenLoc(),
10395                                                   ControllingExpr.get(),
10396                                                   AssocTypes,
10397                                                   AssocExprs);
10398 }
10399 
10400 template<typename Derived>
10401 ExprResult
10402 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10403   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10404   if (SubExpr.isInvalid())
10405     return ExprError();
10406 
10407   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10408     return E;
10409 
10410   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10411                                        E->getRParen());
10412 }
10413 
10414 /// The operand of a unary address-of operator has special rules: it's
10415 /// allowed to refer to a non-static member of a class even if there's no 'this'
10416 /// object available.
10417 template<typename Derived>
10418 ExprResult
10419 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10420   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10421     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10422   else
10423     return getDerived().TransformExpr(E);
10424 }
10425 
10426 template<typename Derived>
10427 ExprResult
10428 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10429   ExprResult SubExpr;
10430   if (E->getOpcode() == UO_AddrOf)
10431     SubExpr = TransformAddressOfOperand(E->getSubExpr());
10432   else
10433     SubExpr = TransformExpr(E->getSubExpr());
10434   if (SubExpr.isInvalid())
10435     return ExprError();
10436 
10437   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10438     return E;
10439 
10440   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10441                                            E->getOpcode(),
10442                                            SubExpr.get());
10443 }
10444 
10445 template<typename Derived>
10446 ExprResult
10447 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10448   // Transform the type.
10449   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10450   if (!Type)
10451     return ExprError();
10452 
10453   // Transform all of the components into components similar to what the
10454   // parser uses.
10455   // FIXME: It would be slightly more efficient in the non-dependent case to
10456   // just map FieldDecls, rather than requiring the rebuilder to look for
10457   // the fields again. However, __builtin_offsetof is rare enough in
10458   // template code that we don't care.
10459   bool ExprChanged = false;
10460   typedef Sema::OffsetOfComponent Component;
10461   SmallVector<Component, 4> Components;
10462   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10463     const OffsetOfNode &ON = E->getComponent(I);
10464     Component Comp;
10465     Comp.isBrackets = true;
10466     Comp.LocStart = ON.getSourceRange().getBegin();
10467     Comp.LocEnd = ON.getSourceRange().getEnd();
10468     switch (ON.getKind()) {
10469     case OffsetOfNode::Array: {
10470       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10471       ExprResult Index = getDerived().TransformExpr(FromIndex);
10472       if (Index.isInvalid())
10473         return ExprError();
10474 
10475       ExprChanged = ExprChanged || Index.get() != FromIndex;
10476       Comp.isBrackets = true;
10477       Comp.U.E = Index.get();
10478       break;
10479     }
10480 
10481     case OffsetOfNode::Field:
10482     case OffsetOfNode::Identifier:
10483       Comp.isBrackets = false;
10484       Comp.U.IdentInfo = ON.getFieldName();
10485       if (!Comp.U.IdentInfo)
10486         continue;
10487 
10488       break;
10489 
10490     case OffsetOfNode::Base:
10491       // Will be recomputed during the rebuild.
10492       continue;
10493     }
10494 
10495     Components.push_back(Comp);
10496   }
10497 
10498   // If nothing changed, retain the existing expression.
10499   if (!getDerived().AlwaysRebuild() &&
10500       Type == E->getTypeSourceInfo() &&
10501       !ExprChanged)
10502     return E;
10503 
10504   // Build a new offsetof expression.
10505   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10506                                           Components, E->getRParenLoc());
10507 }
10508 
10509 template<typename Derived>
10510 ExprResult
10511 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
10512   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
10513          "opaque value expression requires transformation");
10514   return E;
10515 }
10516 
10517 template<typename Derived>
10518 ExprResult
10519 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
10520   return E;
10521 }
10522 
10523 template <typename Derived>
10524 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
10525   llvm::SmallVector<Expr *, 8> Children;
10526   bool Changed = false;
10527   for (Expr *C : E->subExpressions()) {
10528     ExprResult NewC = getDerived().TransformExpr(C);
10529     if (NewC.isInvalid())
10530       return ExprError();
10531     Children.push_back(NewC.get());
10532 
10533     Changed |= NewC.get() != C;
10534   }
10535   if (!getDerived().AlwaysRebuild() && !Changed)
10536     return E;
10537   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
10538                                           Children, E->getType());
10539 }
10540 
10541 template<typename Derived>
10542 ExprResult
10543 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
10544   // Rebuild the syntactic form.  The original syntactic form has
10545   // opaque-value expressions in it, so strip those away and rebuild
10546   // the result.  This is a really awful way of doing this, but the
10547   // better solution (rebuilding the semantic expressions and
10548   // rebinding OVEs as necessary) doesn't work; we'd need
10549   // TreeTransform to not strip away implicit conversions.
10550   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
10551   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
10552   if (result.isInvalid()) return ExprError();
10553 
10554   // If that gives us a pseudo-object result back, the pseudo-object
10555   // expression must have been an lvalue-to-rvalue conversion which we
10556   // should reapply.
10557   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
10558     result = SemaRef.checkPseudoObjectRValue(result.get());
10559 
10560   return result;
10561 }
10562 
10563 template<typename Derived>
10564 ExprResult
10565 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
10566                                                 UnaryExprOrTypeTraitExpr *E) {
10567   if (E->isArgumentType()) {
10568     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
10569 
10570     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10571     if (!NewT)
10572       return ExprError();
10573 
10574     if (!getDerived().AlwaysRebuild() && OldT == NewT)
10575       return E;
10576 
10577     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
10578                                                     E->getKind(),
10579                                                     E->getSourceRange());
10580   }
10581 
10582   // C++0x [expr.sizeof]p1:
10583   //   The operand is either an expression, which is an unevaluated operand
10584   //   [...]
10585   EnterExpressionEvaluationContext Unevaluated(
10586       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10587       Sema::ReuseLambdaContextDecl);
10588 
10589   // Try to recover if we have something like sizeof(T::X) where X is a type.
10590   // Notably, there must be *exactly* one set of parens if X is a type.
10591   TypeSourceInfo *RecoveryTSI = nullptr;
10592   ExprResult SubExpr;
10593   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
10594   if (auto *DRE =
10595           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
10596     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
10597         PE, DRE, false, &RecoveryTSI);
10598   else
10599     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
10600 
10601   if (RecoveryTSI) {
10602     return getDerived().RebuildUnaryExprOrTypeTrait(
10603         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
10604   } else if (SubExpr.isInvalid())
10605     return ExprError();
10606 
10607   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
10608     return E;
10609 
10610   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
10611                                                   E->getOperatorLoc(),
10612                                                   E->getKind(),
10613                                                   E->getSourceRange());
10614 }
10615 
10616 template<typename Derived>
10617 ExprResult
10618 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
10619   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10620   if (LHS.isInvalid())
10621     return ExprError();
10622 
10623   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10624   if (RHS.isInvalid())
10625     return ExprError();
10626 
10627 
10628   if (!getDerived().AlwaysRebuild() &&
10629       LHS.get() == E->getLHS() &&
10630       RHS.get() == E->getRHS())
10631     return E;
10632 
10633   return getDerived().RebuildArraySubscriptExpr(
10634       LHS.get(),
10635       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
10636 }
10637 
10638 template <typename Derived>
10639 ExprResult
10640 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
10641   ExprResult Base = getDerived().TransformExpr(E->getBase());
10642   if (Base.isInvalid())
10643     return ExprError();
10644 
10645   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
10646   if (RowIdx.isInvalid())
10647     return ExprError();
10648 
10649   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
10650   if (ColumnIdx.isInvalid())
10651     return ExprError();
10652 
10653   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10654       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
10655     return E;
10656 
10657   return getDerived().RebuildMatrixSubscriptExpr(
10658       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
10659 }
10660 
10661 template <typename Derived>
10662 ExprResult
10663 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
10664   ExprResult Base = getDerived().TransformExpr(E->getBase());
10665   if (Base.isInvalid())
10666     return ExprError();
10667 
10668   ExprResult LowerBound;
10669   if (E->getLowerBound()) {
10670     LowerBound = getDerived().TransformExpr(E->getLowerBound());
10671     if (LowerBound.isInvalid())
10672       return ExprError();
10673   }
10674 
10675   ExprResult Length;
10676   if (E->getLength()) {
10677     Length = getDerived().TransformExpr(E->getLength());
10678     if (Length.isInvalid())
10679       return ExprError();
10680   }
10681 
10682   ExprResult Stride;
10683   if (Expr *Str = E->getStride()) {
10684     Stride = getDerived().TransformExpr(Str);
10685     if (Stride.isInvalid())
10686       return ExprError();
10687   }
10688 
10689   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10690       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
10691     return E;
10692 
10693   return getDerived().RebuildOMPArraySectionExpr(
10694       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
10695       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
10696       E->getRBracketLoc());
10697 }
10698 
10699 template <typename Derived>
10700 ExprResult
10701 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
10702   ExprResult Base = getDerived().TransformExpr(E->getBase());
10703   if (Base.isInvalid())
10704     return ExprError();
10705 
10706   SmallVector<Expr *, 4> Dims;
10707   bool ErrorFound = false;
10708   for (Expr *Dim : E->getDimensions()) {
10709     ExprResult DimRes = getDerived().TransformExpr(Dim);
10710     if (DimRes.isInvalid()) {
10711       ErrorFound = true;
10712       continue;
10713     }
10714     Dims.push_back(DimRes.get());
10715   }
10716 
10717   if (ErrorFound)
10718     return ExprError();
10719   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
10720                                                  E->getRParenLoc(), Dims,
10721                                                  E->getBracketsRanges());
10722 }
10723 
10724 template <typename Derived>
10725 ExprResult
10726 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
10727   unsigned NumIterators = E->numOfIterators();
10728   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
10729 
10730   bool ErrorFound = false;
10731   bool NeedToRebuild = getDerived().AlwaysRebuild();
10732   for (unsigned I = 0; I < NumIterators; ++I) {
10733     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
10734     Data[I].DeclIdent = D->getIdentifier();
10735     Data[I].DeclIdentLoc = D->getLocation();
10736     if (D->getLocation() == D->getBeginLoc()) {
10737       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
10738              "Implicit type must be int.");
10739     } else {
10740       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
10741       QualType DeclTy = getDerived().TransformType(D->getType());
10742       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
10743     }
10744     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
10745     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
10746     ExprResult End = getDerived().TransformExpr(Range.End);
10747     ExprResult Step = getDerived().TransformExpr(Range.Step);
10748     ErrorFound = ErrorFound ||
10749                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
10750                                                !Data[I].Type.get().isNull())) ||
10751                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
10752     if (ErrorFound)
10753       continue;
10754     Data[I].Range.Begin = Begin.get();
10755     Data[I].Range.End = End.get();
10756     Data[I].Range.Step = Step.get();
10757     Data[I].AssignLoc = E->getAssignLoc(I);
10758     Data[I].ColonLoc = E->getColonLoc(I);
10759     Data[I].SecColonLoc = E->getSecondColonLoc(I);
10760     NeedToRebuild =
10761         NeedToRebuild ||
10762         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
10763                                        D->getType().getTypePtrOrNull()) ||
10764         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
10765         Range.Step != Data[I].Range.Step;
10766   }
10767   if (ErrorFound)
10768     return ExprError();
10769   if (!NeedToRebuild)
10770     return E;
10771 
10772   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
10773       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
10774   if (!Res.isUsable())
10775     return Res;
10776   auto *IE = cast<OMPIteratorExpr>(Res.get());
10777   for (unsigned I = 0; I < NumIterators; ++I)
10778     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
10779                                       IE->getIteratorDecl(I));
10780   return Res;
10781 }
10782 
10783 template<typename Derived>
10784 ExprResult
10785 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
10786   // Transform the callee.
10787   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10788   if (Callee.isInvalid())
10789     return ExprError();
10790 
10791   // Transform arguments.
10792   bool ArgChanged = false;
10793   SmallVector<Expr*, 8> Args;
10794   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10795                                   &ArgChanged))
10796     return ExprError();
10797 
10798   if (!getDerived().AlwaysRebuild() &&
10799       Callee.get() == E->getCallee() &&
10800       !ArgChanged)
10801     return SemaRef.MaybeBindToTemporary(E);
10802 
10803   // FIXME: Wrong source location information for the '('.
10804   SourceLocation FakeLParenLoc
10805     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10806 
10807   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10808   if (E->hasStoredFPFeatures()) {
10809     FPOptionsOverride NewOverrides = E->getFPFeatures();
10810     getSema().CurFPFeatures =
10811         NewOverrides.applyOverrides(getSema().getLangOpts());
10812     getSema().FpPragmaStack.CurrentValue = NewOverrides;
10813   }
10814 
10815   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10816                                       Args,
10817                                       E->getRParenLoc());
10818 }
10819 
10820 template<typename Derived>
10821 ExprResult
10822 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
10823   ExprResult Base = getDerived().TransformExpr(E->getBase());
10824   if (Base.isInvalid())
10825     return ExprError();
10826 
10827   NestedNameSpecifierLoc QualifierLoc;
10828   if (E->hasQualifier()) {
10829     QualifierLoc
10830       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10831 
10832     if (!QualifierLoc)
10833       return ExprError();
10834   }
10835   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10836 
10837   ValueDecl *Member
10838     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
10839                                                          E->getMemberDecl()));
10840   if (!Member)
10841     return ExprError();
10842 
10843   NamedDecl *FoundDecl = E->getFoundDecl();
10844   if (FoundDecl == E->getMemberDecl()) {
10845     FoundDecl = Member;
10846   } else {
10847     FoundDecl = cast_or_null<NamedDecl>(
10848                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
10849     if (!FoundDecl)
10850       return ExprError();
10851   }
10852 
10853   if (!getDerived().AlwaysRebuild() &&
10854       Base.get() == E->getBase() &&
10855       QualifierLoc == E->getQualifierLoc() &&
10856       Member == E->getMemberDecl() &&
10857       FoundDecl == E->getFoundDecl() &&
10858       !E->hasExplicitTemplateArgs()) {
10859 
10860     // Mark it referenced in the new context regardless.
10861     // FIXME: this is a bit instantiation-specific.
10862     SemaRef.MarkMemberReferenced(E);
10863 
10864     return E;
10865   }
10866 
10867   TemplateArgumentListInfo TransArgs;
10868   if (E->hasExplicitTemplateArgs()) {
10869     TransArgs.setLAngleLoc(E->getLAngleLoc());
10870     TransArgs.setRAngleLoc(E->getRAngleLoc());
10871     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10872                                                 E->getNumTemplateArgs(),
10873                                                 TransArgs))
10874       return ExprError();
10875   }
10876 
10877   // FIXME: Bogus source location for the operator
10878   SourceLocation FakeOperatorLoc =
10879       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
10880 
10881   // FIXME: to do this check properly, we will need to preserve the
10882   // first-qualifier-in-scope here, just in case we had a dependent
10883   // base (and therefore couldn't do the check) and a
10884   // nested-name-qualifier (and therefore could do the lookup).
10885   NamedDecl *FirstQualifierInScope = nullptr;
10886   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
10887   if (MemberNameInfo.getName()) {
10888     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
10889     if (!MemberNameInfo.getName())
10890       return ExprError();
10891   }
10892 
10893   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
10894                                         E->isArrow(),
10895                                         QualifierLoc,
10896                                         TemplateKWLoc,
10897                                         MemberNameInfo,
10898                                         Member,
10899                                         FoundDecl,
10900                                         (E->hasExplicitTemplateArgs()
10901                                            ? &TransArgs : nullptr),
10902                                         FirstQualifierInScope);
10903 }
10904 
10905 template<typename Derived>
10906 ExprResult
10907 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
10908   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10909   if (LHS.isInvalid())
10910     return ExprError();
10911 
10912   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10913   if (RHS.isInvalid())
10914     return ExprError();
10915 
10916   if (!getDerived().AlwaysRebuild() &&
10917       LHS.get() == E->getLHS() &&
10918       RHS.get() == E->getRHS())
10919     return E;
10920 
10921   if (E->isCompoundAssignmentOp())
10922     // FPFeatures has already been established from trailing storage
10923     return getDerived().RebuildBinaryOperator(
10924         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
10925   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10926   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
10927   getSema().CurFPFeatures =
10928       NewOverrides.applyOverrides(getSema().getLangOpts());
10929   getSema().FpPragmaStack.CurrentValue = NewOverrides;
10930   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
10931                                             LHS.get(), RHS.get());
10932 }
10933 
10934 template <typename Derived>
10935 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
10936     CXXRewrittenBinaryOperator *E) {
10937   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
10938 
10939   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
10940   if (LHS.isInvalid())
10941     return ExprError();
10942 
10943   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
10944   if (RHS.isInvalid())
10945     return ExprError();
10946 
10947   if (!getDerived().AlwaysRebuild() &&
10948       LHS.get() == Decomp.LHS &&
10949       RHS.get() == Decomp.RHS)
10950     return E;
10951 
10952   // Extract the already-resolved callee declarations so that we can restrict
10953   // ourselves to using them as the unqualified lookup results when rebuilding.
10954   UnresolvedSet<2> UnqualLookups;
10955   Expr *PossibleBinOps[] = {E->getSemanticForm(),
10956                             const_cast<Expr *>(Decomp.InnerBinOp)};
10957   for (Expr *PossibleBinOp : PossibleBinOps) {
10958     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
10959     if (!Op)
10960       continue;
10961     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
10962     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
10963       continue;
10964 
10965     // Transform the callee in case we built a call to a local extern
10966     // declaration.
10967     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
10968         E->getOperatorLoc(), Callee->getFoundDecl()));
10969     if (!Found)
10970       return ExprError();
10971     UnqualLookups.addDecl(Found);
10972   }
10973 
10974   return getDerived().RebuildCXXRewrittenBinaryOperator(
10975       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
10976 }
10977 
10978 template<typename Derived>
10979 ExprResult
10980 TreeTransform<Derived>::TransformCompoundAssignOperator(
10981                                                       CompoundAssignOperator *E) {
10982   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10983   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
10984   getSema().CurFPFeatures =
10985       NewOverrides.applyOverrides(getSema().getLangOpts());
10986   getSema().FpPragmaStack.CurrentValue = NewOverrides;
10987   return getDerived().TransformBinaryOperator(E);
10988 }
10989 
10990 template<typename Derived>
10991 ExprResult TreeTransform<Derived>::
10992 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
10993   // Just rebuild the common and RHS expressions and see whether we
10994   // get any changes.
10995 
10996   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
10997   if (commonExpr.isInvalid())
10998     return ExprError();
10999 
11000   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11001   if (rhs.isInvalid())
11002     return ExprError();
11003 
11004   if (!getDerived().AlwaysRebuild() &&
11005       commonExpr.get() == e->getCommon() &&
11006       rhs.get() == e->getFalseExpr())
11007     return e;
11008 
11009   return getDerived().RebuildConditionalOperator(commonExpr.get(),
11010                                                  e->getQuestionLoc(),
11011                                                  nullptr,
11012                                                  e->getColonLoc(),
11013                                                  rhs.get());
11014 }
11015 
11016 template<typename Derived>
11017 ExprResult
11018 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11019   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11020   if (Cond.isInvalid())
11021     return ExprError();
11022 
11023   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11024   if (LHS.isInvalid())
11025     return ExprError();
11026 
11027   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11028   if (RHS.isInvalid())
11029     return ExprError();
11030 
11031   if (!getDerived().AlwaysRebuild() &&
11032       Cond.get() == E->getCond() &&
11033       LHS.get() == E->getLHS() &&
11034       RHS.get() == E->getRHS())
11035     return E;
11036 
11037   return getDerived().RebuildConditionalOperator(Cond.get(),
11038                                                  E->getQuestionLoc(),
11039                                                  LHS.get(),
11040                                                  E->getColonLoc(),
11041                                                  RHS.get());
11042 }
11043 
11044 template<typename Derived>
11045 ExprResult
11046 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11047   // Implicit casts are eliminated during transformation, since they
11048   // will be recomputed by semantic analysis after transformation.
11049   return getDerived().TransformExpr(E->getSubExprAsWritten());
11050 }
11051 
11052 template<typename Derived>
11053 ExprResult
11054 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11055   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11056   if (!Type)
11057     return ExprError();
11058 
11059   ExprResult SubExpr
11060     = getDerived().TransformExpr(E->getSubExprAsWritten());
11061   if (SubExpr.isInvalid())
11062     return ExprError();
11063 
11064   if (!getDerived().AlwaysRebuild() &&
11065       Type == E->getTypeInfoAsWritten() &&
11066       SubExpr.get() == E->getSubExpr())
11067     return E;
11068 
11069   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11070                                             Type,
11071                                             E->getRParenLoc(),
11072                                             SubExpr.get());
11073 }
11074 
11075 template<typename Derived>
11076 ExprResult
11077 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11078   TypeSourceInfo *OldT = E->getTypeSourceInfo();
11079   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11080   if (!NewT)
11081     return ExprError();
11082 
11083   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11084   if (Init.isInvalid())
11085     return ExprError();
11086 
11087   if (!getDerived().AlwaysRebuild() &&
11088       OldT == NewT &&
11089       Init.get() == E->getInitializer())
11090     return SemaRef.MaybeBindToTemporary(E);
11091 
11092   // Note: the expression type doesn't necessarily match the
11093   // type-as-written, but that's okay, because it should always be
11094   // derivable from the initializer.
11095 
11096   return getDerived().RebuildCompoundLiteralExpr(
11097       E->getLParenLoc(), NewT,
11098       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11099 }
11100 
11101 template<typename Derived>
11102 ExprResult
11103 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11104   ExprResult Base = getDerived().TransformExpr(E->getBase());
11105   if (Base.isInvalid())
11106     return ExprError();
11107 
11108   if (!getDerived().AlwaysRebuild() &&
11109       Base.get() == E->getBase())
11110     return E;
11111 
11112   // FIXME: Bad source location
11113   SourceLocation FakeOperatorLoc =
11114       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11115   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
11116                                                   E->getAccessorLoc(),
11117                                                   E->getAccessor());
11118 }
11119 
11120 template<typename Derived>
11121 ExprResult
11122 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11123   if (InitListExpr *Syntactic = E->getSyntacticForm())
11124     E = Syntactic;
11125 
11126   bool InitChanged = false;
11127 
11128   EnterExpressionEvaluationContext Context(
11129       getSema(), EnterExpressionEvaluationContext::InitList);
11130 
11131   SmallVector<Expr*, 4> Inits;
11132   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11133                                   Inits, &InitChanged))
11134     return ExprError();
11135 
11136   if (!getDerived().AlwaysRebuild() && !InitChanged) {
11137     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11138     // in some cases. We can't reuse it in general, because the syntactic and
11139     // semantic forms are linked, and we can't know that semantic form will
11140     // match even if the syntactic form does.
11141   }
11142 
11143   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11144                                       E->getRBraceLoc());
11145 }
11146 
11147 template<typename Derived>
11148 ExprResult
11149 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11150   Designation Desig;
11151 
11152   // transform the initializer value
11153   ExprResult Init = getDerived().TransformExpr(E->getInit());
11154   if (Init.isInvalid())
11155     return ExprError();
11156 
11157   // transform the designators.
11158   SmallVector<Expr*, 4> ArrayExprs;
11159   bool ExprChanged = false;
11160   for (const DesignatedInitExpr::Designator &D : E->designators()) {
11161     if (D.isFieldDesignator()) {
11162       Desig.AddDesignator(Designator::getField(D.getFieldName(),
11163                                                D.getDotLoc(),
11164                                                D.getFieldLoc()));
11165       if (D.getField()) {
11166         FieldDecl *Field = cast_or_null<FieldDecl>(
11167             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
11168         if (Field != D.getField())
11169           // Rebuild the expression when the transformed FieldDecl is
11170           // different to the already assigned FieldDecl.
11171           ExprChanged = true;
11172       } else {
11173         // Ensure that the designator expression is rebuilt when there isn't
11174         // a resolved FieldDecl in the designator as we don't want to assign
11175         // a FieldDecl to a pattern designator that will be instantiated again.
11176         ExprChanged = true;
11177       }
11178       continue;
11179     }
11180 
11181     if (D.isArrayDesignator()) {
11182       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11183       if (Index.isInvalid())
11184         return ExprError();
11185 
11186       Desig.AddDesignator(
11187           Designator::getArray(Index.get(), D.getLBracketLoc()));
11188 
11189       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11190       ArrayExprs.push_back(Index.get());
11191       continue;
11192     }
11193 
11194     assert(D.isArrayRangeDesignator() && "New kind of designator?");
11195     ExprResult Start
11196       = getDerived().TransformExpr(E->getArrayRangeStart(D));
11197     if (Start.isInvalid())
11198       return ExprError();
11199 
11200     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11201     if (End.isInvalid())
11202       return ExprError();
11203 
11204     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
11205                                                   End.get(),
11206                                                   D.getLBracketLoc(),
11207                                                   D.getEllipsisLoc()));
11208 
11209     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11210                   End.get() != E->getArrayRangeEnd(D);
11211 
11212     ArrayExprs.push_back(Start.get());
11213     ArrayExprs.push_back(End.get());
11214   }
11215 
11216   if (!getDerived().AlwaysRebuild() &&
11217       Init.get() == E->getInit() &&
11218       !ExprChanged)
11219     return E;
11220 
11221   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11222                                                 E->getEqualOrColonLoc(),
11223                                                 E->usesGNUSyntax(), Init.get());
11224 }
11225 
11226 // Seems that if TransformInitListExpr() only works on the syntactic form of an
11227 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11228 template<typename Derived>
11229 ExprResult
11230 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11231     DesignatedInitUpdateExpr *E) {
11232   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
11233                    "initializer");
11234   return ExprError();
11235 }
11236 
11237 template<typename Derived>
11238 ExprResult
11239 TreeTransform<Derived>::TransformNoInitExpr(
11240     NoInitExpr *E) {
11241   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
11242   return ExprError();
11243 }
11244 
11245 template<typename Derived>
11246 ExprResult
11247 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11248   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
11249   return ExprError();
11250 }
11251 
11252 template<typename Derived>
11253 ExprResult
11254 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11255   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
11256   return ExprError();
11257 }
11258 
11259 template<typename Derived>
11260 ExprResult
11261 TreeTransform<Derived>::TransformImplicitValueInitExpr(
11262                                                      ImplicitValueInitExpr *E) {
11263   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11264 
11265   // FIXME: Will we ever have proper type location here? Will we actually
11266   // need to transform the type?
11267   QualType T = getDerived().TransformType(E->getType());
11268   if (T.isNull())
11269     return ExprError();
11270 
11271   if (!getDerived().AlwaysRebuild() &&
11272       T == E->getType())
11273     return E;
11274 
11275   return getDerived().RebuildImplicitValueInitExpr(T);
11276 }
11277 
11278 template<typename Derived>
11279 ExprResult
11280 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11281   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11282   if (!TInfo)
11283     return ExprError();
11284 
11285   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11286   if (SubExpr.isInvalid())
11287     return ExprError();
11288 
11289   if (!getDerived().AlwaysRebuild() &&
11290       TInfo == E->getWrittenTypeInfo() &&
11291       SubExpr.get() == E->getSubExpr())
11292     return E;
11293 
11294   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11295                                        TInfo, E->getRParenLoc());
11296 }
11297 
11298 template<typename Derived>
11299 ExprResult
11300 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11301   bool ArgumentChanged = false;
11302   SmallVector<Expr*, 4> Inits;
11303   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11304                      &ArgumentChanged))
11305     return ExprError();
11306 
11307   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11308                                            Inits,
11309                                            E->getRParenLoc());
11310 }
11311 
11312 /// Transform an address-of-label expression.
11313 ///
11314 /// By default, the transformation of an address-of-label expression always
11315 /// rebuilds the expression, so that the label identifier can be resolved to
11316 /// the corresponding label statement by semantic analysis.
11317 template<typename Derived>
11318 ExprResult
11319 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11320   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11321                                         E->getLabel());
11322   if (!LD)
11323     return ExprError();
11324 
11325   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11326                                            cast<LabelDecl>(LD));
11327 }
11328 
11329 template<typename Derived>
11330 ExprResult
11331 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11332   SemaRef.ActOnStartStmtExpr();
11333   StmtResult SubStmt
11334     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11335   if (SubStmt.isInvalid()) {
11336     SemaRef.ActOnStmtExprError();
11337     return ExprError();
11338   }
11339 
11340   unsigned OldDepth = E->getTemplateDepth();
11341   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11342 
11343   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11344       SubStmt.get() == E->getSubStmt()) {
11345     // Calling this an 'error' is unintuitive, but it does the right thing.
11346     SemaRef.ActOnStmtExprError();
11347     return SemaRef.MaybeBindToTemporary(E);
11348   }
11349 
11350   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11351                                       E->getRParenLoc(), NewDepth);
11352 }
11353 
11354 template<typename Derived>
11355 ExprResult
11356 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11357   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11358   if (Cond.isInvalid())
11359     return ExprError();
11360 
11361   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11362   if (LHS.isInvalid())
11363     return ExprError();
11364 
11365   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11366   if (RHS.isInvalid())
11367     return ExprError();
11368 
11369   if (!getDerived().AlwaysRebuild() &&
11370       Cond.get() == E->getCond() &&
11371       LHS.get() == E->getLHS() &&
11372       RHS.get() == E->getRHS())
11373     return E;
11374 
11375   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11376                                         Cond.get(), LHS.get(), RHS.get(),
11377                                         E->getRParenLoc());
11378 }
11379 
11380 template<typename Derived>
11381 ExprResult
11382 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11383   return E;
11384 }
11385 
11386 template<typename Derived>
11387 ExprResult
11388 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11389   switch (E->getOperator()) {
11390   case OO_New:
11391   case OO_Delete:
11392   case OO_Array_New:
11393   case OO_Array_Delete:
11394     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
11395 
11396   case OO_Call: {
11397     // This is a call to an object's operator().
11398     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
11399 
11400     // Transform the object itself.
11401     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11402     if (Object.isInvalid())
11403       return ExprError();
11404 
11405     // FIXME: Poor location information
11406     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11407         static_cast<Expr *>(Object.get())->getEndLoc());
11408 
11409     // Transform the call arguments.
11410     SmallVector<Expr*, 8> Args;
11411     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11412                                     Args))
11413       return ExprError();
11414 
11415     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11416                                         E->getEndLoc());
11417   }
11418 
11419 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11420   case OO_##Name:
11421 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11422 #include "clang/Basic/OperatorKinds.def"
11423   case OO_Subscript:
11424     // Handled below.
11425     break;
11426 
11427   case OO_Conditional:
11428     llvm_unreachable("conditional operator is not actually overloadable");
11429 
11430   case OO_None:
11431   case NUM_OVERLOADED_OPERATORS:
11432     llvm_unreachable("not an overloaded operator?");
11433   }
11434 
11435   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11436   if (Callee.isInvalid())
11437     return ExprError();
11438 
11439   ExprResult First;
11440   if (E->getOperator() == OO_Amp)
11441     First = getDerived().TransformAddressOfOperand(E->getArg(0));
11442   else
11443     First = getDerived().TransformExpr(E->getArg(0));
11444   if (First.isInvalid())
11445     return ExprError();
11446 
11447   ExprResult Second;
11448   if (E->getNumArgs() == 2) {
11449     Second = getDerived().TransformExpr(E->getArg(1));
11450     if (Second.isInvalid())
11451       return ExprError();
11452   }
11453 
11454   if (!getDerived().AlwaysRebuild() &&
11455       Callee.get() == E->getCallee() &&
11456       First.get() == E->getArg(0) &&
11457       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11458     return SemaRef.MaybeBindToTemporary(E);
11459 
11460   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11461   FPOptionsOverride NewOverrides(E->getFPFeatures());
11462   getSema().CurFPFeatures =
11463       NewOverrides.applyOverrides(getSema().getLangOpts());
11464   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11465 
11466   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11467                                                  E->getOperatorLoc(),
11468                                                  Callee.get(),
11469                                                  First.get(),
11470                                                  Second.get());
11471 }
11472 
11473 template<typename Derived>
11474 ExprResult
11475 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11476   return getDerived().TransformCallExpr(E);
11477 }
11478 
11479 template <typename Derived>
11480 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11481   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11482                          getSema().CurContext != E->getParentContext();
11483 
11484   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11485     return E;
11486 
11487   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
11488                                            E->getEndLoc(),
11489                                            getSema().CurContext);
11490 }
11491 
11492 template<typename Derived>
11493 ExprResult
11494 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11495   // Transform the callee.
11496   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11497   if (Callee.isInvalid())
11498     return ExprError();
11499 
11500   // Transform exec config.
11501   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
11502   if (EC.isInvalid())
11503     return ExprError();
11504 
11505   // Transform arguments.
11506   bool ArgChanged = false;
11507   SmallVector<Expr*, 8> Args;
11508   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11509                                   &ArgChanged))
11510     return ExprError();
11511 
11512   if (!getDerived().AlwaysRebuild() &&
11513       Callee.get() == E->getCallee() &&
11514       !ArgChanged)
11515     return SemaRef.MaybeBindToTemporary(E);
11516 
11517   // FIXME: Wrong source location information for the '('.
11518   SourceLocation FakeLParenLoc
11519     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11520   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11521                                       Args,
11522                                       E->getRParenLoc(), EC.get());
11523 }
11524 
11525 template<typename Derived>
11526 ExprResult
11527 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
11528   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11529   if (!Type)
11530     return ExprError();
11531 
11532   ExprResult SubExpr
11533     = getDerived().TransformExpr(E->getSubExprAsWritten());
11534   if (SubExpr.isInvalid())
11535     return ExprError();
11536 
11537   if (!getDerived().AlwaysRebuild() &&
11538       Type == E->getTypeInfoAsWritten() &&
11539       SubExpr.get() == E->getSubExpr())
11540     return E;
11541   return getDerived().RebuildCXXNamedCastExpr(
11542       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
11543       Type, E->getAngleBrackets().getEnd(),
11544       // FIXME. this should be '(' location
11545       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
11546 }
11547 
11548 template<typename Derived>
11549 ExprResult
11550 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
11551   TypeSourceInfo *TSI =
11552       getDerived().TransformType(BCE->getTypeInfoAsWritten());
11553   if (!TSI)
11554     return ExprError();
11555 
11556   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
11557   if (Sub.isInvalid())
11558     return ExprError();
11559 
11560   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
11561                                                 Sub.get(), BCE->getEndLoc());
11562 }
11563 
11564 template<typename Derived>
11565 ExprResult
11566 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
11567   return getDerived().TransformCXXNamedCastExpr(E);
11568 }
11569 
11570 template<typename Derived>
11571 ExprResult
11572 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
11573   return getDerived().TransformCXXNamedCastExpr(E);
11574 }
11575 
11576 template<typename Derived>
11577 ExprResult
11578 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
11579                                                       CXXReinterpretCastExpr *E) {
11580   return getDerived().TransformCXXNamedCastExpr(E);
11581 }
11582 
11583 template<typename Derived>
11584 ExprResult
11585 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
11586   return getDerived().TransformCXXNamedCastExpr(E);
11587 }
11588 
11589 template<typename Derived>
11590 ExprResult
11591 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
11592   return getDerived().TransformCXXNamedCastExpr(E);
11593 }
11594 
11595 template<typename Derived>
11596 ExprResult
11597 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
11598                                                      CXXFunctionalCastExpr *E) {
11599   TypeSourceInfo *Type =
11600       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
11601   if (!Type)
11602     return ExprError();
11603 
11604   ExprResult SubExpr
11605     = getDerived().TransformExpr(E->getSubExprAsWritten());
11606   if (SubExpr.isInvalid())
11607     return ExprError();
11608 
11609   if (!getDerived().AlwaysRebuild() &&
11610       Type == E->getTypeInfoAsWritten() &&
11611       SubExpr.get() == E->getSubExpr())
11612     return E;
11613 
11614   return getDerived().RebuildCXXFunctionalCastExpr(Type,
11615                                                    E->getLParenLoc(),
11616                                                    SubExpr.get(),
11617                                                    E->getRParenLoc(),
11618                                                    E->isListInitialization());
11619 }
11620 
11621 template<typename Derived>
11622 ExprResult
11623 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
11624   if (E->isTypeOperand()) {
11625     TypeSourceInfo *TInfo
11626       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11627     if (!TInfo)
11628       return ExprError();
11629 
11630     if (!getDerived().AlwaysRebuild() &&
11631         TInfo == E->getTypeOperandSourceInfo())
11632       return E;
11633 
11634     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11635                                              TInfo, E->getEndLoc());
11636   }
11637 
11638   // Typeid's operand is an unevaluated context, unless it's a polymorphic
11639   // type.  We must not unilaterally enter unevaluated context here, as then
11640   // semantic processing can re-transform an already transformed operand.
11641   Expr *Op = E->getExprOperand();
11642   auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
11643   if (E->isGLValue())
11644     if (auto *RecordT = Op->getType()->getAs<RecordType>())
11645       if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
11646         EvalCtx = SemaRef.ExprEvalContexts.back().Context;
11647 
11648   EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
11649                                                Sema::ReuseLambdaContextDecl);
11650 
11651   ExprResult SubExpr = getDerived().TransformExpr(Op);
11652   if (SubExpr.isInvalid())
11653     return ExprError();
11654 
11655   if (!getDerived().AlwaysRebuild() &&
11656       SubExpr.get() == E->getExprOperand())
11657     return E;
11658 
11659   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11660                                            SubExpr.get(), E->getEndLoc());
11661 }
11662 
11663 template<typename Derived>
11664 ExprResult
11665 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
11666   if (E->isTypeOperand()) {
11667     TypeSourceInfo *TInfo
11668       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11669     if (!TInfo)
11670       return ExprError();
11671 
11672     if (!getDerived().AlwaysRebuild() &&
11673         TInfo == E->getTypeOperandSourceInfo())
11674       return E;
11675 
11676     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11677                                              TInfo, E->getEndLoc());
11678   }
11679 
11680   EnterExpressionEvaluationContext Unevaluated(
11681       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11682 
11683   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11684   if (SubExpr.isInvalid())
11685     return ExprError();
11686 
11687   if (!getDerived().AlwaysRebuild() &&
11688       SubExpr.get() == E->getExprOperand())
11689     return E;
11690 
11691   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11692                                            SubExpr.get(), E->getEndLoc());
11693 }
11694 
11695 template<typename Derived>
11696 ExprResult
11697 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
11698   return E;
11699 }
11700 
11701 template<typename Derived>
11702 ExprResult
11703 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
11704                                                      CXXNullPtrLiteralExpr *E) {
11705   return E;
11706 }
11707 
11708 template<typename Derived>
11709 ExprResult
11710 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
11711   QualType T = getSema().getCurrentThisType();
11712 
11713   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
11714     // Mark it referenced in the new context regardless.
11715     // FIXME: this is a bit instantiation-specific.
11716     getSema().MarkThisReferenced(E);
11717     return E;
11718   }
11719 
11720   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
11721 }
11722 
11723 template<typename Derived>
11724 ExprResult
11725 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
11726   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11727   if (SubExpr.isInvalid())
11728     return ExprError();
11729 
11730   if (!getDerived().AlwaysRebuild() &&
11731       SubExpr.get() == E->getSubExpr())
11732     return E;
11733 
11734   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
11735                                           E->isThrownVariableInScope());
11736 }
11737 
11738 template<typename Derived>
11739 ExprResult
11740 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11741   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
11742       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
11743   if (!Param)
11744     return ExprError();
11745 
11746   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
11747       E->getUsedContext() == SemaRef.CurContext)
11748     return E;
11749 
11750   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
11751 }
11752 
11753 template<typename Derived>
11754 ExprResult
11755 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
11756   FieldDecl *Field = cast_or_null<FieldDecl>(
11757       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
11758   if (!Field)
11759     return ExprError();
11760 
11761   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
11762       E->getUsedContext() == SemaRef.CurContext)
11763     return E;
11764 
11765   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
11766 }
11767 
11768 template<typename Derived>
11769 ExprResult
11770 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
11771                                                     CXXScalarValueInitExpr *E) {
11772   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
11773   if (!T)
11774     return ExprError();
11775 
11776   if (!getDerived().AlwaysRebuild() &&
11777       T == E->getTypeSourceInfo())
11778     return E;
11779 
11780   return getDerived().RebuildCXXScalarValueInitExpr(T,
11781                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
11782                                                     E->getRParenLoc());
11783 }
11784 
11785 template<typename Derived>
11786 ExprResult
11787 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
11788   // Transform the type that we're allocating
11789   TypeSourceInfo *AllocTypeInfo =
11790       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
11791   if (!AllocTypeInfo)
11792     return ExprError();
11793 
11794   // Transform the size of the array we're allocating (if any).
11795   Optional<Expr *> ArraySize;
11796   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
11797     ExprResult NewArraySize;
11798     if (*OldArraySize) {
11799       NewArraySize = getDerived().TransformExpr(*OldArraySize);
11800       if (NewArraySize.isInvalid())
11801         return ExprError();
11802     }
11803     ArraySize = NewArraySize.get();
11804   }
11805 
11806   // Transform the placement arguments (if any).
11807   bool ArgumentChanged = false;
11808   SmallVector<Expr*, 8> PlacementArgs;
11809   if (getDerived().TransformExprs(E->getPlacementArgs(),
11810                                   E->getNumPlacementArgs(), true,
11811                                   PlacementArgs, &ArgumentChanged))
11812     return ExprError();
11813 
11814   // Transform the initializer (if any).
11815   Expr *OldInit = E->getInitializer();
11816   ExprResult NewInit;
11817   if (OldInit)
11818     NewInit = getDerived().TransformInitializer(OldInit, true);
11819   if (NewInit.isInvalid())
11820     return ExprError();
11821 
11822   // Transform new operator and delete operator.
11823   FunctionDecl *OperatorNew = nullptr;
11824   if (E->getOperatorNew()) {
11825     OperatorNew = cast_or_null<FunctionDecl>(
11826         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
11827     if (!OperatorNew)
11828       return ExprError();
11829   }
11830 
11831   FunctionDecl *OperatorDelete = nullptr;
11832   if (E->getOperatorDelete()) {
11833     OperatorDelete = cast_or_null<FunctionDecl>(
11834         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
11835     if (!OperatorDelete)
11836       return ExprError();
11837   }
11838 
11839   if (!getDerived().AlwaysRebuild() &&
11840       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
11841       ArraySize == E->getArraySize() &&
11842       NewInit.get() == OldInit &&
11843       OperatorNew == E->getOperatorNew() &&
11844       OperatorDelete == E->getOperatorDelete() &&
11845       !ArgumentChanged) {
11846     // Mark any declarations we need as referenced.
11847     // FIXME: instantiation-specific.
11848     if (OperatorNew)
11849       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
11850     if (OperatorDelete)
11851       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
11852 
11853     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
11854       QualType ElementType
11855         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
11856       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
11857         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
11858         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
11859           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
11860         }
11861       }
11862     }
11863 
11864     return E;
11865   }
11866 
11867   QualType AllocType = AllocTypeInfo->getType();
11868   if (!ArraySize) {
11869     // If no array size was specified, but the new expression was
11870     // instantiated with an array type (e.g., "new T" where T is
11871     // instantiated with "int[4]"), extract the outer bound from the
11872     // array type as our array size. We do this with constant and
11873     // dependently-sized array types.
11874     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
11875     if (!ArrayT) {
11876       // Do nothing
11877     } else if (const ConstantArrayType *ConsArrayT
11878                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
11879       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
11880                                          SemaRef.Context.getSizeType(),
11881                                          /*FIXME:*/ E->getBeginLoc());
11882       AllocType = ConsArrayT->getElementType();
11883     } else if (const DependentSizedArrayType *DepArrayT
11884                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
11885       if (DepArrayT->getSizeExpr()) {
11886         ArraySize = DepArrayT->getSizeExpr();
11887         AllocType = DepArrayT->getElementType();
11888       }
11889     }
11890   }
11891 
11892   return getDerived().RebuildCXXNewExpr(
11893       E->getBeginLoc(), E->isGlobalNew(),
11894       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
11895       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
11896       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
11897 }
11898 
11899 template<typename Derived>
11900 ExprResult
11901 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
11902   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
11903   if (Operand.isInvalid())
11904     return ExprError();
11905 
11906   // Transform the delete operator, if known.
11907   FunctionDecl *OperatorDelete = nullptr;
11908   if (E->getOperatorDelete()) {
11909     OperatorDelete = cast_or_null<FunctionDecl>(
11910         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
11911     if (!OperatorDelete)
11912       return ExprError();
11913   }
11914 
11915   if (!getDerived().AlwaysRebuild() &&
11916       Operand.get() == E->getArgument() &&
11917       OperatorDelete == E->getOperatorDelete()) {
11918     // Mark any declarations we need as referenced.
11919     // FIXME: instantiation-specific.
11920     if (OperatorDelete)
11921       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
11922 
11923     if (!E->getArgument()->isTypeDependent()) {
11924       QualType Destroyed = SemaRef.Context.getBaseElementType(
11925                                                          E->getDestroyedType());
11926       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11927         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11928         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
11929                                        SemaRef.LookupDestructor(Record));
11930       }
11931     }
11932 
11933     return E;
11934   }
11935 
11936   return getDerived().RebuildCXXDeleteExpr(
11937       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
11938 }
11939 
11940 template<typename Derived>
11941 ExprResult
11942 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
11943                                                      CXXPseudoDestructorExpr *E) {
11944   ExprResult Base = getDerived().TransformExpr(E->getBase());
11945   if (Base.isInvalid())
11946     return ExprError();
11947 
11948   ParsedType ObjectTypePtr;
11949   bool MayBePseudoDestructor = false;
11950   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11951                                               E->getOperatorLoc(),
11952                                         E->isArrow()? tok::arrow : tok::period,
11953                                               ObjectTypePtr,
11954                                               MayBePseudoDestructor);
11955   if (Base.isInvalid())
11956     return ExprError();
11957 
11958   QualType ObjectType = ObjectTypePtr.get();
11959   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
11960   if (QualifierLoc) {
11961     QualifierLoc
11962       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
11963     if (!QualifierLoc)
11964       return ExprError();
11965   }
11966   CXXScopeSpec SS;
11967   SS.Adopt(QualifierLoc);
11968 
11969   PseudoDestructorTypeStorage Destroyed;
11970   if (E->getDestroyedTypeInfo()) {
11971     TypeSourceInfo *DestroyedTypeInfo
11972       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
11973                                                 ObjectType, nullptr, SS);
11974     if (!DestroyedTypeInfo)
11975       return ExprError();
11976     Destroyed = DestroyedTypeInfo;
11977   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
11978     // We aren't likely to be able to resolve the identifier down to a type
11979     // now anyway, so just retain the identifier.
11980     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
11981                                             E->getDestroyedTypeLoc());
11982   } else {
11983     // Look for a destructor known with the given name.
11984     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
11985                                               *E->getDestroyedTypeIdentifier(),
11986                                                 E->getDestroyedTypeLoc(),
11987                                                 /*Scope=*/nullptr,
11988                                                 SS, ObjectTypePtr,
11989                                                 false);
11990     if (!T)
11991       return ExprError();
11992 
11993     Destroyed
11994       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
11995                                                  E->getDestroyedTypeLoc());
11996   }
11997 
11998   TypeSourceInfo *ScopeTypeInfo = nullptr;
11999   if (E->getScopeTypeInfo()) {
12000     CXXScopeSpec EmptySS;
12001     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12002                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12003     if (!ScopeTypeInfo)
12004       return ExprError();
12005   }
12006 
12007   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12008                                                      E->getOperatorLoc(),
12009                                                      E->isArrow(),
12010                                                      SS,
12011                                                      ScopeTypeInfo,
12012                                                      E->getColonColonLoc(),
12013                                                      E->getTildeLoc(),
12014                                                      Destroyed);
12015 }
12016 
12017 template <typename Derived>
12018 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12019                                                         bool RequiresADL,
12020                                                         LookupResult &R) {
12021   // Transform all the decls.
12022   bool AllEmptyPacks = true;
12023   for (auto *OldD : Old->decls()) {
12024     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12025     if (!InstD) {
12026       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12027       // This can happen because of dependent hiding.
12028       if (isa<UsingShadowDecl>(OldD))
12029         continue;
12030       else {
12031         R.clear();
12032         return true;
12033       }
12034     }
12035 
12036     // Expand using pack declarations.
12037     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12038     ArrayRef<NamedDecl*> Decls = SingleDecl;
12039     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12040       Decls = UPD->expansions();
12041 
12042     // Expand using declarations.
12043     for (auto *D : Decls) {
12044       if (auto *UD = dyn_cast<UsingDecl>(D)) {
12045         for (auto *SD : UD->shadows())
12046           R.addDecl(SD);
12047       } else {
12048         R.addDecl(D);
12049       }
12050     }
12051 
12052     AllEmptyPacks &= Decls.empty();
12053   };
12054 
12055   // C++ [temp.res]/8.4.2:
12056   //   The program is ill-formed, no diagnostic required, if [...] lookup for
12057   //   a name in the template definition found a using-declaration, but the
12058   //   lookup in the corresponding scope in the instantiation odoes not find
12059   //   any declarations because the using-declaration was a pack expansion and
12060   //   the corresponding pack is empty
12061   if (AllEmptyPacks && !RequiresADL) {
12062     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12063         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12064     return true;
12065   }
12066 
12067   // Resolve a kind, but don't do any further analysis.  If it's
12068   // ambiguous, the callee needs to deal with it.
12069   R.resolveKind();
12070   return false;
12071 }
12072 
12073 template<typename Derived>
12074 ExprResult
12075 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12076                                                   UnresolvedLookupExpr *Old) {
12077   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12078                  Sema::LookupOrdinaryName);
12079 
12080   // Transform the declaration set.
12081   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12082     return ExprError();
12083 
12084   // Rebuild the nested-name qualifier, if present.
12085   CXXScopeSpec SS;
12086   if (Old->getQualifierLoc()) {
12087     NestedNameSpecifierLoc QualifierLoc
12088       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12089     if (!QualifierLoc)
12090       return ExprError();
12091 
12092     SS.Adopt(QualifierLoc);
12093   }
12094 
12095   if (Old->getNamingClass()) {
12096     CXXRecordDecl *NamingClass
12097       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12098                                                             Old->getNameLoc(),
12099                                                         Old->getNamingClass()));
12100     if (!NamingClass) {
12101       R.clear();
12102       return ExprError();
12103     }
12104 
12105     R.setNamingClass(NamingClass);
12106   }
12107 
12108   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12109 
12110   // If we have neither explicit template arguments, nor the template keyword,
12111   // it's a normal declaration name or member reference.
12112   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12113     NamedDecl *D = R.getAsSingle<NamedDecl>();
12114     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12115     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12116     // give a good diagnostic.
12117     if (D && D->isCXXInstanceMember()) {
12118       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12119                                                      /*TemplateArgs=*/nullptr,
12120                                                      /*Scope=*/nullptr);
12121     }
12122 
12123     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12124   }
12125 
12126   // If we have template arguments, rebuild them, then rebuild the
12127   // templateid expression.
12128   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12129   if (Old->hasExplicitTemplateArgs() &&
12130       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12131                                               Old->getNumTemplateArgs(),
12132                                               TransArgs)) {
12133     R.clear();
12134     return ExprError();
12135   }
12136 
12137   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12138                                             Old->requiresADL(), &TransArgs);
12139 }
12140 
12141 template<typename Derived>
12142 ExprResult
12143 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12144   bool ArgChanged = false;
12145   SmallVector<TypeSourceInfo *, 4> Args;
12146   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12147     TypeSourceInfo *From = E->getArg(I);
12148     TypeLoc FromTL = From->getTypeLoc();
12149     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12150       TypeLocBuilder TLB;
12151       TLB.reserve(FromTL.getFullDataSize());
12152       QualType To = getDerived().TransformType(TLB, FromTL);
12153       if (To.isNull())
12154         return ExprError();
12155 
12156       if (To == From->getType())
12157         Args.push_back(From);
12158       else {
12159         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12160         ArgChanged = true;
12161       }
12162       continue;
12163     }
12164 
12165     ArgChanged = true;
12166 
12167     // We have a pack expansion. Instantiate it.
12168     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12169     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12170     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12171     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12172 
12173     // Determine whether the set of unexpanded parameter packs can and should
12174     // be expanded.
12175     bool Expand = true;
12176     bool RetainExpansion = false;
12177     Optional<unsigned> OrigNumExpansions =
12178         ExpansionTL.getTypePtr()->getNumExpansions();
12179     Optional<unsigned> NumExpansions = OrigNumExpansions;
12180     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12181                                              PatternTL.getSourceRange(),
12182                                              Unexpanded,
12183                                              Expand, RetainExpansion,
12184                                              NumExpansions))
12185       return ExprError();
12186 
12187     if (!Expand) {
12188       // The transform has determined that we should perform a simple
12189       // transformation on the pack expansion, producing another pack
12190       // expansion.
12191       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12192 
12193       TypeLocBuilder TLB;
12194       TLB.reserve(From->getTypeLoc().getFullDataSize());
12195 
12196       QualType To = getDerived().TransformType(TLB, PatternTL);
12197       if (To.isNull())
12198         return ExprError();
12199 
12200       To = getDerived().RebuildPackExpansionType(To,
12201                                                  PatternTL.getSourceRange(),
12202                                                  ExpansionTL.getEllipsisLoc(),
12203                                                  NumExpansions);
12204       if (To.isNull())
12205         return ExprError();
12206 
12207       PackExpansionTypeLoc ToExpansionTL
12208         = TLB.push<PackExpansionTypeLoc>(To);
12209       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12210       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12211       continue;
12212     }
12213 
12214     // Expand the pack expansion by substituting for each argument in the
12215     // pack(s).
12216     for (unsigned I = 0; I != *NumExpansions; ++I) {
12217       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12218       TypeLocBuilder TLB;
12219       TLB.reserve(PatternTL.getFullDataSize());
12220       QualType To = getDerived().TransformType(TLB, PatternTL);
12221       if (To.isNull())
12222         return ExprError();
12223 
12224       if (To->containsUnexpandedParameterPack()) {
12225         To = getDerived().RebuildPackExpansionType(To,
12226                                                    PatternTL.getSourceRange(),
12227                                                    ExpansionTL.getEllipsisLoc(),
12228                                                    NumExpansions);
12229         if (To.isNull())
12230           return ExprError();
12231 
12232         PackExpansionTypeLoc ToExpansionTL
12233           = TLB.push<PackExpansionTypeLoc>(To);
12234         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12235       }
12236 
12237       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12238     }
12239 
12240     if (!RetainExpansion)
12241       continue;
12242 
12243     // If we're supposed to retain a pack expansion, do so by temporarily
12244     // forgetting the partially-substituted parameter pack.
12245     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12246 
12247     TypeLocBuilder TLB;
12248     TLB.reserve(From->getTypeLoc().getFullDataSize());
12249 
12250     QualType To = getDerived().TransformType(TLB, PatternTL);
12251     if (To.isNull())
12252       return ExprError();
12253 
12254     To = getDerived().RebuildPackExpansionType(To,
12255                                                PatternTL.getSourceRange(),
12256                                                ExpansionTL.getEllipsisLoc(),
12257                                                NumExpansions);
12258     if (To.isNull())
12259       return ExprError();
12260 
12261     PackExpansionTypeLoc ToExpansionTL
12262       = TLB.push<PackExpansionTypeLoc>(To);
12263     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12264     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12265   }
12266 
12267   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12268     return E;
12269 
12270   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12271                                        E->getEndLoc());
12272 }
12273 
12274 template<typename Derived>
12275 ExprResult
12276 TreeTransform<Derived>::TransformConceptSpecializationExpr(
12277                                                  ConceptSpecializationExpr *E) {
12278   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12279   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12280   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12281                                               Old->NumTemplateArgs, TransArgs))
12282     return ExprError();
12283 
12284   return getDerived().RebuildConceptSpecializationExpr(
12285       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12286       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12287       &TransArgs);
12288 }
12289 
12290 template<typename Derived>
12291 ExprResult
12292 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12293   SmallVector<ParmVarDecl*, 4> TransParams;
12294   SmallVector<QualType, 4> TransParamTypes;
12295   Sema::ExtParameterInfoBuilder ExtParamInfos;
12296 
12297   // C++2a [expr.prim.req]p2
12298   // Expressions appearing within a requirement-body are unevaluated operands.
12299   EnterExpressionEvaluationContext Ctx(
12300       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12301 
12302   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12303       getSema().Context, getSema().CurContext,
12304       E->getBody()->getBeginLoc());
12305 
12306   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12307 
12308   if (getDerived().TransformFunctionTypeParams(E->getRequiresKWLoc(),
12309                                                E->getLocalParameters(),
12310                                                /*ParamTypes=*/nullptr,
12311                                                /*ParamInfos=*/nullptr,
12312                                                TransParamTypes, &TransParams,
12313                                                ExtParamInfos))
12314     return ExprError();
12315 
12316   for (ParmVarDecl *Param : TransParams)
12317     Param->setDeclContext(Body);
12318 
12319   SmallVector<concepts::Requirement *, 4> TransReqs;
12320   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12321                                                      TransReqs))
12322     return ExprError();
12323 
12324   for (concepts::Requirement *Req : TransReqs) {
12325     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12326       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12327         ER->getReturnTypeRequirement()
12328                 .getTypeConstraintTemplateParameterList()->getParam(0)
12329                 ->setDeclContext(Body);
12330       }
12331     }
12332   }
12333 
12334   return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12335                                           TransParams, TransReqs,
12336                                           E->getRBraceLoc());
12337 }
12338 
12339 template<typename Derived>
12340 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12341     ArrayRef<concepts::Requirement *> Reqs,
12342     SmallVectorImpl<concepts::Requirement *> &Transformed) {
12343   for (concepts::Requirement *Req : Reqs) {
12344     concepts::Requirement *TransReq = nullptr;
12345     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12346       TransReq = getDerived().TransformTypeRequirement(TypeReq);
12347     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12348       TransReq = getDerived().TransformExprRequirement(ExprReq);
12349     else
12350       TransReq = getDerived().TransformNestedRequirement(
12351                      cast<concepts::NestedRequirement>(Req));
12352     if (!TransReq)
12353       return true;
12354     Transformed.push_back(TransReq);
12355   }
12356   return false;
12357 }
12358 
12359 template<typename Derived>
12360 concepts::TypeRequirement *
12361 TreeTransform<Derived>::TransformTypeRequirement(
12362     concepts::TypeRequirement *Req) {
12363   if (Req->isSubstitutionFailure()) {
12364     if (getDerived().AlwaysRebuild())
12365       return getDerived().RebuildTypeRequirement(
12366               Req->getSubstitutionDiagnostic());
12367     return Req;
12368   }
12369   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12370   if (!TransType)
12371     return nullptr;
12372   return getDerived().RebuildTypeRequirement(TransType);
12373 }
12374 
12375 template<typename Derived>
12376 concepts::ExprRequirement *
12377 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12378   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12379   if (Req->isExprSubstitutionFailure())
12380     TransExpr = Req->getExprSubstitutionDiagnostic();
12381   else {
12382     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12383     if (TransExprRes.isInvalid())
12384       return nullptr;
12385     TransExpr = TransExprRes.get();
12386   }
12387 
12388   llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12389   const auto &RetReq = Req->getReturnTypeRequirement();
12390   if (RetReq.isEmpty())
12391     TransRetReq.emplace();
12392   else if (RetReq.isSubstitutionFailure())
12393     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12394   else if (RetReq.isTypeConstraint()) {
12395     TemplateParameterList *OrigTPL =
12396         RetReq.getTypeConstraintTemplateParameterList();
12397     TemplateParameterList *TPL =
12398         getDerived().TransformTemplateParameterList(OrigTPL);
12399     if (!TPL)
12400       return nullptr;
12401     TransRetReq.emplace(TPL);
12402   }
12403   assert(TransRetReq.hasValue() &&
12404          "All code paths leading here must set TransRetReq");
12405   if (Expr *E = TransExpr.dyn_cast<Expr *>())
12406     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12407                                                Req->getNoexceptLoc(),
12408                                                std::move(*TransRetReq));
12409   return getDerived().RebuildExprRequirement(
12410       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12411       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12412 }
12413 
12414 template<typename Derived>
12415 concepts::NestedRequirement *
12416 TreeTransform<Derived>::TransformNestedRequirement(
12417     concepts::NestedRequirement *Req) {
12418   if (Req->isSubstitutionFailure()) {
12419     if (getDerived().AlwaysRebuild())
12420       return getDerived().RebuildNestedRequirement(
12421           Req->getSubstitutionDiagnostic());
12422     return Req;
12423   }
12424   ExprResult TransConstraint =
12425       getDerived().TransformExpr(Req->getConstraintExpr());
12426   if (TransConstraint.isInvalid())
12427     return nullptr;
12428   return getDerived().RebuildNestedRequirement(TransConstraint.get());
12429 }
12430 
12431 template<typename Derived>
12432 ExprResult
12433 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12434   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12435   if (!T)
12436     return ExprError();
12437 
12438   if (!getDerived().AlwaysRebuild() &&
12439       T == E->getQueriedTypeSourceInfo())
12440     return E;
12441 
12442   ExprResult SubExpr;
12443   {
12444     EnterExpressionEvaluationContext Unevaluated(
12445         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12446     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12447     if (SubExpr.isInvalid())
12448       return ExprError();
12449 
12450     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12451       return E;
12452   }
12453 
12454   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12455                                             SubExpr.get(), E->getEndLoc());
12456 }
12457 
12458 template<typename Derived>
12459 ExprResult
12460 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12461   ExprResult SubExpr;
12462   {
12463     EnterExpressionEvaluationContext Unevaluated(
12464         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12465     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12466     if (SubExpr.isInvalid())
12467       return ExprError();
12468 
12469     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12470       return E;
12471   }
12472 
12473   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12474                                              SubExpr.get(), E->getEndLoc());
12475 }
12476 
12477 template <typename Derived>
12478 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12479     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12480     TypeSourceInfo **RecoveryTSI) {
12481   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
12482       DRE, AddrTaken, RecoveryTSI);
12483 
12484   // Propagate both errors and recovered types, which return ExprEmpty.
12485   if (!NewDRE.isUsable())
12486     return NewDRE;
12487 
12488   // We got an expr, wrap it up in parens.
12489   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
12490     return PE;
12491   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
12492                                        PE->getRParen());
12493 }
12494 
12495 template <typename Derived>
12496 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12497     DependentScopeDeclRefExpr *E) {
12498   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
12499                                             nullptr);
12500 }
12501 
12502 template <typename Derived>
12503 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12504     DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
12505     TypeSourceInfo **RecoveryTSI) {
12506   assert(E->getQualifierLoc());
12507   NestedNameSpecifierLoc QualifierLoc =
12508       getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
12509   if (!QualifierLoc)
12510     return ExprError();
12511   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12512 
12513   // TODO: If this is a conversion-function-id, verify that the
12514   // destination type name (if present) resolves the same way after
12515   // instantiation as it did in the local scope.
12516 
12517   DeclarationNameInfo NameInfo =
12518       getDerived().TransformDeclarationNameInfo(E->getNameInfo());
12519   if (!NameInfo.getName())
12520     return ExprError();
12521 
12522   if (!E->hasExplicitTemplateArgs()) {
12523     if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
12524         // Note: it is sufficient to compare the Name component of NameInfo:
12525         // if name has not changed, DNLoc has not changed either.
12526         NameInfo.getName() == E->getDeclName())
12527       return E;
12528 
12529     return getDerived().RebuildDependentScopeDeclRefExpr(
12530         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
12531         IsAddressOfOperand, RecoveryTSI);
12532   }
12533 
12534   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12535   if (getDerived().TransformTemplateArguments(
12536           E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
12537     return ExprError();
12538 
12539   return getDerived().RebuildDependentScopeDeclRefExpr(
12540       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
12541       RecoveryTSI);
12542 }
12543 
12544 template<typename Derived>
12545 ExprResult
12546 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
12547   // CXXConstructExprs other than for list-initialization and
12548   // CXXTemporaryObjectExpr are always implicit, so when we have
12549   // a 1-argument construction we just transform that argument.
12550   if (getDerived().AllowSkippingCXXConstructExpr() &&
12551       ((E->getNumArgs() == 1 ||
12552         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
12553        (!getDerived().DropCallArgument(E->getArg(0))) &&
12554        !E->isListInitialization()))
12555     return getDerived().TransformInitializer(E->getArg(0),
12556                                              /*DirectInit*/ false);
12557 
12558   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
12559 
12560   QualType T = getDerived().TransformType(E->getType());
12561   if (T.isNull())
12562     return ExprError();
12563 
12564   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12565       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12566   if (!Constructor)
12567     return ExprError();
12568 
12569   bool ArgumentChanged = false;
12570   SmallVector<Expr*, 8> Args;
12571   {
12572     EnterExpressionEvaluationContext Context(
12573         getSema(), EnterExpressionEvaluationContext::InitList,
12574         E->isListInitialization());
12575     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12576                                     &ArgumentChanged))
12577       return ExprError();
12578   }
12579 
12580   if (!getDerived().AlwaysRebuild() &&
12581       T == E->getType() &&
12582       Constructor == E->getConstructor() &&
12583       !ArgumentChanged) {
12584     // Mark the constructor as referenced.
12585     // FIXME: Instantiation-specific
12586     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12587     return E;
12588   }
12589 
12590   return getDerived().RebuildCXXConstructExpr(
12591       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
12592       E->hadMultipleCandidates(), E->isListInitialization(),
12593       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
12594       E->getConstructionKind(), E->getParenOrBraceRange());
12595 }
12596 
12597 template<typename Derived>
12598 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
12599     CXXInheritedCtorInitExpr *E) {
12600   QualType T = getDerived().TransformType(E->getType());
12601   if (T.isNull())
12602     return ExprError();
12603 
12604   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12605       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12606   if (!Constructor)
12607     return ExprError();
12608 
12609   if (!getDerived().AlwaysRebuild() &&
12610       T == E->getType() &&
12611       Constructor == E->getConstructor()) {
12612     // Mark the constructor as referenced.
12613     // FIXME: Instantiation-specific
12614     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12615     return E;
12616   }
12617 
12618   return getDerived().RebuildCXXInheritedCtorInitExpr(
12619       T, E->getLocation(), Constructor,
12620       E->constructsVBase(), E->inheritedFromVBase());
12621 }
12622 
12623 /// Transform a C++ temporary-binding expression.
12624 ///
12625 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
12626 /// transform the subexpression and return that.
12627 template<typename Derived>
12628 ExprResult
12629 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12630   return getDerived().TransformExpr(E->getSubExpr());
12631 }
12632 
12633 /// Transform a C++ expression that contains cleanups that should
12634 /// be run after the expression is evaluated.
12635 ///
12636 /// Since ExprWithCleanups nodes are implicitly generated, we
12637 /// just transform the subexpression and return that.
12638 template<typename Derived>
12639 ExprResult
12640 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
12641   return getDerived().TransformExpr(E->getSubExpr());
12642 }
12643 
12644 template<typename Derived>
12645 ExprResult
12646 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
12647                                                     CXXTemporaryObjectExpr *E) {
12648   TypeSourceInfo *T =
12649       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12650   if (!T)
12651     return ExprError();
12652 
12653   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12654       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12655   if (!Constructor)
12656     return ExprError();
12657 
12658   bool ArgumentChanged = false;
12659   SmallVector<Expr*, 8> Args;
12660   Args.reserve(E->getNumArgs());
12661   {
12662     EnterExpressionEvaluationContext Context(
12663         getSema(), EnterExpressionEvaluationContext::InitList,
12664         E->isListInitialization());
12665     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12666                        &ArgumentChanged))
12667       return ExprError();
12668   }
12669 
12670   if (!getDerived().AlwaysRebuild() &&
12671       T == E->getTypeSourceInfo() &&
12672       Constructor == E->getConstructor() &&
12673       !ArgumentChanged) {
12674     // FIXME: Instantiation-specific
12675     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12676     return SemaRef.MaybeBindToTemporary(E);
12677   }
12678 
12679   // FIXME: We should just pass E->isListInitialization(), but we're not
12680   // prepared to handle list-initialization without a child InitListExpr.
12681   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
12682   return getDerived().RebuildCXXTemporaryObjectExpr(
12683       T, LParenLoc, Args, E->getEndLoc(),
12684       /*ListInitialization=*/LParenLoc.isInvalid());
12685 }
12686 
12687 template<typename Derived>
12688 ExprResult
12689 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
12690   // Transform any init-capture expressions before entering the scope of the
12691   // lambda body, because they are not semantically within that scope.
12692   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
12693   struct TransformedInitCapture {
12694     // The location of the ... if the result is retaining a pack expansion.
12695     SourceLocation EllipsisLoc;
12696     // Zero or more expansions of the init-capture.
12697     SmallVector<InitCaptureInfoTy, 4> Expansions;
12698   };
12699   SmallVector<TransformedInitCapture, 4> InitCaptures;
12700   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
12701   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12702                                     CEnd = E->capture_end();
12703        C != CEnd; ++C) {
12704     if (!E->isInitCapture(C))
12705       continue;
12706 
12707     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
12708     VarDecl *OldVD = C->getCapturedVar();
12709 
12710     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
12711                                 Optional<unsigned> NumExpansions) {
12712       ExprResult NewExprInitResult = getDerived().TransformInitializer(
12713           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
12714 
12715       if (NewExprInitResult.isInvalid()) {
12716         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
12717         return;
12718       }
12719       Expr *NewExprInit = NewExprInitResult.get();
12720 
12721       QualType NewInitCaptureType =
12722           getSema().buildLambdaInitCaptureInitialization(
12723               C->getLocation(), OldVD->getType()->isReferenceType(),
12724               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
12725               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
12726               NewExprInit);
12727       Result.Expansions.push_back(
12728           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
12729     };
12730 
12731     // If this is an init-capture pack, consider expanding the pack now.
12732     if (OldVD->isParameterPack()) {
12733       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
12734                                              ->getTypeLoc()
12735                                              .castAs<PackExpansionTypeLoc>();
12736       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12737       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
12738 
12739       // Determine whether the set of unexpanded parameter packs can and should
12740       // be expanded.
12741       bool Expand = true;
12742       bool RetainExpansion = false;
12743       Optional<unsigned> OrigNumExpansions =
12744           ExpansionTL.getTypePtr()->getNumExpansions();
12745       Optional<unsigned> NumExpansions = OrigNumExpansions;
12746       if (getDerived().TryExpandParameterPacks(
12747               ExpansionTL.getEllipsisLoc(),
12748               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
12749               RetainExpansion, NumExpansions))
12750         return ExprError();
12751       if (Expand) {
12752         for (unsigned I = 0; I != *NumExpansions; ++I) {
12753           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12754           SubstInitCapture(SourceLocation(), None);
12755         }
12756       }
12757       if (!Expand || RetainExpansion) {
12758         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12759         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
12760         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
12761       }
12762     } else {
12763       SubstInitCapture(SourceLocation(), None);
12764     }
12765   }
12766 
12767   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
12768   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
12769 
12770   // Transform the template parameters, and add them to the current
12771   // instantiation scope. The null case is handled correctly.
12772   auto TPL = getDerived().TransformTemplateParameterList(
12773       E->getTemplateParameterList());
12774   LSI->GLTemplateParameterList = TPL;
12775 
12776   // Transform the type of the original lambda's call operator.
12777   // The transformation MUST be done in the CurrentInstantiationScope since
12778   // it introduces a mapping of the original to the newly created
12779   // transformed parameters.
12780   TypeSourceInfo *NewCallOpTSI = nullptr;
12781   {
12782     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
12783     FunctionProtoTypeLoc OldCallOpFPTL =
12784         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
12785 
12786     TypeLocBuilder NewCallOpTLBuilder;
12787     SmallVector<QualType, 4> ExceptionStorage;
12788     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
12789     QualType NewCallOpType = TransformFunctionProtoType(
12790         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
12791         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
12792           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
12793                                               ExceptionStorage, Changed);
12794         });
12795     if (NewCallOpType.isNull())
12796       return ExprError();
12797     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
12798                                                         NewCallOpType);
12799   }
12800 
12801   // Transform the trailing requires clause
12802   ExprResult NewTrailingRequiresClause;
12803   if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
12804     // FIXME: Concepts: Substitution into requires clause should only happen
12805     //                  when checking satisfaction.
12806     NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
12807 
12808   // Create the local class that will describe the lambda.
12809   // FIXME: KnownDependent below is wrong when substituting inside a templated
12810   // context that isn't a DeclContext (such as a variable template).
12811   CXXRecordDecl *OldClass = E->getLambdaClass();
12812   CXXRecordDecl *Class
12813     = getSema().createLambdaClosureType(E->getIntroducerRange(),
12814                                         NewCallOpTSI,
12815                                         /*KnownDependent=*/false,
12816                                         E->getCaptureDefault());
12817   getDerived().transformedLocalDecl(OldClass, {Class});
12818 
12819   Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling;
12820   if (getDerived().ReplacingOriginal())
12821     Mangling = std::make_tuple(OldClass->hasKnownLambdaInternalLinkage(),
12822                                OldClass->getLambdaManglingNumber(),
12823                                OldClass->getDeviceLambdaManglingNumber(),
12824                                OldClass->getLambdaContextDecl());
12825 
12826   // Build the call operator.
12827   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
12828       Class, E->getIntroducerRange(), NewCallOpTSI,
12829       E->getCallOperator()->getEndLoc(),
12830       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
12831       E->getCallOperator()->getConstexprKind(),
12832       NewTrailingRequiresClause.get());
12833 
12834   LSI->CallOperator = NewCallOperator;
12835 
12836   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
12837   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
12838 
12839   // Number the lambda for linkage purposes if necessary.
12840   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
12841 
12842   // Introduce the context of the call operator.
12843   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
12844                                  /*NewThisContext*/false);
12845 
12846   // Enter the scope of the lambda.
12847   getSema().buildLambdaScope(LSI, NewCallOperator,
12848                              E->getIntroducerRange(),
12849                              E->getCaptureDefault(),
12850                              E->getCaptureDefaultLoc(),
12851                              E->hasExplicitParameters(),
12852                              E->hasExplicitResultType(),
12853                              E->isMutable());
12854 
12855   bool Invalid = false;
12856 
12857   // Transform captures.
12858   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12859                                  CEnd = E->capture_end();
12860        C != CEnd; ++C) {
12861     // When we hit the first implicit capture, tell Sema that we've finished
12862     // the list of explicit captures.
12863     if (C->isImplicit())
12864       break;
12865 
12866     // Capturing 'this' is trivial.
12867     if (C->capturesThis()) {
12868       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
12869                                     /*BuildAndDiagnose*/ true, nullptr,
12870                                     C->getCaptureKind() == LCK_StarThis);
12871       continue;
12872     }
12873     // Captured expression will be recaptured during captured variables
12874     // rebuilding.
12875     if (C->capturesVLAType())
12876       continue;
12877 
12878     // Rebuild init-captures, including the implied field declaration.
12879     if (E->isInitCapture(C)) {
12880       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
12881 
12882       VarDecl *OldVD = C->getCapturedVar();
12883       llvm::SmallVector<Decl*, 4> NewVDs;
12884 
12885       for (InitCaptureInfoTy &Info : NewC.Expansions) {
12886         ExprResult Init = Info.first;
12887         QualType InitQualType = Info.second;
12888         if (Init.isInvalid() || InitQualType.isNull()) {
12889           Invalid = true;
12890           break;
12891         }
12892         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
12893             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
12894             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
12895         if (!NewVD) {
12896           Invalid = true;
12897           break;
12898         }
12899         NewVDs.push_back(NewVD);
12900         getSema().addInitCapture(LSI, NewVD);
12901       }
12902 
12903       if (Invalid)
12904         break;
12905 
12906       getDerived().transformedLocalDecl(OldVD, NewVDs);
12907       continue;
12908     }
12909 
12910     assert(C->capturesVariable() && "unexpected kind of lambda capture");
12911 
12912     // Determine the capture kind for Sema.
12913     Sema::TryCaptureKind Kind
12914       = C->isImplicit()? Sema::TryCapture_Implicit
12915                        : C->getCaptureKind() == LCK_ByCopy
12916                            ? Sema::TryCapture_ExplicitByVal
12917                            : Sema::TryCapture_ExplicitByRef;
12918     SourceLocation EllipsisLoc;
12919     if (C->isPackExpansion()) {
12920       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
12921       bool ShouldExpand = false;
12922       bool RetainExpansion = false;
12923       Optional<unsigned> NumExpansions;
12924       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
12925                                                C->getLocation(),
12926                                                Unexpanded,
12927                                                ShouldExpand, RetainExpansion,
12928                                                NumExpansions)) {
12929         Invalid = true;
12930         continue;
12931       }
12932 
12933       if (ShouldExpand) {
12934         // The transform has determined that we should perform an expansion;
12935         // transform and capture each of the arguments.
12936         // expansion of the pattern. Do so.
12937         VarDecl *Pack = C->getCapturedVar();
12938         for (unsigned I = 0; I != *NumExpansions; ++I) {
12939           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12940           VarDecl *CapturedVar
12941             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
12942                                                                Pack));
12943           if (!CapturedVar) {
12944             Invalid = true;
12945             continue;
12946           }
12947 
12948           // Capture the transformed variable.
12949           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
12950         }
12951 
12952         // FIXME: Retain a pack expansion if RetainExpansion is true.
12953 
12954         continue;
12955       }
12956 
12957       EllipsisLoc = C->getEllipsisLoc();
12958     }
12959 
12960     // Transform the captured variable.
12961     VarDecl *CapturedVar
12962       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
12963                                                          C->getCapturedVar()));
12964     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
12965       Invalid = true;
12966       continue;
12967     }
12968 
12969     // Capture the transformed variable.
12970     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
12971                                  EllipsisLoc);
12972   }
12973   getSema().finishLambdaExplicitCaptures(LSI);
12974 
12975   // FIXME: Sema's lambda-building mechanism expects us to push an expression
12976   // evaluation context even if we're not transforming the function body.
12977   getSema().PushExpressionEvaluationContext(
12978       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
12979 
12980   // Instantiate the body of the lambda expression.
12981   StmtResult Body =
12982       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
12983 
12984   // ActOnLambda* will pop the function scope for us.
12985   FuncScopeCleanup.disable();
12986 
12987   if (Body.isInvalid()) {
12988     SavedContext.pop();
12989     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
12990                                /*IsInstantiation=*/true);
12991     return ExprError();
12992   }
12993 
12994   // Copy the LSI before ActOnFinishFunctionBody removes it.
12995   // FIXME: This is dumb. Store the lambda information somewhere that outlives
12996   // the call operator.
12997   auto LSICopy = *LSI;
12998   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
12999                                     /*IsInstantiation*/ true);
13000   SavedContext.pop();
13001 
13002   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13003                                    &LSICopy);
13004 }
13005 
13006 template<typename Derived>
13007 StmtResult
13008 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13009   return TransformStmt(S);
13010 }
13011 
13012 template<typename Derived>
13013 StmtResult
13014 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13015   // Transform captures.
13016   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13017                                  CEnd = E->capture_end();
13018        C != CEnd; ++C) {
13019     // When we hit the first implicit capture, tell Sema that we've finished
13020     // the list of explicit captures.
13021     if (!C->isImplicit())
13022       continue;
13023 
13024     // Capturing 'this' is trivial.
13025     if (C->capturesThis()) {
13026       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13027                                     /*BuildAndDiagnose*/ true, nullptr,
13028                                     C->getCaptureKind() == LCK_StarThis);
13029       continue;
13030     }
13031     // Captured expression will be recaptured during captured variables
13032     // rebuilding.
13033     if (C->capturesVLAType())
13034       continue;
13035 
13036     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13037     assert(!E->isInitCapture(C) && "implicit init-capture?");
13038 
13039     // Transform the captured variable.
13040     VarDecl *CapturedVar = cast_or_null<VarDecl>(
13041         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13042     if (!CapturedVar || CapturedVar->isInvalidDecl())
13043       return StmtError();
13044 
13045     // Capture the transformed variable.
13046     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13047   }
13048 
13049   return S;
13050 }
13051 
13052 template<typename Derived>
13053 ExprResult
13054 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13055                                                   CXXUnresolvedConstructExpr *E) {
13056   TypeSourceInfo *T =
13057       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13058   if (!T)
13059     return ExprError();
13060 
13061   bool ArgumentChanged = false;
13062   SmallVector<Expr*, 8> Args;
13063   Args.reserve(E->getNumArgs());
13064   {
13065     EnterExpressionEvaluationContext Context(
13066         getSema(), EnterExpressionEvaluationContext::InitList,
13067         E->isListInitialization());
13068     if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13069                                     &ArgumentChanged))
13070       return ExprError();
13071   }
13072 
13073   if (!getDerived().AlwaysRebuild() &&
13074       T == E->getTypeSourceInfo() &&
13075       !ArgumentChanged)
13076     return E;
13077 
13078   // FIXME: we're faking the locations of the commas
13079   return getDerived().RebuildCXXUnresolvedConstructExpr(
13080       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13081 }
13082 
13083 template<typename Derived>
13084 ExprResult
13085 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13086                                              CXXDependentScopeMemberExpr *E) {
13087   // Transform the base of the expression.
13088   ExprResult Base((Expr*) nullptr);
13089   Expr *OldBase;
13090   QualType BaseType;
13091   QualType ObjectType;
13092   if (!E->isImplicitAccess()) {
13093     OldBase = E->getBase();
13094     Base = getDerived().TransformExpr(OldBase);
13095     if (Base.isInvalid())
13096       return ExprError();
13097 
13098     // Start the member reference and compute the object's type.
13099     ParsedType ObjectTy;
13100     bool MayBePseudoDestructor = false;
13101     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13102                                                 E->getOperatorLoc(),
13103                                       E->isArrow()? tok::arrow : tok::period,
13104                                                 ObjectTy,
13105                                                 MayBePseudoDestructor);
13106     if (Base.isInvalid())
13107       return ExprError();
13108 
13109     ObjectType = ObjectTy.get();
13110     BaseType = ((Expr*) Base.get())->getType();
13111   } else {
13112     OldBase = nullptr;
13113     BaseType = getDerived().TransformType(E->getBaseType());
13114     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13115   }
13116 
13117   // Transform the first part of the nested-name-specifier that qualifies
13118   // the member name.
13119   NamedDecl *FirstQualifierInScope
13120     = getDerived().TransformFirstQualifierInScope(
13121                                             E->getFirstQualifierFoundInScope(),
13122                                             E->getQualifierLoc().getBeginLoc());
13123 
13124   NestedNameSpecifierLoc QualifierLoc;
13125   if (E->getQualifier()) {
13126     QualifierLoc
13127       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13128                                                      ObjectType,
13129                                                      FirstQualifierInScope);
13130     if (!QualifierLoc)
13131       return ExprError();
13132   }
13133 
13134   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13135 
13136   // TODO: If this is a conversion-function-id, verify that the
13137   // destination type name (if present) resolves the same way after
13138   // instantiation as it did in the local scope.
13139 
13140   DeclarationNameInfo NameInfo
13141     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13142   if (!NameInfo.getName())
13143     return ExprError();
13144 
13145   if (!E->hasExplicitTemplateArgs()) {
13146     // This is a reference to a member without an explicitly-specified
13147     // template argument list. Optimize for this common case.
13148     if (!getDerived().AlwaysRebuild() &&
13149         Base.get() == OldBase &&
13150         BaseType == E->getBaseType() &&
13151         QualifierLoc == E->getQualifierLoc() &&
13152         NameInfo.getName() == E->getMember() &&
13153         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13154       return E;
13155 
13156     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13157                                                        BaseType,
13158                                                        E->isArrow(),
13159                                                        E->getOperatorLoc(),
13160                                                        QualifierLoc,
13161                                                        TemplateKWLoc,
13162                                                        FirstQualifierInScope,
13163                                                        NameInfo,
13164                                                        /*TemplateArgs*/nullptr);
13165   }
13166 
13167   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13168   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13169                                               E->getNumTemplateArgs(),
13170                                               TransArgs))
13171     return ExprError();
13172 
13173   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13174                                                      BaseType,
13175                                                      E->isArrow(),
13176                                                      E->getOperatorLoc(),
13177                                                      QualifierLoc,
13178                                                      TemplateKWLoc,
13179                                                      FirstQualifierInScope,
13180                                                      NameInfo,
13181                                                      &TransArgs);
13182 }
13183 
13184 template <typename Derived>
13185 ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13186     UnresolvedMemberExpr *Old) {
13187   // Transform the base of the expression.
13188   ExprResult Base((Expr *)nullptr);
13189   QualType BaseType;
13190   if (!Old->isImplicitAccess()) {
13191     Base = getDerived().TransformExpr(Old->getBase());
13192     if (Base.isInvalid())
13193       return ExprError();
13194     Base =
13195         getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13196     if (Base.isInvalid())
13197       return ExprError();
13198     BaseType = Base.get()->getType();
13199   } else {
13200     BaseType = getDerived().TransformType(Old->getBaseType());
13201   }
13202 
13203   NestedNameSpecifierLoc QualifierLoc;
13204   if (Old->getQualifierLoc()) {
13205     QualifierLoc =
13206         getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13207     if (!QualifierLoc)
13208       return ExprError();
13209   }
13210 
13211   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13212 
13213   LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13214 
13215   // Transform the declaration set.
13216   if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13217     return ExprError();
13218 
13219   // Determine the naming class.
13220   if (Old->getNamingClass()) {
13221     CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13222         getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13223     if (!NamingClass)
13224       return ExprError();
13225 
13226     R.setNamingClass(NamingClass);
13227   }
13228 
13229   TemplateArgumentListInfo TransArgs;
13230   if (Old->hasExplicitTemplateArgs()) {
13231     TransArgs.setLAngleLoc(Old->getLAngleLoc());
13232     TransArgs.setRAngleLoc(Old->getRAngleLoc());
13233     if (getDerived().TransformTemplateArguments(
13234             Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13235       return ExprError();
13236   }
13237 
13238   // FIXME: to do this check properly, we will need to preserve the
13239   // first-qualifier-in-scope here, just in case we had a dependent
13240   // base (and therefore couldn't do the check) and a
13241   // nested-name-qualifier (and therefore could do the lookup).
13242   NamedDecl *FirstQualifierInScope = nullptr;
13243 
13244   return getDerived().RebuildUnresolvedMemberExpr(
13245       Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13246       TemplateKWLoc, FirstQualifierInScope, R,
13247       (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13248 }
13249 
13250 template<typename Derived>
13251 ExprResult
13252 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13253   EnterExpressionEvaluationContext Unevaluated(
13254       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13255   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13256   if (SubExpr.isInvalid())
13257     return ExprError();
13258 
13259   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13260     return E;
13261 
13262   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13263 }
13264 
13265 template<typename Derived>
13266 ExprResult
13267 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13268   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13269   if (Pattern.isInvalid())
13270     return ExprError();
13271 
13272   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13273     return E;
13274 
13275   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13276                                            E->getNumExpansions());
13277 }
13278 
13279 template<typename Derived>
13280 ExprResult
13281 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13282   // If E is not value-dependent, then nothing will change when we transform it.
13283   // Note: This is an instantiation-centric view.
13284   if (!E->isValueDependent())
13285     return E;
13286 
13287   EnterExpressionEvaluationContext Unevaluated(
13288       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13289 
13290   ArrayRef<TemplateArgument> PackArgs;
13291   TemplateArgument ArgStorage;
13292 
13293   // Find the argument list to transform.
13294   if (E->isPartiallySubstituted()) {
13295     PackArgs = E->getPartialArguments();
13296   } else if (E->isValueDependent()) {
13297     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13298     bool ShouldExpand = false;
13299     bool RetainExpansion = false;
13300     Optional<unsigned> NumExpansions;
13301     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13302                                              Unexpanded,
13303                                              ShouldExpand, RetainExpansion,
13304                                              NumExpansions))
13305       return ExprError();
13306 
13307     // If we need to expand the pack, build a template argument from it and
13308     // expand that.
13309     if (ShouldExpand) {
13310       auto *Pack = E->getPack();
13311       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13312         ArgStorage = getSema().Context.getPackExpansionType(
13313             getSema().Context.getTypeDeclType(TTPD), None);
13314       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13315         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
13316       } else {
13317         auto *VD = cast<ValueDecl>(Pack);
13318         ExprResult DRE = getSema().BuildDeclRefExpr(
13319             VD, VD->getType().getNonLValueExprType(getSema().Context),
13320             VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13321             E->getPackLoc());
13322         if (DRE.isInvalid())
13323           return ExprError();
13324         ArgStorage = new (getSema().Context) PackExpansionExpr(
13325             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
13326       }
13327       PackArgs = ArgStorage;
13328     }
13329   }
13330 
13331   // If we're not expanding the pack, just transform the decl.
13332   if (!PackArgs.size()) {
13333     auto *Pack = cast_or_null<NamedDecl>(
13334         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13335     if (!Pack)
13336       return ExprError();
13337     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
13338                                               E->getPackLoc(),
13339                                               E->getRParenLoc(), None, None);
13340   }
13341 
13342   // Try to compute the result without performing a partial substitution.
13343   Optional<unsigned> Result = 0;
13344   for (const TemplateArgument &Arg : PackArgs) {
13345     if (!Arg.isPackExpansion()) {
13346       Result = *Result + 1;
13347       continue;
13348     }
13349 
13350     TemplateArgumentLoc ArgLoc;
13351     InventTemplateArgumentLoc(Arg, ArgLoc);
13352 
13353     // Find the pattern of the pack expansion.
13354     SourceLocation Ellipsis;
13355     Optional<unsigned> OrigNumExpansions;
13356     TemplateArgumentLoc Pattern =
13357         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13358                                                           OrigNumExpansions);
13359 
13360     // Substitute under the pack expansion. Do not expand the pack (yet).
13361     TemplateArgumentLoc OutPattern;
13362     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13363     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13364                                                /*Uneval*/ true))
13365       return true;
13366 
13367     // See if we can determine the number of arguments from the result.
13368     Optional<unsigned> NumExpansions =
13369         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13370     if (!NumExpansions) {
13371       // No: we must be in an alias template expansion, and we're going to need
13372       // to actually expand the packs.
13373       Result = None;
13374       break;
13375     }
13376 
13377     Result = *Result + *NumExpansions;
13378   }
13379 
13380   // Common case: we could determine the number of expansions without
13381   // substituting.
13382   if (Result)
13383     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13384                                               E->getPackLoc(),
13385                                               E->getRParenLoc(), *Result, None);
13386 
13387   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13388                                                E->getPackLoc());
13389   {
13390     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13391     typedef TemplateArgumentLocInventIterator<
13392         Derived, const TemplateArgument*> PackLocIterator;
13393     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13394                                    PackLocIterator(*this, PackArgs.end()),
13395                                    TransformedPackArgs, /*Uneval*/true))
13396       return ExprError();
13397   }
13398 
13399   // Check whether we managed to fully-expand the pack.
13400   // FIXME: Is it possible for us to do so and not hit the early exit path?
13401   SmallVector<TemplateArgument, 8> Args;
13402   bool PartialSubstitution = false;
13403   for (auto &Loc : TransformedPackArgs.arguments()) {
13404     Args.push_back(Loc.getArgument());
13405     if (Loc.getArgument().isPackExpansion())
13406       PartialSubstitution = true;
13407   }
13408 
13409   if (PartialSubstitution)
13410     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13411                                               E->getPackLoc(),
13412                                               E->getRParenLoc(), None, Args);
13413 
13414   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13415                                             E->getPackLoc(), E->getRParenLoc(),
13416                                             Args.size(), None);
13417 }
13418 
13419 template<typename Derived>
13420 ExprResult
13421 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13422                                           SubstNonTypeTemplateParmPackExpr *E) {
13423   // Default behavior is to do nothing with this transformation.
13424   return E;
13425 }
13426 
13427 template<typename Derived>
13428 ExprResult
13429 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13430                                           SubstNonTypeTemplateParmExpr *E) {
13431   // Default behavior is to do nothing with this transformation.
13432   return E;
13433 }
13434 
13435 template<typename Derived>
13436 ExprResult
13437 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13438   // Default behavior is to do nothing with this transformation.
13439   return E;
13440 }
13441 
13442 template<typename Derived>
13443 ExprResult
13444 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13445                                                   MaterializeTemporaryExpr *E) {
13446   return getDerived().TransformExpr(E->getSubExpr());
13447 }
13448 
13449 template<typename Derived>
13450 ExprResult
13451 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13452   UnresolvedLookupExpr *Callee = nullptr;
13453   if (Expr *OldCallee = E->getCallee()) {
13454     ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13455     if (CalleeResult.isInvalid())
13456       return ExprError();
13457     Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13458   }
13459 
13460   Expr *Pattern = E->getPattern();
13461 
13462   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13463   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13464   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13465 
13466   // Determine whether the set of unexpanded parameter packs can and should
13467   // be expanded.
13468   bool Expand = true;
13469   bool RetainExpansion = false;
13470   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13471                      NumExpansions = OrigNumExpansions;
13472   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
13473                                            Pattern->getSourceRange(),
13474                                            Unexpanded,
13475                                            Expand, RetainExpansion,
13476                                            NumExpansions))
13477     return true;
13478 
13479   if (!Expand) {
13480     // Do not expand any packs here, just transform and rebuild a fold
13481     // expression.
13482     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13483 
13484     ExprResult LHS =
13485         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
13486     if (LHS.isInvalid())
13487       return true;
13488 
13489     ExprResult RHS =
13490         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
13491     if (RHS.isInvalid())
13492       return true;
13493 
13494     if (!getDerived().AlwaysRebuild() &&
13495         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
13496       return E;
13497 
13498     return getDerived().RebuildCXXFoldExpr(
13499         Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
13500         E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
13501   }
13502 
13503   // Formally a fold expression expands to nested parenthesized expressions.
13504   // Enforce this limit to avoid creating trees so deep we can't safely traverse
13505   // them.
13506   if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
13507     SemaRef.Diag(E->getEllipsisLoc(),
13508                  clang::diag::err_fold_expression_limit_exceeded)
13509         << *NumExpansions << SemaRef.getLangOpts().BracketDepth
13510         << E->getSourceRange();
13511     SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
13512     return ExprError();
13513   }
13514 
13515   // The transform has determined that we should perform an elementwise
13516   // expansion of the pattern. Do so.
13517   ExprResult Result = getDerived().TransformExpr(E->getInit());
13518   if (Result.isInvalid())
13519     return true;
13520   bool LeftFold = E->isLeftFold();
13521 
13522   // If we're retaining an expansion for a right fold, it is the innermost
13523   // component and takes the init (if any).
13524   if (!LeftFold && RetainExpansion) {
13525     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13526 
13527     ExprResult Out = getDerived().TransformExpr(Pattern);
13528     if (Out.isInvalid())
13529       return true;
13530 
13531     Result = getDerived().RebuildCXXFoldExpr(
13532         Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
13533         E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
13534     if (Result.isInvalid())
13535       return true;
13536   }
13537 
13538   for (unsigned I = 0; I != *NumExpansions; ++I) {
13539     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
13540         getSema(), LeftFold ? I : *NumExpansions - I - 1);
13541     ExprResult Out = getDerived().TransformExpr(Pattern);
13542     if (Out.isInvalid())
13543       return true;
13544 
13545     if (Out.get()->containsUnexpandedParameterPack()) {
13546       // We still have a pack; retain a pack expansion for this slice.
13547       Result = getDerived().RebuildCXXFoldExpr(
13548           Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
13549           E->getOperator(), E->getEllipsisLoc(),
13550           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
13551           OrigNumExpansions);
13552     } else if (Result.isUsable()) {
13553       // We've got down to a single element; build a binary operator.
13554       Expr *LHS = LeftFold ? Result.get() : Out.get();
13555       Expr *RHS = LeftFold ? Out.get() : Result.get();
13556       if (Callee)
13557         Result = getDerived().RebuildCXXOperatorCallExpr(
13558             BinaryOperator::getOverloadedOperator(E->getOperator()),
13559             E->getEllipsisLoc(), Callee, LHS, RHS);
13560       else
13561         Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
13562                                                     E->getOperator(), LHS, RHS);
13563     } else
13564       Result = Out;
13565 
13566     if (Result.isInvalid())
13567       return true;
13568   }
13569 
13570   // If we're retaining an expansion for a left fold, it is the outermost
13571   // component and takes the complete expansion so far as its init (if any).
13572   if (LeftFold && RetainExpansion) {
13573     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13574 
13575     ExprResult Out = getDerived().TransformExpr(Pattern);
13576     if (Out.isInvalid())
13577       return true;
13578 
13579     Result = getDerived().RebuildCXXFoldExpr(
13580         Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
13581         E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
13582     if (Result.isInvalid())
13583       return true;
13584   }
13585 
13586   // If we had no init and an empty pack, and we're not retaining an expansion,
13587   // then produce a fallback value or error.
13588   if (Result.isUnset())
13589     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
13590                                                 E->getOperator());
13591 
13592   return Result;
13593 }
13594 
13595 template<typename Derived>
13596 ExprResult
13597 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
13598     CXXStdInitializerListExpr *E) {
13599   return getDerived().TransformExpr(E->getSubExpr());
13600 }
13601 
13602 template<typename Derived>
13603 ExprResult
13604 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
13605   return SemaRef.MaybeBindToTemporary(E);
13606 }
13607 
13608 template<typename Derived>
13609 ExprResult
13610 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
13611   return E;
13612 }
13613 
13614 template<typename Derived>
13615 ExprResult
13616 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
13617   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
13618   if (SubExpr.isInvalid())
13619     return ExprError();
13620 
13621   if (!getDerived().AlwaysRebuild() &&
13622       SubExpr.get() == E->getSubExpr())
13623     return E;
13624 
13625   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
13626 }
13627 
13628 template<typename Derived>
13629 ExprResult
13630 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
13631   // Transform each of the elements.
13632   SmallVector<Expr *, 8> Elements;
13633   bool ArgChanged = false;
13634   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
13635                                   /*IsCall=*/false, Elements, &ArgChanged))
13636     return ExprError();
13637 
13638   if (!getDerived().AlwaysRebuild() && !ArgChanged)
13639     return SemaRef.MaybeBindToTemporary(E);
13640 
13641   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
13642                                               Elements.data(),
13643                                               Elements.size());
13644 }
13645 
13646 template<typename Derived>
13647 ExprResult
13648 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
13649                                                     ObjCDictionaryLiteral *E) {
13650   // Transform each of the elements.
13651   SmallVector<ObjCDictionaryElement, 8> Elements;
13652   bool ArgChanged = false;
13653   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
13654     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
13655 
13656     if (OrigElement.isPackExpansion()) {
13657       // This key/value element is a pack expansion.
13658       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13659       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
13660       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
13661       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13662 
13663       // Determine whether the set of unexpanded parameter packs can
13664       // and should be expanded.
13665       bool Expand = true;
13666       bool RetainExpansion = false;
13667       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
13668       Optional<unsigned> NumExpansions = OrigNumExpansions;
13669       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
13670                                OrigElement.Value->getEndLoc());
13671       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
13672                                                PatternRange, Unexpanded, Expand,
13673                                                RetainExpansion, NumExpansions))
13674         return ExprError();
13675 
13676       if (!Expand) {
13677         // The transform has determined that we should perform a simple
13678         // transformation on the pack expansion, producing another pack
13679         // expansion.
13680         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13681         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13682         if (Key.isInvalid())
13683           return ExprError();
13684 
13685         if (Key.get() != OrigElement.Key)
13686           ArgChanged = true;
13687 
13688         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13689         if (Value.isInvalid())
13690           return ExprError();
13691 
13692         if (Value.get() != OrigElement.Value)
13693           ArgChanged = true;
13694 
13695         ObjCDictionaryElement Expansion = {
13696           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
13697         };
13698         Elements.push_back(Expansion);
13699         continue;
13700       }
13701 
13702       // Record right away that the argument was changed.  This needs
13703       // to happen even if the array expands to nothing.
13704       ArgChanged = true;
13705 
13706       // The transform has determined that we should perform an elementwise
13707       // expansion of the pattern. Do so.
13708       for (unsigned I = 0; I != *NumExpansions; ++I) {
13709         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13710         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13711         if (Key.isInvalid())
13712           return ExprError();
13713 
13714         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13715         if (Value.isInvalid())
13716           return ExprError();
13717 
13718         ObjCDictionaryElement Element = {
13719           Key.get(), Value.get(), SourceLocation(), NumExpansions
13720         };
13721 
13722         // If any unexpanded parameter packs remain, we still have a
13723         // pack expansion.
13724         // FIXME: Can this really happen?
13725         if (Key.get()->containsUnexpandedParameterPack() ||
13726             Value.get()->containsUnexpandedParameterPack())
13727           Element.EllipsisLoc = OrigElement.EllipsisLoc;
13728 
13729         Elements.push_back(Element);
13730       }
13731 
13732       // FIXME: Retain a pack expansion if RetainExpansion is true.
13733 
13734       // We've finished with this pack expansion.
13735       continue;
13736     }
13737 
13738     // Transform and check key.
13739     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13740     if (Key.isInvalid())
13741       return ExprError();
13742 
13743     if (Key.get() != OrigElement.Key)
13744       ArgChanged = true;
13745 
13746     // Transform and check value.
13747     ExprResult Value
13748       = getDerived().TransformExpr(OrigElement.Value);
13749     if (Value.isInvalid())
13750       return ExprError();
13751 
13752     if (Value.get() != OrigElement.Value)
13753       ArgChanged = true;
13754 
13755     ObjCDictionaryElement Element = {
13756       Key.get(), Value.get(), SourceLocation(), None
13757     };
13758     Elements.push_back(Element);
13759   }
13760 
13761   if (!getDerived().AlwaysRebuild() && !ArgChanged)
13762     return SemaRef.MaybeBindToTemporary(E);
13763 
13764   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
13765                                                    Elements);
13766 }
13767 
13768 template<typename Derived>
13769 ExprResult
13770 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
13771   TypeSourceInfo *EncodedTypeInfo
13772     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
13773   if (!EncodedTypeInfo)
13774     return ExprError();
13775 
13776   if (!getDerived().AlwaysRebuild() &&
13777       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
13778     return E;
13779 
13780   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
13781                                             EncodedTypeInfo,
13782                                             E->getRParenLoc());
13783 }
13784 
13785 template<typename Derived>
13786 ExprResult TreeTransform<Derived>::
13787 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
13788   // This is a kind of implicit conversion, and it needs to get dropped
13789   // and recomputed for the same general reasons that ImplicitCastExprs
13790   // do, as well a more specific one: this expression is only valid when
13791   // it appears *immediately* as an argument expression.
13792   return getDerived().TransformExpr(E->getSubExpr());
13793 }
13794 
13795 template<typename Derived>
13796 ExprResult TreeTransform<Derived>::
13797 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
13798   TypeSourceInfo *TSInfo
13799     = getDerived().TransformType(E->getTypeInfoAsWritten());
13800   if (!TSInfo)
13801     return ExprError();
13802 
13803   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
13804   if (Result.isInvalid())
13805     return ExprError();
13806 
13807   if (!getDerived().AlwaysRebuild() &&
13808       TSInfo == E->getTypeInfoAsWritten() &&
13809       Result.get() == E->getSubExpr())
13810     return E;
13811 
13812   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
13813                                       E->getBridgeKeywordLoc(), TSInfo,
13814                                       Result.get());
13815 }
13816 
13817 template <typename Derived>
13818 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
13819     ObjCAvailabilityCheckExpr *E) {
13820   return E;
13821 }
13822 
13823 template<typename Derived>
13824 ExprResult
13825 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
13826   // Transform arguments.
13827   bool ArgChanged = false;
13828   SmallVector<Expr*, 8> Args;
13829   Args.reserve(E->getNumArgs());
13830   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
13831                                   &ArgChanged))
13832     return ExprError();
13833 
13834   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
13835     // Class message: transform the receiver type.
13836     TypeSourceInfo *ReceiverTypeInfo
13837       = getDerived().TransformType(E->getClassReceiverTypeInfo());
13838     if (!ReceiverTypeInfo)
13839       return ExprError();
13840 
13841     // If nothing changed, just retain the existing message send.
13842     if (!getDerived().AlwaysRebuild() &&
13843         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
13844       return SemaRef.MaybeBindToTemporary(E);
13845 
13846     // Build a new class message send.
13847     SmallVector<SourceLocation, 16> SelLocs;
13848     E->getSelectorLocs(SelLocs);
13849     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
13850                                                E->getSelector(),
13851                                                SelLocs,
13852                                                E->getMethodDecl(),
13853                                                E->getLeftLoc(),
13854                                                Args,
13855                                                E->getRightLoc());
13856   }
13857   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
13858            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13859     if (!E->getMethodDecl())
13860       return ExprError();
13861 
13862     // Build a new class message send to 'super'.
13863     SmallVector<SourceLocation, 16> SelLocs;
13864     E->getSelectorLocs(SelLocs);
13865     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
13866                                                E->getSelector(),
13867                                                SelLocs,
13868                                                E->getReceiverType(),
13869                                                E->getMethodDecl(),
13870                                                E->getLeftLoc(),
13871                                                Args,
13872                                                E->getRightLoc());
13873   }
13874 
13875   // Instance message: transform the receiver
13876   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
13877          "Only class and instance messages may be instantiated");
13878   ExprResult Receiver
13879     = getDerived().TransformExpr(E->getInstanceReceiver());
13880   if (Receiver.isInvalid())
13881     return ExprError();
13882 
13883   // If nothing changed, just retain the existing message send.
13884   if (!getDerived().AlwaysRebuild() &&
13885       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
13886     return SemaRef.MaybeBindToTemporary(E);
13887 
13888   // Build a new instance message send.
13889   SmallVector<SourceLocation, 16> SelLocs;
13890   E->getSelectorLocs(SelLocs);
13891   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
13892                                              E->getSelector(),
13893                                              SelLocs,
13894                                              E->getMethodDecl(),
13895                                              E->getLeftLoc(),
13896                                              Args,
13897                                              E->getRightLoc());
13898 }
13899 
13900 template<typename Derived>
13901 ExprResult
13902 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
13903   return E;
13904 }
13905 
13906 template<typename Derived>
13907 ExprResult
13908 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
13909   return E;
13910 }
13911 
13912 template<typename Derived>
13913 ExprResult
13914 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
13915   // Transform the base expression.
13916   ExprResult Base = getDerived().TransformExpr(E->getBase());
13917   if (Base.isInvalid())
13918     return ExprError();
13919 
13920   // We don't need to transform the ivar; it will never change.
13921 
13922   // If nothing changed, just retain the existing expression.
13923   if (!getDerived().AlwaysRebuild() &&
13924       Base.get() == E->getBase())
13925     return E;
13926 
13927   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
13928                                              E->getLocation(),
13929                                              E->isArrow(), E->isFreeIvar());
13930 }
13931 
13932 template<typename Derived>
13933 ExprResult
13934 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
13935   // 'super' and types never change. Property never changes. Just
13936   // retain the existing expression.
13937   if (!E->isObjectReceiver())
13938     return E;
13939 
13940   // Transform the base expression.
13941   ExprResult Base = getDerived().TransformExpr(E->getBase());
13942   if (Base.isInvalid())
13943     return ExprError();
13944 
13945   // We don't need to transform the property; it will never change.
13946 
13947   // If nothing changed, just retain the existing expression.
13948   if (!getDerived().AlwaysRebuild() &&
13949       Base.get() == E->getBase())
13950     return E;
13951 
13952   if (E->isExplicitProperty())
13953     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
13954                                                    E->getExplicitProperty(),
13955                                                    E->getLocation());
13956 
13957   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
13958                                                  SemaRef.Context.PseudoObjectTy,
13959                                                  E->getImplicitPropertyGetter(),
13960                                                  E->getImplicitPropertySetter(),
13961                                                  E->getLocation());
13962 }
13963 
13964 template<typename Derived>
13965 ExprResult
13966 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
13967   // Transform the base expression.
13968   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
13969   if (Base.isInvalid())
13970     return ExprError();
13971 
13972   // Transform the key expression.
13973   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
13974   if (Key.isInvalid())
13975     return ExprError();
13976 
13977   // If nothing changed, just retain the existing expression.
13978   if (!getDerived().AlwaysRebuild() &&
13979       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
13980     return E;
13981 
13982   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
13983                                                   Base.get(), Key.get(),
13984                                                   E->getAtIndexMethodDecl(),
13985                                                   E->setAtIndexMethodDecl());
13986 }
13987 
13988 template<typename Derived>
13989 ExprResult
13990 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
13991   // Transform the base expression.
13992   ExprResult Base = getDerived().TransformExpr(E->getBase());
13993   if (Base.isInvalid())
13994     return ExprError();
13995 
13996   // If nothing changed, just retain the existing expression.
13997   if (!getDerived().AlwaysRebuild() &&
13998       Base.get() == E->getBase())
13999     return E;
14000 
14001   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14002                                          E->getOpLoc(),
14003                                          E->isArrow());
14004 }
14005 
14006 template<typename Derived>
14007 ExprResult
14008 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14009   bool ArgumentChanged = false;
14010   SmallVector<Expr*, 8> SubExprs;
14011   SubExprs.reserve(E->getNumSubExprs());
14012   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14013                                   SubExprs, &ArgumentChanged))
14014     return ExprError();
14015 
14016   if (!getDerived().AlwaysRebuild() &&
14017       !ArgumentChanged)
14018     return E;
14019 
14020   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14021                                                SubExprs,
14022                                                E->getRParenLoc());
14023 }
14024 
14025 template<typename Derived>
14026 ExprResult
14027 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14028   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14029   if (SrcExpr.isInvalid())
14030     return ExprError();
14031 
14032   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14033   if (!Type)
14034     return ExprError();
14035 
14036   if (!getDerived().AlwaysRebuild() &&
14037       Type == E->getTypeSourceInfo() &&
14038       SrcExpr.get() == E->getSrcExpr())
14039     return E;
14040 
14041   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14042                                                SrcExpr.get(), Type,
14043                                                E->getRParenLoc());
14044 }
14045 
14046 template<typename Derived>
14047 ExprResult
14048 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14049   BlockDecl *oldBlock = E->getBlockDecl();
14050 
14051   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14052   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14053 
14054   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14055   blockScope->TheDecl->setBlockMissingReturnType(
14056                          oldBlock->blockMissingReturnType());
14057 
14058   SmallVector<ParmVarDecl*, 4> params;
14059   SmallVector<QualType, 4> paramTypes;
14060 
14061   const FunctionProtoType *exprFunctionType = E->getFunctionType();
14062 
14063   // Parameter substitution.
14064   Sema::ExtParameterInfoBuilder extParamInfos;
14065   if (getDerived().TransformFunctionTypeParams(
14066           E->getCaretLocation(), oldBlock->parameters(), nullptr,
14067           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14068           extParamInfos)) {
14069     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14070     return ExprError();
14071   }
14072 
14073   QualType exprResultType =
14074       getDerived().TransformType(exprFunctionType->getReturnType());
14075 
14076   auto epi = exprFunctionType->getExtProtoInfo();
14077   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14078 
14079   QualType functionType =
14080     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14081   blockScope->FunctionType = functionType;
14082 
14083   // Set the parameters on the block decl.
14084   if (!params.empty())
14085     blockScope->TheDecl->setParams(params);
14086 
14087   if (!oldBlock->blockMissingReturnType()) {
14088     blockScope->HasImplicitReturnType = false;
14089     blockScope->ReturnType = exprResultType;
14090   }
14091 
14092   // Transform the body
14093   StmtResult body = getDerived().TransformStmt(E->getBody());
14094   if (body.isInvalid()) {
14095     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14096     return ExprError();
14097   }
14098 
14099 #ifndef NDEBUG
14100   // In builds with assertions, make sure that we captured everything we
14101   // captured before.
14102   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14103     for (const auto &I : oldBlock->captures()) {
14104       VarDecl *oldCapture = I.getVariable();
14105 
14106       // Ignore parameter packs.
14107       if (oldCapture->isParameterPack())
14108         continue;
14109 
14110       VarDecl *newCapture =
14111         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14112                                                  oldCapture));
14113       assert(blockScope->CaptureMap.count(newCapture));
14114     }
14115     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
14116   }
14117 #endif
14118 
14119   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14120                                     /*Scope=*/nullptr);
14121 }
14122 
14123 template<typename Derived>
14124 ExprResult
14125 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14126   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14127   if (SrcExpr.isInvalid())
14128     return ExprError();
14129 
14130   QualType Type = getDerived().TransformType(E->getType());
14131 
14132   return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14133                                  E->getRParenLoc());
14134 }
14135 
14136 template<typename Derived>
14137 ExprResult
14138 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14139   bool ArgumentChanged = false;
14140   SmallVector<Expr*, 8> SubExprs;
14141   SubExprs.reserve(E->getNumSubExprs());
14142   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14143                                   SubExprs, &ArgumentChanged))
14144     return ExprError();
14145 
14146   if (!getDerived().AlwaysRebuild() &&
14147       !ArgumentChanged)
14148     return E;
14149 
14150   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14151                                         E->getOp(), E->getRParenLoc());
14152 }
14153 
14154 //===----------------------------------------------------------------------===//
14155 // Type reconstruction
14156 //===----------------------------------------------------------------------===//
14157 
14158 template<typename Derived>
14159 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14160                                                     SourceLocation Star) {
14161   return SemaRef.BuildPointerType(PointeeType, Star,
14162                                   getDerived().getBaseEntity());
14163 }
14164 
14165 template<typename Derived>
14166 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14167                                                          SourceLocation Star) {
14168   return SemaRef.BuildBlockPointerType(PointeeType, Star,
14169                                        getDerived().getBaseEntity());
14170 }
14171 
14172 template<typename Derived>
14173 QualType
14174 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14175                                              bool WrittenAsLValue,
14176                                              SourceLocation Sigil) {
14177   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14178                                     Sigil, getDerived().getBaseEntity());
14179 }
14180 
14181 template<typename Derived>
14182 QualType
14183 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14184                                                  QualType ClassType,
14185                                                  SourceLocation Sigil) {
14186   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14187                                         getDerived().getBaseEntity());
14188 }
14189 
14190 template<typename Derived>
14191 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14192            const ObjCTypeParamDecl *Decl,
14193            SourceLocation ProtocolLAngleLoc,
14194            ArrayRef<ObjCProtocolDecl *> Protocols,
14195            ArrayRef<SourceLocation> ProtocolLocs,
14196            SourceLocation ProtocolRAngleLoc) {
14197   return SemaRef.BuildObjCTypeParamType(Decl,
14198                                         ProtocolLAngleLoc, Protocols,
14199                                         ProtocolLocs, ProtocolRAngleLoc,
14200                                         /*FailOnError=*/true);
14201 }
14202 
14203 template<typename Derived>
14204 QualType TreeTransform<Derived>::RebuildObjCObjectType(
14205            QualType BaseType,
14206            SourceLocation Loc,
14207            SourceLocation TypeArgsLAngleLoc,
14208            ArrayRef<TypeSourceInfo *> TypeArgs,
14209            SourceLocation TypeArgsRAngleLoc,
14210            SourceLocation ProtocolLAngleLoc,
14211            ArrayRef<ObjCProtocolDecl *> Protocols,
14212            ArrayRef<SourceLocation> ProtocolLocs,
14213            SourceLocation ProtocolRAngleLoc) {
14214   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
14215                                      TypeArgs, TypeArgsRAngleLoc,
14216                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
14217                                      ProtocolRAngleLoc,
14218                                      /*FailOnError=*/true);
14219 }
14220 
14221 template<typename Derived>
14222 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14223            QualType PointeeType,
14224            SourceLocation Star) {
14225   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14226 }
14227 
14228 template<typename Derived>
14229 QualType
14230 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14231                                          ArrayType::ArraySizeModifier SizeMod,
14232                                          const llvm::APInt *Size,
14233                                          Expr *SizeExpr,
14234                                          unsigned IndexTypeQuals,
14235                                          SourceRange BracketsRange) {
14236   if (SizeExpr || !Size)
14237     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14238                                   IndexTypeQuals, BracketsRange,
14239                                   getDerived().getBaseEntity());
14240 
14241   QualType Types[] = {
14242     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14243     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14244     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14245   };
14246   const unsigned NumTypes = llvm::array_lengthof(Types);
14247   QualType SizeType;
14248   for (unsigned I = 0; I != NumTypes; ++I)
14249     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
14250       SizeType = Types[I];
14251       break;
14252     }
14253 
14254   // Note that we can return a VariableArrayType here in the case where
14255   // the element type was a dependent VariableArrayType.
14256   IntegerLiteral *ArraySize
14257       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14258                                /*FIXME*/BracketsRange.getBegin());
14259   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14260                                 IndexTypeQuals, BracketsRange,
14261                                 getDerived().getBaseEntity());
14262 }
14263 
14264 template<typename Derived>
14265 QualType
14266 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14267                                                  ArrayType::ArraySizeModifier SizeMod,
14268                                                  const llvm::APInt &Size,
14269                                                  Expr *SizeExpr,
14270                                                  unsigned IndexTypeQuals,
14271                                                  SourceRange BracketsRange) {
14272   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14273                                         IndexTypeQuals, BracketsRange);
14274 }
14275 
14276 template<typename Derived>
14277 QualType
14278 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14279                                           ArrayType::ArraySizeModifier SizeMod,
14280                                                  unsigned IndexTypeQuals,
14281                                                    SourceRange BracketsRange) {
14282   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14283                                        IndexTypeQuals, BracketsRange);
14284 }
14285 
14286 template<typename Derived>
14287 QualType
14288 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14289                                           ArrayType::ArraySizeModifier SizeMod,
14290                                                  Expr *SizeExpr,
14291                                                  unsigned IndexTypeQuals,
14292                                                  SourceRange BracketsRange) {
14293   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14294                                        SizeExpr,
14295                                        IndexTypeQuals, BracketsRange);
14296 }
14297 
14298 template<typename Derived>
14299 QualType
14300 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14301                                           ArrayType::ArraySizeModifier SizeMod,
14302                                                        Expr *SizeExpr,
14303                                                        unsigned IndexTypeQuals,
14304                                                    SourceRange BracketsRange) {
14305   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14306                                        SizeExpr,
14307                                        IndexTypeQuals, BracketsRange);
14308 }
14309 
14310 template <typename Derived>
14311 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14312     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14313   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14314                                           AttributeLoc);
14315 }
14316 
14317 template <typename Derived>
14318 QualType
14319 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14320                                           unsigned NumElements,
14321                                           VectorType::VectorKind VecKind) {
14322   // FIXME: semantic checking!
14323   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14324 }
14325 
14326 template <typename Derived>
14327 QualType TreeTransform<Derived>::RebuildDependentVectorType(
14328     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14329     VectorType::VectorKind VecKind) {
14330   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14331 }
14332 
14333 template<typename Derived>
14334 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14335                                                       unsigned NumElements,
14336                                                  SourceLocation AttributeLoc) {
14337   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14338                           NumElements, true);
14339   IntegerLiteral *VectorSize
14340     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14341                              AttributeLoc);
14342   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14343 }
14344 
14345 template<typename Derived>
14346 QualType
14347 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14348                                                            Expr *SizeExpr,
14349                                                   SourceLocation AttributeLoc) {
14350   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14351 }
14352 
14353 template <typename Derived>
14354 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14355     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14356   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14357                                                NumColumns);
14358 }
14359 
14360 template <typename Derived>
14361 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14362     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14363     SourceLocation AttributeLoc) {
14364   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14365                                  AttributeLoc);
14366 }
14367 
14368 template<typename Derived>
14369 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14370     QualType T,
14371     MutableArrayRef<QualType> ParamTypes,
14372     const FunctionProtoType::ExtProtoInfo &EPI) {
14373   return SemaRef.BuildFunctionType(T, ParamTypes,
14374                                    getDerived().getBaseLocation(),
14375                                    getDerived().getBaseEntity(),
14376                                    EPI);
14377 }
14378 
14379 template<typename Derived>
14380 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14381   return SemaRef.Context.getFunctionNoProtoType(T);
14382 }
14383 
14384 template<typename Derived>
14385 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14386                                                             Decl *D) {
14387   assert(D && "no decl found");
14388   if (D->isInvalidDecl()) return QualType();
14389 
14390   // FIXME: Doesn't account for ObjCInterfaceDecl!
14391   TypeDecl *Ty;
14392   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14393     // A valid resolved using typename pack expansion decl can have multiple
14394     // UsingDecls, but they must each have exactly one type, and it must be
14395     // the same type in every case. But we must have at least one expansion!
14396     if (UPD->expansions().empty()) {
14397       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14398           << UPD->isCXXClassMember() << UPD;
14399       return QualType();
14400     }
14401 
14402     // We might still have some unresolved types. Try to pick a resolved type
14403     // if we can. The final instantiation will check that the remaining
14404     // unresolved types instantiate to the type we pick.
14405     QualType FallbackT;
14406     QualType T;
14407     for (auto *E : UPD->expansions()) {
14408       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14409       if (ThisT.isNull())
14410         continue;
14411       else if (ThisT->getAs<UnresolvedUsingType>())
14412         FallbackT = ThisT;
14413       else if (T.isNull())
14414         T = ThisT;
14415       else
14416         assert(getSema().Context.hasSameType(ThisT, T) &&
14417                "mismatched resolved types in using pack expansion");
14418     }
14419     return T.isNull() ? FallbackT : T;
14420   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14421     assert(Using->hasTypename() &&
14422            "UnresolvedUsingTypenameDecl transformed to non-typename using");
14423 
14424     // A valid resolved using typename decl points to exactly one type decl.
14425     assert(++Using->shadow_begin() == Using->shadow_end());
14426 
14427     NamedDecl *Target = Using->shadow_begin()->getTargetDecl();
14428     if (SemaRef.DiagnoseUseOfDecl(Target, Loc))
14429       return QualType();
14430     Ty = cast<TypeDecl>(Target);
14431   } else {
14432     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
14433            "UnresolvedUsingTypenameDecl transformed to non-using decl");
14434     Ty = cast<UnresolvedUsingTypenameDecl>(D);
14435   }
14436 
14437   return SemaRef.Context.getTypeDeclType(Ty);
14438 }
14439 
14440 template<typename Derived>
14441 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
14442                                                        SourceLocation Loc) {
14443   return SemaRef.BuildTypeofExprType(E, Loc);
14444 }
14445 
14446 template<typename Derived>
14447 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
14448   return SemaRef.Context.getTypeOfType(Underlying);
14449 }
14450 
14451 template<typename Derived>
14452 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
14453                                                      SourceLocation Loc) {
14454   return SemaRef.BuildDecltypeType(E, Loc);
14455 }
14456 
14457 template<typename Derived>
14458 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
14459                                             UnaryTransformType::UTTKind UKind,
14460                                             SourceLocation Loc) {
14461   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
14462 }
14463 
14464 template<typename Derived>
14465 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
14466                                                       TemplateName Template,
14467                                              SourceLocation TemplateNameLoc,
14468                                      TemplateArgumentListInfo &TemplateArgs) {
14469   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
14470 }
14471 
14472 template<typename Derived>
14473 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
14474                                                    SourceLocation KWLoc) {
14475   return SemaRef.BuildAtomicType(ValueType, KWLoc);
14476 }
14477 
14478 template<typename Derived>
14479 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
14480                                                  SourceLocation KWLoc,
14481                                                  bool isReadPipe) {
14482   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
14483                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
14484 }
14485 
14486 template <typename Derived>
14487 QualType TreeTransform<Derived>::RebuildExtIntType(bool IsUnsigned,
14488                                                    unsigned NumBits,
14489                                                    SourceLocation Loc) {
14490   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14491                         NumBits, true);
14492   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
14493                                                 SemaRef.Context.IntTy, Loc);
14494   return SemaRef.BuildExtIntType(IsUnsigned, Bits, Loc);
14495 }
14496 
14497 template <typename Derived>
14498 QualType TreeTransform<Derived>::RebuildDependentExtIntType(
14499     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
14500   return SemaRef.BuildExtIntType(IsUnsigned, NumBitsExpr, Loc);
14501 }
14502 
14503 template<typename Derived>
14504 TemplateName
14505 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14506                                             bool TemplateKW,
14507                                             TemplateDecl *Template) {
14508   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
14509                                                   Template);
14510 }
14511 
14512 template<typename Derived>
14513 TemplateName
14514 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14515                                             SourceLocation TemplateKWLoc,
14516                                             const IdentifierInfo &Name,
14517                                             SourceLocation NameLoc,
14518                                             QualType ObjectType,
14519                                             NamedDecl *FirstQualifierInScope,
14520                                             bool AllowInjectedClassName) {
14521   UnqualifiedId TemplateName;
14522   TemplateName.setIdentifier(&Name, NameLoc);
14523   Sema::TemplateTy Template;
14524   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
14525                               TemplateName, ParsedType::make(ObjectType),
14526                               /*EnteringContext=*/false, Template,
14527                               AllowInjectedClassName);
14528   return Template.get();
14529 }
14530 
14531 template<typename Derived>
14532 TemplateName
14533 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14534                                             SourceLocation TemplateKWLoc,
14535                                             OverloadedOperatorKind Operator,
14536                                             SourceLocation NameLoc,
14537                                             QualType ObjectType,
14538                                             bool AllowInjectedClassName) {
14539   UnqualifiedId Name;
14540   // FIXME: Bogus location information.
14541   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
14542   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
14543   Sema::TemplateTy Template;
14544   getSema().ActOnTemplateName(
14545       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
14546       /*EnteringContext=*/false, Template, AllowInjectedClassName);
14547   return Template.get();
14548 }
14549 
14550 template<typename Derived>
14551 ExprResult
14552 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
14553                                                    SourceLocation OpLoc,
14554                                                    Expr *OrigCallee,
14555                                                    Expr *First,
14556                                                    Expr *Second) {
14557   Expr *Callee = OrigCallee->IgnoreParenCasts();
14558   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
14559 
14560   if (First->getObjectKind() == OK_ObjCProperty) {
14561     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14562     if (BinaryOperator::isAssignmentOp(Opc))
14563       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
14564                                                  First, Second);
14565     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
14566     if (Result.isInvalid())
14567       return ExprError();
14568     First = Result.get();
14569   }
14570 
14571   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
14572     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
14573     if (Result.isInvalid())
14574       return ExprError();
14575     Second = Result.get();
14576   }
14577 
14578   // Determine whether this should be a builtin operation.
14579   if (Op == OO_Subscript) {
14580     if (!First->getType()->isOverloadableType() &&
14581         !Second->getType()->isOverloadableType())
14582       return getSema().CreateBuiltinArraySubscriptExpr(
14583           First, Callee->getBeginLoc(), Second, OpLoc);
14584   } else if (Op == OO_Arrow) {
14585     // -> is never a builtin operation.
14586     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
14587   } else if (Second == nullptr || isPostIncDec) {
14588     if (!First->getType()->isOverloadableType() ||
14589         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
14590       // The argument is not of overloadable type, or this is an expression
14591       // of the form &Class::member, so try to create a built-in unary
14592       // operation.
14593       UnaryOperatorKind Opc
14594         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14595 
14596       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
14597     }
14598   } else {
14599     if (!First->getType()->isOverloadableType() &&
14600         !Second->getType()->isOverloadableType()) {
14601       // Neither of the arguments is an overloadable type, so try to
14602       // create a built-in binary operation.
14603       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14604       ExprResult Result
14605         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
14606       if (Result.isInvalid())
14607         return ExprError();
14608 
14609       return Result;
14610     }
14611   }
14612 
14613   // Compute the transformed set of functions (and function templates) to be
14614   // used during overload resolution.
14615   UnresolvedSet<16> Functions;
14616   bool RequiresADL;
14617 
14618   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
14619     Functions.append(ULE->decls_begin(), ULE->decls_end());
14620     // If the overload could not be resolved in the template definition
14621     // (because we had a dependent argument), ADL is performed as part of
14622     // template instantiation.
14623     RequiresADL = ULE->requiresADL();
14624   } else {
14625     // If we've resolved this to a particular non-member function, just call
14626     // that function. If we resolved it to a member function,
14627     // CreateOverloaded* will find that function for us.
14628     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
14629     if (!isa<CXXMethodDecl>(ND))
14630       Functions.addDecl(ND);
14631     RequiresADL = false;
14632   }
14633 
14634   // Add any functions found via argument-dependent lookup.
14635   Expr *Args[2] = { First, Second };
14636   unsigned NumArgs = 1 + (Second != nullptr);
14637 
14638   // Create the overloaded operator invocation for unary operators.
14639   if (NumArgs == 1 || isPostIncDec) {
14640     UnaryOperatorKind Opc
14641       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14642     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
14643                                            RequiresADL);
14644   }
14645 
14646   if (Op == OO_Subscript) {
14647     SourceLocation LBrace;
14648     SourceLocation RBrace;
14649 
14650     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
14651       DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
14652       LBrace = NameLoc.getCXXOperatorNameBeginLoc();
14653       RBrace = NameLoc.getCXXOperatorNameEndLoc();
14654     } else {
14655       LBrace = Callee->getBeginLoc();
14656       RBrace = OpLoc;
14657     }
14658 
14659     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
14660                                                       First, Second);
14661   }
14662 
14663   // Create the overloaded operator invocation for binary operators.
14664   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14665   ExprResult Result = SemaRef.CreateOverloadedBinOp(
14666       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
14667   if (Result.isInvalid())
14668     return ExprError();
14669 
14670   return Result;
14671 }
14672 
14673 template<typename Derived>
14674 ExprResult
14675 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
14676                                                      SourceLocation OperatorLoc,
14677                                                        bool isArrow,
14678                                                        CXXScopeSpec &SS,
14679                                                      TypeSourceInfo *ScopeType,
14680                                                        SourceLocation CCLoc,
14681                                                        SourceLocation TildeLoc,
14682                                         PseudoDestructorTypeStorage Destroyed) {
14683   QualType BaseType = Base->getType();
14684   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
14685       (!isArrow && !BaseType->getAs<RecordType>()) ||
14686       (isArrow && BaseType->getAs<PointerType>() &&
14687        !BaseType->castAs<PointerType>()->getPointeeType()
14688                                               ->template getAs<RecordType>())){
14689     // This pseudo-destructor expression is still a pseudo-destructor.
14690     return SemaRef.BuildPseudoDestructorExpr(
14691         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
14692         CCLoc, TildeLoc, Destroyed);
14693   }
14694 
14695   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
14696   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
14697                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
14698   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
14699   NameInfo.setNamedTypeInfo(DestroyedType);
14700 
14701   // The scope type is now known to be a valid nested name specifier
14702   // component. Tack it on to the end of the nested name specifier.
14703   if (ScopeType) {
14704     if (!ScopeType->getType()->getAs<TagType>()) {
14705       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
14706                      diag::err_expected_class_or_namespace)
14707           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
14708       return ExprError();
14709     }
14710     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
14711               CCLoc);
14712   }
14713 
14714   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
14715   return getSema().BuildMemberReferenceExpr(Base, BaseType,
14716                                             OperatorLoc, isArrow,
14717                                             SS, TemplateKWLoc,
14718                                             /*FIXME: FirstQualifier*/ nullptr,
14719                                             NameInfo,
14720                                             /*TemplateArgs*/ nullptr,
14721                                             /*S*/nullptr);
14722 }
14723 
14724 template<typename Derived>
14725 StmtResult
14726 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
14727   SourceLocation Loc = S->getBeginLoc();
14728   CapturedDecl *CD = S->getCapturedDecl();
14729   unsigned NumParams = CD->getNumParams();
14730   unsigned ContextParamPos = CD->getContextParamPosition();
14731   SmallVector<Sema::CapturedParamNameType, 4> Params;
14732   for (unsigned I = 0; I < NumParams; ++I) {
14733     if (I != ContextParamPos) {
14734       Params.push_back(
14735              std::make_pair(
14736                   CD->getParam(I)->getName(),
14737                   getDerived().TransformType(CD->getParam(I)->getType())));
14738     } else {
14739       Params.push_back(std::make_pair(StringRef(), QualType()));
14740     }
14741   }
14742   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
14743                                      S->getCapturedRegionKind(), Params);
14744   StmtResult Body;
14745   {
14746     Sema::CompoundScopeRAII CompoundScope(getSema());
14747     Body = getDerived().TransformStmt(S->getCapturedStmt());
14748   }
14749 
14750   if (Body.isInvalid()) {
14751     getSema().ActOnCapturedRegionError();
14752     return StmtError();
14753   }
14754 
14755   return getSema().ActOnCapturedRegionEnd(Body.get());
14756 }
14757 
14758 } // end namespace clang
14759 
14760 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14761