1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file implements a semantic tree transformation that takes a given
10 // AST and rebuilds it, possibly transforming some nodes in the process.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
17 #include "CoroutineStmtBuilder.h"
18 #include "TypeLocBuilder.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/AST/StmtOpenMP.h"
30 #include "clang/Sema/Designator.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Ownership.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaDiagnostic.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/Support/ErrorHandling.h"
44 /// \brief A semantic tree transformation that allows one to transform one
45 /// abstract syntax tree into another.
47 /// A new tree transformation is defined by creating a new subclass \c X of
48 /// \c TreeTransform<X> and then overriding certain operations to provide
49 /// behavior specific to that transformation. For example, template
50 /// instantiation is implemented as a tree transformation where the
51 /// transformation of TemplateTypeParmType nodes involves substituting the
52 /// template arguments for their corresponding template parameters; a similar
53 /// transformation is performed for non-type template parameters and
54 /// template template parameters.
56 /// This tree-transformation template uses static polymorphism to allow
57 /// subclasses to customize any of its operations. Thus, a subclass can
58 /// override any of the transformation or rebuild operators by providing an
59 /// operation with the same signature as the default implementation. The
60 /// overridding function should not be virtual.
62 /// Semantic tree transformations are split into two stages, either of which
63 /// can be replaced by a subclass. The "transform" step transforms an AST node
64 /// or the parts of an AST node using the various transformation functions,
65 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
66 /// node of the appropriate kind from the pieces. The default transformation
67 /// routines recursively transform the operands to composite AST nodes (e.g.,
68 /// the pointee type of a PointerType node) and, if any of those operand nodes
69 /// were changed by the transformation, invokes the rebuild operation to create
72 /// Subclasses can customize the transformation at various levels. The
73 /// most coarse-grained transformations involve replacing TransformType(),
74 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
75 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
76 /// new implementations.
78 /// For more fine-grained transformations, subclasses can replace any of the
79 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
80 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
81 /// replacing TransformTemplateTypeParmType() allows template instantiation
82 /// to substitute template arguments for their corresponding template
83 /// parameters. Additionally, subclasses can override the \c RebuildXXX
84 /// functions to control how AST nodes are rebuilt when their operands change.
85 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
86 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
87 /// be able to use more efficient rebuild steps.
89 /// There are a handful of other functions that can be overridden, allowing one
90 /// to avoid traversing nodes that don't need any transformation
91 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
92 /// operands have not changed (\c AlwaysRebuild()), and customize the
93 /// default locations and entity names used for type-checking
94 /// (\c getBaseLocation(), \c getBaseEntity()).
95 template<typename Derived>
97 /// \brief Private RAII object that helps us forget and then re-remember
98 /// the template argument corresponding to a partially-substituted parameter
100 class ForgetPartiallySubstitutedPackRAII {
102 TemplateArgument Old;
105 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
106 Old = Self.ForgetPartiallySubstitutedPack();
109 ~ForgetPartiallySubstitutedPackRAII() {
110 Self.RememberPartiallySubstitutedPack(Old);
117 /// \brief The set of local declarations that have been transformed, for
118 /// cases where we are forced to build new declarations within the transformer
119 /// rather than in the subclass (e.g., lambda closure types).
120 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
123 /// \brief Initializes a new tree transformer.
124 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
126 /// \brief Retrieves a reference to the derived class.
127 Derived &getDerived() { return static_cast<Derived&>(*this); }
129 /// \brief Retrieves a reference to the derived class.
130 const Derived &getDerived() const {
131 return static_cast<const Derived&>(*this);
134 static inline ExprResult Owned(Expr *E) { return E; }
135 static inline StmtResult Owned(Stmt *S) { return S; }
137 /// \brief Retrieves a reference to the semantic analysis object used for
138 /// this tree transform.
139 Sema &getSema() const { return SemaRef; }
141 /// \brief Whether the transformation should always rebuild AST nodes, even
142 /// if none of the children have changed.
144 /// Subclasses may override this function to specify when the transformation
145 /// should rebuild all AST nodes.
147 /// We must always rebuild all AST nodes when performing variadic template
148 /// pack expansion, in order to avoid violating the AST invariant that each
149 /// statement node appears at most once in its containing declaration.
150 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
152 /// \brief Returns the location of the entity being transformed, if that
153 /// information was not available elsewhere in the AST.
155 /// By default, returns no source-location information. Subclasses can
156 /// provide an alternative implementation that provides better location
158 SourceLocation getBaseLocation() { return SourceLocation(); }
160 /// \brief Returns the name of the entity being transformed, if that
161 /// information was not available elsewhere in the AST.
163 /// By default, returns an empty name. Subclasses can provide an alternative
164 /// implementation with a more precise name.
165 DeclarationName getBaseEntity() { return DeclarationName(); }
167 /// \brief Sets the "base" location and entity when that
168 /// information is known based on another transformation.
170 /// By default, the source location and entity are ignored. Subclasses can
171 /// override this function to provide a customized implementation.
172 void setBase(SourceLocation Loc, DeclarationName Entity) { }
174 /// \brief RAII object that temporarily sets the base location and entity
175 /// used for reporting diagnostics in types.
176 class TemporaryBase {
178 SourceLocation OldLocation;
179 DeclarationName OldEntity;
182 TemporaryBase(TreeTransform &Self, SourceLocation Location,
183 DeclarationName Entity) : Self(Self) {
184 OldLocation = Self.getDerived().getBaseLocation();
185 OldEntity = Self.getDerived().getBaseEntity();
187 if (Location.isValid())
188 Self.getDerived().setBase(Location, Entity);
192 Self.getDerived().setBase(OldLocation, OldEntity);
196 /// \brief Determine whether the given type \p T has already been
199 /// Subclasses can provide an alternative implementation of this routine
200 /// to short-circuit evaluation when it is known that a given type will
201 /// not change. For example, template instantiation need not traverse
202 /// non-dependent types.
203 bool AlreadyTransformed(QualType T) {
207 /// \brief Determine whether the given call argument should be dropped, e.g.,
208 /// because it is a default argument.
210 /// Subclasses can provide an alternative implementation of this routine to
211 /// determine which kinds of call arguments get dropped. By default,
212 /// CXXDefaultArgument nodes are dropped (prior to transformation).
213 bool DropCallArgument(Expr *E) {
214 return E->isDefaultArgument();
217 /// \brief Determine whether we should expand a pack expansion with the
218 /// given set of parameter packs into separate arguments by repeatedly
219 /// transforming the pattern.
221 /// By default, the transformer never tries to expand pack expansions.
222 /// Subclasses can override this routine to provide different behavior.
224 /// \param EllipsisLoc The location of the ellipsis that identifies the
227 /// \param PatternRange The source range that covers the entire pattern of
228 /// the pack expansion.
230 /// \param Unexpanded The set of unexpanded parameter packs within the
233 /// \param ShouldExpand Will be set to \c true if the transformer should
234 /// expand the corresponding pack expansions into separate arguments. When
235 /// set, \c NumExpansions must also be set.
237 /// \param RetainExpansion Whether the caller should add an unexpanded
238 /// pack expansion after all of the expanded arguments. This is used
239 /// when extending explicitly-specified template argument packs per
240 /// C++0x [temp.arg.explicit]p9.
242 /// \param NumExpansions The number of separate arguments that will be in
243 /// the expanded form of the corresponding pack expansion. This is both an
244 /// input and an output parameter, which can be set by the caller if the
245 /// number of expansions is known a priori (e.g., due to a prior substitution)
246 /// and will be set by the callee when the number of expansions is known.
247 /// The callee must set this value when \c ShouldExpand is \c true; it may
248 /// set this value in other cases.
250 /// \returns true if an error occurred (e.g., because the parameter packs
251 /// are to be instantiated with arguments of different lengths), false
252 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
254 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
255 SourceRange PatternRange,
256 ArrayRef<UnexpandedParameterPack> Unexpanded,
258 bool &RetainExpansion,
259 Optional<unsigned> &NumExpansions) {
260 ShouldExpand = false;
264 /// \brief "Forget" about the partially-substituted pack template argument,
265 /// when performing an instantiation that must preserve the parameter pack
268 /// This routine is meant to be overridden by the template instantiator.
269 TemplateArgument ForgetPartiallySubstitutedPack() {
270 return TemplateArgument();
273 /// \brief "Remember" the partially-substituted pack template argument
274 /// after performing an instantiation that must preserve the parameter pack
277 /// This routine is meant to be overridden by the template instantiator.
278 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
280 /// \brief Note to the derived class when a function parameter pack is
282 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
284 /// \brief Transforms the given type into another type.
286 /// By default, this routine transforms a type by creating a
287 /// TypeSourceInfo for it and delegating to the appropriate
288 /// function. This is expensive, but we don't mind, because
289 /// this method is deprecated anyway; all users should be
290 /// switched to storing TypeSourceInfos.
292 /// \returns the transformed type.
293 QualType TransformType(QualType T);
295 /// \brief Transforms the given type-with-location into a new
296 /// type-with-location.
298 /// By default, this routine transforms a type by delegating to the
299 /// appropriate TransformXXXType to build a new type. Subclasses
300 /// may override this function (to take over all type
301 /// transformations) or some set of the TransformXXXType functions
302 /// to alter the transformation.
303 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
305 /// \brief Transform the given type-with-location into a new
306 /// type, collecting location information in the given builder
309 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
311 /// \brief Transform a type that is permitted to produce a
312 /// DeducedTemplateSpecializationType.
314 /// This is used in the (relatively rare) contexts where it is acceptable
315 /// for transformation to produce a class template type with deduced
316 /// template arguments.
318 QualType TransformTypeWithDeducedTST(QualType T);
319 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
322 /// \brief Transform the given statement.
324 /// By default, this routine transforms a statement by delegating to the
325 /// appropriate TransformXXXStmt function to transform a specific kind of
326 /// statement or the TransformExpr() function to transform an expression.
327 /// Subclasses may override this function to transform statements using some
330 /// \returns the transformed statement.
331 StmtResult TransformStmt(Stmt *S);
333 /// \brief Transform the given statement.
335 /// By default, this routine transforms a statement by delegating to the
336 /// appropriate TransformOMPXXXClause function to transform a specific kind
337 /// of clause. Subclasses may override this function to transform statements
338 /// using some other mechanism.
340 /// \returns the transformed OpenMP clause.
341 OMPClause *TransformOMPClause(OMPClause *S);
343 /// \brief Transform the given attribute.
345 /// By default, this routine transforms a statement by delegating to the
346 /// appropriate TransformXXXAttr function to transform a specific kind
347 /// of attribute. Subclasses may override this function to transform
348 /// attributed statements using some other mechanism.
350 /// \returns the transformed attribute
351 const Attr *TransformAttr(const Attr *S);
353 /// \brief Transform the specified attribute.
355 /// Subclasses should override the transformation of attributes with a pragma
356 /// spelling to transform expressions stored within the attribute.
358 /// \returns the transformed attribute.
360 #define PRAGMA_SPELLING_ATTR(X) \
361 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
362 #include "clang/Basic/AttrList.inc"
364 /// \brief Transform the given expression.
366 /// By default, this routine transforms an expression by delegating to the
367 /// appropriate TransformXXXExpr function to build a new expression.
368 /// Subclasses may override this function to transform expressions using some
371 /// \returns the transformed expression.
372 ExprResult TransformExpr(Expr *E);
374 /// \brief Transform the given initializer.
376 /// By default, this routine transforms an initializer by stripping off the
377 /// semantic nodes added by initialization, then passing the result to
378 /// TransformExpr or TransformExprs.
380 /// \returns the transformed initializer.
381 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
383 /// \brief Transform the given list of expressions.
385 /// This routine transforms a list of expressions by invoking
386 /// \c TransformExpr() for each subexpression. However, it also provides
387 /// support for variadic templates by expanding any pack expansions (if the
388 /// derived class permits such expansion) along the way. When pack expansions
389 /// are present, the number of outputs may not equal the number of inputs.
391 /// \param Inputs The set of expressions to be transformed.
393 /// \param NumInputs The number of expressions in \c Inputs.
395 /// \param IsCall If \c true, then this transform is being performed on
396 /// function-call arguments, and any arguments that should be dropped, will
399 /// \param Outputs The transformed input expressions will be added to this
402 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
403 /// due to transformation.
405 /// \returns true if an error occurred, false otherwise.
406 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
407 SmallVectorImpl<Expr *> &Outputs,
408 bool *ArgChanged = nullptr);
410 /// \brief Transform the given declaration, which is referenced from a type
413 /// By default, acts as the identity function on declarations, unless the
414 /// transformer has had to transform the declaration itself. Subclasses
415 /// may override this function to provide alternate behavior.
416 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
417 llvm::DenseMap<Decl *, Decl *>::iterator Known
418 = TransformedLocalDecls.find(D);
419 if (Known != TransformedLocalDecls.end())
420 return Known->second;
425 /// \brief Transform the specified condition.
427 /// By default, this transforms the variable and expression and rebuilds
429 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
431 Sema::ConditionKind Kind);
433 /// \brief Transform the attributes associated with the given declaration and
434 /// place them on the new declaration.
436 /// By default, this operation does nothing. Subclasses may override this
437 /// behavior to transform attributes.
438 void transformAttrs(Decl *Old, Decl *New) { }
440 /// \brief Note that a local declaration has been transformed by this
443 /// Local declarations are typically transformed via a call to
444 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
445 /// the transformer itself has to transform the declarations. This routine
446 /// can be overridden by a subclass that keeps track of such mappings.
447 void transformedLocalDecl(Decl *Old, Decl *New) {
448 TransformedLocalDecls[Old] = New;
451 /// \brief Transform the definition of the given declaration.
453 /// By default, invokes TransformDecl() to transform the declaration.
454 /// Subclasses may override this function to provide alternate behavior.
455 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
456 return getDerived().TransformDecl(Loc, D);
459 /// \brief Transform the given declaration, which was the first part of a
460 /// nested-name-specifier in a member access expression.
462 /// This specific declaration transformation only applies to the first
463 /// identifier in a nested-name-specifier of a member access expression, e.g.,
464 /// the \c T in \c x->T::member
466 /// By default, invokes TransformDecl() to transform the declaration.
467 /// Subclasses may override this function to provide alternate behavior.
468 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
469 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
472 /// Transform the set of declarations in an OverloadExpr.
473 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
476 /// \brief Transform the given nested-name-specifier with source-location
479 /// By default, transforms all of the types and declarations within the
480 /// nested-name-specifier. Subclasses may override this function to provide
481 /// alternate behavior.
482 NestedNameSpecifierLoc
483 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
484 QualType ObjectType = QualType(),
485 NamedDecl *FirstQualifierInScope = nullptr);
487 /// \brief Transform the given declaration name.
489 /// By default, transforms the types of conversion function, constructor,
490 /// and destructor names and then (if needed) rebuilds the declaration name.
491 /// Identifiers and selectors are returned unmodified. Sublcasses may
492 /// override this function to provide alternate behavior.
494 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
496 /// \brief Transform the given template name.
498 /// \param SS The nested-name-specifier that qualifies the template
499 /// name. This nested-name-specifier must already have been transformed.
501 /// \param Name The template name to transform.
503 /// \param NameLoc The source location of the template name.
505 /// \param ObjectType If we're translating a template name within a member
506 /// access expression, this is the type of the object whose member template
507 /// is being referenced.
509 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
510 /// also refers to a name within the current (lexical) scope, this is the
511 /// declaration it refers to.
513 /// By default, transforms the template name by transforming the declarations
514 /// and nested-name-specifiers that occur within the template name.
515 /// Subclasses may override this function to provide alternate behavior.
517 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
518 SourceLocation NameLoc,
519 QualType ObjectType = QualType(),
520 NamedDecl *FirstQualifierInScope = nullptr,
521 bool AllowInjectedClassName = false);
523 /// \brief Transform the given template argument.
525 /// By default, this operation transforms the type, expression, or
526 /// declaration stored within the template argument and constructs a
527 /// new template argument from the transformed result. Subclasses may
528 /// override this function to provide alternate behavior.
530 /// Returns true if there was an error.
531 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
532 TemplateArgumentLoc &Output,
533 bool Uneval = false);
535 /// \brief Transform the given set of template arguments.
537 /// By default, this operation transforms all of the template arguments
538 /// in the input set using \c TransformTemplateArgument(), and appends
539 /// the transformed arguments to the output list.
541 /// Note that this overload of \c TransformTemplateArguments() is merely
542 /// a convenience function. Subclasses that wish to override this behavior
543 /// should override the iterator-based member template version.
545 /// \param Inputs The set of template arguments to be transformed.
547 /// \param NumInputs The number of template arguments in \p Inputs.
549 /// \param Outputs The set of transformed template arguments output by this
552 /// Returns true if an error occurred.
553 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
555 TemplateArgumentListInfo &Outputs,
556 bool Uneval = false) {
557 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
561 /// \brief Transform the given set of template arguments.
563 /// By default, this operation transforms all of the template arguments
564 /// in the input set using \c TransformTemplateArgument(), and appends
565 /// the transformed arguments to the output list.
567 /// \param First An iterator to the first template argument.
569 /// \param Last An iterator one step past the last template argument.
571 /// \param Outputs The set of transformed template arguments output by this
574 /// Returns true if an error occurred.
575 template<typename InputIterator>
576 bool TransformTemplateArguments(InputIterator First,
578 TemplateArgumentListInfo &Outputs,
579 bool Uneval = false);
581 /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
582 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
583 TemplateArgumentLoc &ArgLoc);
585 /// \brief Fakes up a TypeSourceInfo for a type.
586 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
587 return SemaRef.Context.getTrivialTypeSourceInfo(T,
588 getDerived().getBaseLocation());
591 #define ABSTRACT_TYPELOC(CLASS, PARENT)
592 #define TYPELOC(CLASS, PARENT) \
593 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
594 #include "clang/AST/TypeLocNodes.def"
596 template<typename Fn>
597 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
598 FunctionProtoTypeLoc TL,
599 CXXRecordDecl *ThisContext,
600 unsigned ThisTypeQuals,
601 Fn TransformExceptionSpec);
603 bool TransformExceptionSpec(SourceLocation Loc,
604 FunctionProtoType::ExceptionSpecInfo &ESI,
605 SmallVectorImpl<QualType> &Exceptions,
608 StmtResult TransformSEHHandler(Stmt *Handler);
611 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
612 TemplateSpecializationTypeLoc TL,
613 TemplateName Template);
616 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
617 DependentTemplateSpecializationTypeLoc TL,
618 TemplateName Template,
621 QualType TransformDependentTemplateSpecializationType(
622 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
623 NestedNameSpecifierLoc QualifierLoc);
625 /// \brief Transforms the parameters of a function type into the
628 /// The result vectors should be kept in sync; null entries in the
629 /// variables vector are acceptable.
631 /// Return true on error.
632 bool TransformFunctionTypeParams(
633 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
634 const QualType *ParamTypes,
635 const FunctionProtoType::ExtParameterInfo *ParamInfos,
636 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
637 Sema::ExtParameterInfoBuilder &PInfos);
639 /// \brief Transforms a single function-type parameter. Return null
642 /// \param indexAdjustment - A number to add to the parameter's
643 /// scope index; can be negative
644 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
646 Optional<unsigned> NumExpansions,
647 bool ExpectParameterPack);
649 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
651 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
652 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
654 TemplateParameterList *TransformTemplateParameterList(
655 TemplateParameterList *TPL) {
659 ExprResult TransformAddressOfOperand(Expr *E);
661 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
662 bool IsAddressOfOperand,
663 TypeSourceInfo **RecoveryTSI);
665 ExprResult TransformParenDependentScopeDeclRefExpr(
666 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
667 TypeSourceInfo **RecoveryTSI);
669 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
671 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
672 // amount of stack usage with clang.
673 #define STMT(Node, Parent) \
674 LLVM_ATTRIBUTE_NOINLINE \
675 StmtResult Transform##Node(Node *S);
676 #define EXPR(Node, Parent) \
677 LLVM_ATTRIBUTE_NOINLINE \
678 ExprResult Transform##Node(Node *E);
679 #define ABSTRACT_STMT(Stmt)
680 #include "clang/AST/StmtNodes.inc"
682 #define OPENMP_CLAUSE(Name, Class) \
683 LLVM_ATTRIBUTE_NOINLINE \
684 OMPClause *Transform ## Class(Class *S);
685 #include "clang/Basic/OpenMPKinds.def"
687 /// \brief Build a new qualified type given its unqualified type and type
690 /// By default, this routine adds type qualifiers only to types that can
691 /// have qualifiers, and silently suppresses those qualifiers that are not
692 /// permitted. Subclasses may override this routine to provide different
694 QualType RebuildQualifiedType(QualType T, SourceLocation Loc,
697 /// \brief Build a new pointer type given its pointee type.
699 /// By default, performs semantic analysis when building the pointer type.
700 /// Subclasses may override this routine to provide different behavior.
701 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
703 /// \brief Build a new block pointer type given its pointee type.
705 /// By default, performs semantic analysis when building the block pointer
706 /// type. Subclasses may override this routine to provide different behavior.
707 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
709 /// \brief Build a new reference type given the type it references.
711 /// By default, performs semantic analysis when building the
712 /// reference type. Subclasses may override this routine to provide
713 /// different behavior.
715 /// \param LValue whether the type was written with an lvalue sigil
716 /// or an rvalue sigil.
717 QualType RebuildReferenceType(QualType ReferentType,
719 SourceLocation Sigil);
721 /// \brief Build a new member pointer type given the pointee type and the
722 /// class type it refers into.
724 /// By default, performs semantic analysis when building the member pointer
725 /// type. Subclasses may override this routine to provide different behavior.
726 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
727 SourceLocation Sigil);
729 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
730 SourceLocation ProtocolLAngleLoc,
731 ArrayRef<ObjCProtocolDecl *> Protocols,
732 ArrayRef<SourceLocation> ProtocolLocs,
733 SourceLocation ProtocolRAngleLoc);
735 /// \brief Build an Objective-C object type.
737 /// By default, performs semantic analysis when building the object type.
738 /// Subclasses may override this routine to provide different behavior.
739 QualType RebuildObjCObjectType(QualType BaseType,
741 SourceLocation TypeArgsLAngleLoc,
742 ArrayRef<TypeSourceInfo *> TypeArgs,
743 SourceLocation TypeArgsRAngleLoc,
744 SourceLocation ProtocolLAngleLoc,
745 ArrayRef<ObjCProtocolDecl *> Protocols,
746 ArrayRef<SourceLocation> ProtocolLocs,
747 SourceLocation ProtocolRAngleLoc);
749 /// \brief Build a new Objective-C object pointer type given the pointee type.
751 /// By default, directly builds the pointer type, with no additional semantic
753 QualType RebuildObjCObjectPointerType(QualType PointeeType,
754 SourceLocation Star);
756 /// \brief Build a new array type given the element type, size
757 /// modifier, size of the array (if known), size expression, and index type
760 /// By default, performs semantic analysis when building the array type.
761 /// Subclasses may override this routine to provide different behavior.
762 /// Also by default, all of the other Rebuild*Array
763 QualType RebuildArrayType(QualType ElementType,
764 ArrayType::ArraySizeModifier SizeMod,
765 const llvm::APInt *Size,
767 unsigned IndexTypeQuals,
768 SourceRange BracketsRange);
770 /// \brief Build a new constant array type given the element type, size
771 /// modifier, (known) size of the array, and index type qualifiers.
773 /// By default, performs semantic analysis when building the array type.
774 /// Subclasses may override this routine to provide different behavior.
775 QualType RebuildConstantArrayType(QualType ElementType,
776 ArrayType::ArraySizeModifier SizeMod,
777 const llvm::APInt &Size,
778 unsigned IndexTypeQuals,
779 SourceRange BracketsRange);
781 /// \brief Build a new incomplete array type given the element type, size
782 /// modifier, and index type qualifiers.
784 /// By default, performs semantic analysis when building the array type.
785 /// Subclasses may override this routine to provide different behavior.
786 QualType RebuildIncompleteArrayType(QualType ElementType,
787 ArrayType::ArraySizeModifier SizeMod,
788 unsigned IndexTypeQuals,
789 SourceRange BracketsRange);
791 /// \brief Build a new variable-length array type given the element type,
792 /// size modifier, size expression, and index type qualifiers.
794 /// By default, performs semantic analysis when building the array type.
795 /// Subclasses may override this routine to provide different behavior.
796 QualType RebuildVariableArrayType(QualType ElementType,
797 ArrayType::ArraySizeModifier SizeMod,
799 unsigned IndexTypeQuals,
800 SourceRange BracketsRange);
802 /// \brief Build a new dependent-sized array type given the element type,
803 /// size modifier, size expression, and index type qualifiers.
805 /// By default, performs semantic analysis when building the array type.
806 /// Subclasses may override this routine to provide different behavior.
807 QualType RebuildDependentSizedArrayType(QualType ElementType,
808 ArrayType::ArraySizeModifier SizeMod,
810 unsigned IndexTypeQuals,
811 SourceRange BracketsRange);
813 /// \brief Build a new vector type given the element type and
814 /// number of elements.
816 /// By default, performs semantic analysis when building the vector type.
817 /// Subclasses may override this routine to provide different behavior.
818 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
819 VectorType::VectorKind VecKind);
821 /// \brief Build a new extended vector type given the element type and
822 /// number of elements.
824 /// By default, performs semantic analysis when building the vector type.
825 /// Subclasses may override this routine to provide different behavior.
826 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
827 SourceLocation AttributeLoc);
829 /// \brief Build a new potentially dependently-sized extended vector type
830 /// given the element type and number of elements.
832 /// By default, performs semantic analysis when building the vector type.
833 /// Subclasses may override this routine to provide different behavior.
834 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
836 SourceLocation AttributeLoc);
838 /// \brief Build a new function type.
840 /// By default, performs semantic analysis when building the function type.
841 /// Subclasses may override this routine to provide different behavior.
842 QualType RebuildFunctionProtoType(QualType T,
843 MutableArrayRef<QualType> ParamTypes,
844 const FunctionProtoType::ExtProtoInfo &EPI);
846 /// \brief Build a new unprototyped function type.
847 QualType RebuildFunctionNoProtoType(QualType ResultType);
849 /// \brief Rebuild an unresolved typename type, given the decl that
850 /// the UnresolvedUsingTypenameDecl was transformed to.
851 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
853 /// \brief Build a new typedef type.
854 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
855 return SemaRef.Context.getTypeDeclType(Typedef);
858 /// \brief Build a new class/struct/union type.
859 QualType RebuildRecordType(RecordDecl *Record) {
860 return SemaRef.Context.getTypeDeclType(Record);
863 /// \brief Build a new Enum type.
864 QualType RebuildEnumType(EnumDecl *Enum) {
865 return SemaRef.Context.getTypeDeclType(Enum);
868 /// \brief Build a new typeof(expr) type.
870 /// By default, performs semantic analysis when building the typeof type.
871 /// Subclasses may override this routine to provide different behavior.
872 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
874 /// \brief Build a new typeof(type) type.
876 /// By default, builds a new TypeOfType with the given underlying type.
877 QualType RebuildTypeOfType(QualType Underlying);
879 /// \brief Build a new unary transform type.
880 QualType RebuildUnaryTransformType(QualType BaseType,
881 UnaryTransformType::UTTKind UKind,
884 /// \brief Build a new C++11 decltype type.
886 /// By default, performs semantic analysis when building the decltype type.
887 /// Subclasses may override this routine to provide different behavior.
888 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
890 /// \brief Build a new C++11 auto type.
892 /// By default, builds a new AutoType with the given deduced type.
893 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
894 // Note, IsDependent is always false here: we implicitly convert an 'auto'
895 // which has been deduced to a dependent type into an undeduced 'auto', so
896 // that we'll retry deduction after the transformation.
897 return SemaRef.Context.getAutoType(Deduced, Keyword,
898 /*IsDependent*/ false);
901 /// By default, builds a new DeducedTemplateSpecializationType with the given
903 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
905 return SemaRef.Context.getDeducedTemplateSpecializationType(
906 Template, Deduced, /*IsDependent*/ false);
909 /// \brief Build a new template specialization type.
911 /// By default, performs semantic analysis when building the template
912 /// specialization type. Subclasses may override this routine to provide
913 /// different behavior.
914 QualType RebuildTemplateSpecializationType(TemplateName Template,
915 SourceLocation TemplateLoc,
916 TemplateArgumentListInfo &Args);
918 /// \brief Build a new parenthesized type.
920 /// By default, builds a new ParenType type from the inner type.
921 /// Subclasses may override this routine to provide different behavior.
922 QualType RebuildParenType(QualType InnerType) {
923 return SemaRef.BuildParenType(InnerType);
926 /// \brief Build a new qualified name type.
928 /// By default, builds a new ElaboratedType type from the keyword,
929 /// the nested-name-specifier and the named type.
930 /// Subclasses may override this routine to provide different behavior.
931 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
932 ElaboratedTypeKeyword Keyword,
933 NestedNameSpecifierLoc QualifierLoc,
935 return SemaRef.Context.getElaboratedType(Keyword,
936 QualifierLoc.getNestedNameSpecifier(),
940 /// \brief Build a new typename type that refers to a template-id.
942 /// By default, builds a new DependentNameType type from the
943 /// nested-name-specifier and the given type. Subclasses may override
944 /// this routine to provide different behavior.
945 QualType RebuildDependentTemplateSpecializationType(
946 ElaboratedTypeKeyword Keyword,
947 NestedNameSpecifierLoc QualifierLoc,
948 const IdentifierInfo *Name,
949 SourceLocation NameLoc,
950 TemplateArgumentListInfo &Args,
951 bool AllowInjectedClassName) {
952 // Rebuild the template name.
953 // TODO: avoid TemplateName abstraction
955 SS.Adopt(QualifierLoc);
956 TemplateName InstName
957 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
958 nullptr, AllowInjectedClassName);
960 if (InstName.isNull())
963 // If it's still dependent, make a dependent specialization.
964 if (InstName.getAsDependentTemplateName())
965 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
966 QualifierLoc.getNestedNameSpecifier(),
970 // Otherwise, make an elaborated type wrapping a non-dependent
973 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
974 if (T.isNull()) return QualType();
976 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
979 return SemaRef.Context.getElaboratedType(Keyword,
980 QualifierLoc.getNestedNameSpecifier(),
984 /// \brief Build a new typename type that refers to an identifier.
986 /// By default, performs semantic analysis when building the typename type
987 /// (or elaborated type). Subclasses may override this routine to provide
988 /// different behavior.
989 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
990 SourceLocation KeywordLoc,
991 NestedNameSpecifierLoc QualifierLoc,
992 const IdentifierInfo *Id,
993 SourceLocation IdLoc,
994 bool DeducedTSTContext) {
996 SS.Adopt(QualifierLoc);
998 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
999 // If the name is still dependent, just build a new dependent name type.
1000 if (!SemaRef.computeDeclContext(SS))
1001 return SemaRef.Context.getDependentNameType(Keyword,
1002 QualifierLoc.getNestedNameSpecifier(),
1006 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1007 QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1009 // If a dependent name resolves to a deduced template specialization type,
1010 // check that we're in one of the syntactic contexts permitting it.
1011 if (!DeducedTSTContext) {
1012 if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1013 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1014 SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1015 << (int)SemaRef.getTemplateNameKindForDiagnostics(
1016 Deduced->getTemplateName())
1017 << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1018 if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1019 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1026 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1028 // We had a dependent elaborated-type-specifier that has been transformed
1029 // into a non-dependent elaborated-type-specifier. Find the tag we're
1031 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1032 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1036 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1039 TagDecl *Tag = nullptr;
1040 SemaRef.LookupQualifiedName(Result, DC);
1041 switch (Result.getResultKind()) {
1042 case LookupResult::NotFound:
1043 case LookupResult::NotFoundInCurrentInstantiation:
1046 case LookupResult::Found:
1047 Tag = Result.getAsSingle<TagDecl>();
1050 case LookupResult::FoundOverloaded:
1051 case LookupResult::FoundUnresolvedValue:
1052 llvm_unreachable("Tag lookup cannot find non-tags");
1054 case LookupResult::Ambiguous:
1055 // Let the LookupResult structure handle ambiguities.
1060 // Check where the name exists but isn't a tag type and use that to emit
1061 // better diagnostics.
1062 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1063 SemaRef.LookupQualifiedName(Result, DC);
1064 switch (Result.getResultKind()) {
1065 case LookupResult::Found:
1066 case LookupResult::FoundOverloaded:
1067 case LookupResult::FoundUnresolvedValue: {
1068 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1069 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1070 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1072 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1076 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1077 << Kind << Id << DC << QualifierLoc.getSourceRange();
1083 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1085 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1086 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1090 // Build the elaborated-type-specifier type.
1091 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1092 return SemaRef.Context.getElaboratedType(Keyword,
1093 QualifierLoc.getNestedNameSpecifier(),
1097 /// \brief Build a new pack expansion type.
1099 /// By default, builds a new PackExpansionType type from the given pattern.
1100 /// Subclasses may override this routine to provide different behavior.
1101 QualType RebuildPackExpansionType(QualType Pattern,
1102 SourceRange PatternRange,
1103 SourceLocation EllipsisLoc,
1104 Optional<unsigned> NumExpansions) {
1105 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1109 /// \brief Build a new atomic type given its value type.
1111 /// By default, performs semantic analysis when building the atomic type.
1112 /// Subclasses may override this routine to provide different behavior.
1113 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1115 /// \brief Build a new pipe type given its value type.
1116 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1119 /// \brief Build a new template name given a nested name specifier, a flag
1120 /// indicating whether the "template" keyword was provided, and the template
1121 /// that the template name refers to.
1123 /// By default, builds the new template name directly. Subclasses may override
1124 /// this routine to provide different behavior.
1125 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1127 TemplateDecl *Template);
1129 /// \brief Build a new template name given a nested name specifier and the
1130 /// name that is referred to as a template.
1132 /// By default, performs semantic analysis to determine whether the name can
1133 /// be resolved to a specific template, then builds the appropriate kind of
1134 /// template name. Subclasses may override this routine to provide different
1136 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1137 const IdentifierInfo &Name,
1138 SourceLocation NameLoc,
1139 QualType ObjectType,
1140 NamedDecl *FirstQualifierInScope,
1141 bool AllowInjectedClassName);
1143 /// \brief Build a new template name given a nested name specifier and the
1144 /// overloaded operator name that is referred to as a template.
1146 /// By default, performs semantic analysis to determine whether the name can
1147 /// be resolved to a specific template, then builds the appropriate kind of
1148 /// template name. Subclasses may override this routine to provide different
1150 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1151 OverloadedOperatorKind Operator,
1152 SourceLocation NameLoc,
1153 QualType ObjectType,
1154 bool AllowInjectedClassName);
1156 /// \brief Build a new template name given a template template parameter pack
1159 /// By default, performs semantic analysis to determine whether the name can
1160 /// be resolved to a specific template, then builds the appropriate kind of
1161 /// template name. Subclasses may override this routine to provide different
1163 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1164 const TemplateArgument &ArgPack) {
1165 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1168 /// \brief Build a new compound statement.
1170 /// By default, performs semantic analysis to build the new statement.
1171 /// Subclasses may override this routine to provide different behavior.
1172 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1173 MultiStmtArg Statements,
1174 SourceLocation RBraceLoc,
1176 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1180 /// \brief Build a new case statement.
1182 /// By default, performs semantic analysis to build the new statement.
1183 /// Subclasses may override this routine to provide different behavior.
1184 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1186 SourceLocation EllipsisLoc,
1188 SourceLocation ColonLoc) {
1189 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1193 /// \brief Attach the body to a new case statement.
1195 /// By default, performs semantic analysis to build the new statement.
1196 /// Subclasses may override this routine to provide different behavior.
1197 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1198 getSema().ActOnCaseStmtBody(S, Body);
1202 /// \brief Build a new default statement.
1204 /// By default, performs semantic analysis to build the new statement.
1205 /// Subclasses may override this routine to provide different behavior.
1206 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1207 SourceLocation ColonLoc,
1209 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1210 /*CurScope=*/nullptr);
1213 /// \brief Build a new label statement.
1215 /// By default, performs semantic analysis to build the new statement.
1216 /// Subclasses may override this routine to provide different behavior.
1217 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1218 SourceLocation ColonLoc, Stmt *SubStmt) {
1219 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1222 /// \brief Build a new label statement.
1224 /// By default, performs semantic analysis to build the new statement.
1225 /// Subclasses may override this routine to provide different behavior.
1226 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1227 ArrayRef<const Attr*> Attrs,
1229 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1232 /// \brief Build a new "if" statement.
1234 /// By default, performs semantic analysis to build the new statement.
1235 /// Subclasses may override this routine to provide different behavior.
1236 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1237 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1238 SourceLocation ElseLoc, Stmt *Else) {
1239 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1243 /// \brief Start building a new switch statement.
1245 /// By default, performs semantic analysis to build the new statement.
1246 /// Subclasses may override this routine to provide different behavior.
1247 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1248 Sema::ConditionResult Cond) {
1249 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1252 /// \brief Attach the body to the switch statement.
1254 /// By default, performs semantic analysis to build the new statement.
1255 /// Subclasses may override this routine to provide different behavior.
1256 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1257 Stmt *Switch, Stmt *Body) {
1258 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1261 /// \brief Build a new while statement.
1263 /// By default, performs semantic analysis to build the new statement.
1264 /// Subclasses may override this routine to provide different behavior.
1265 StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1266 Sema::ConditionResult Cond, Stmt *Body) {
1267 return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1270 /// \brief Build a new do-while statement.
1272 /// By default, performs semantic analysis to build the new statement.
1273 /// Subclasses may override this routine to provide different behavior.
1274 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1275 SourceLocation WhileLoc, SourceLocation LParenLoc,
1276 Expr *Cond, SourceLocation RParenLoc) {
1277 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1281 /// \brief Build a new for statement.
1283 /// By default, performs semantic analysis to build the new statement.
1284 /// Subclasses may override this routine to provide different behavior.
1285 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1286 Stmt *Init, Sema::ConditionResult Cond,
1287 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1289 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1290 Inc, RParenLoc, Body);
1293 /// \brief Build a new goto statement.
1295 /// By default, performs semantic analysis to build the new statement.
1296 /// Subclasses may override this routine to provide different behavior.
1297 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1299 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1302 /// \brief Build a new indirect goto statement.
1304 /// By default, performs semantic analysis to build the new statement.
1305 /// Subclasses may override this routine to provide different behavior.
1306 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1307 SourceLocation StarLoc,
1309 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1312 /// \brief Build a new return statement.
1314 /// By default, performs semantic analysis to build the new statement.
1315 /// Subclasses may override this routine to provide different behavior.
1316 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1317 return getSema().BuildReturnStmt(ReturnLoc, Result);
1320 /// \brief Build a new declaration statement.
1322 /// By default, performs semantic analysis to build the new statement.
1323 /// Subclasses may override this routine to provide different behavior.
1324 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1325 SourceLocation StartLoc, SourceLocation EndLoc) {
1326 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1327 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1330 /// \brief Build a new inline asm statement.
1332 /// By default, performs semantic analysis to build the new statement.
1333 /// Subclasses may override this routine to provide different behavior.
1334 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1335 bool IsVolatile, unsigned NumOutputs,
1336 unsigned NumInputs, IdentifierInfo **Names,
1337 MultiExprArg Constraints, MultiExprArg Exprs,
1338 Expr *AsmString, MultiExprArg Clobbers,
1339 SourceLocation RParenLoc) {
1340 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1341 NumInputs, Names, Constraints, Exprs,
1342 AsmString, Clobbers, RParenLoc);
1345 /// \brief Build a new MS style inline asm statement.
1347 /// By default, performs semantic analysis to build the new statement.
1348 /// Subclasses may override this routine to provide different behavior.
1349 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1350 ArrayRef<Token> AsmToks,
1351 StringRef AsmString,
1352 unsigned NumOutputs, unsigned NumInputs,
1353 ArrayRef<StringRef> Constraints,
1354 ArrayRef<StringRef> Clobbers,
1355 ArrayRef<Expr*> Exprs,
1356 SourceLocation EndLoc) {
1357 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1358 NumOutputs, NumInputs,
1359 Constraints, Clobbers, Exprs, EndLoc);
1362 /// \brief Build a new co_return statement.
1364 /// By default, performs semantic analysis to build the new statement.
1365 /// Subclasses may override this routine to provide different behavior.
1366 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1368 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1371 /// \brief Build a new co_await expression.
1373 /// By default, performs semantic analysis to build the new expression.
1374 /// Subclasses may override this routine to provide different behavior.
1375 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1377 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1380 /// \brief Build a new co_await expression.
1382 /// By default, performs semantic analysis to build the new expression.
1383 /// Subclasses may override this routine to provide different behavior.
1384 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1386 UnresolvedLookupExpr *Lookup) {
1387 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1390 /// \brief Build a new co_yield expression.
1392 /// By default, performs semantic analysis to build the new expression.
1393 /// Subclasses may override this routine to provide different behavior.
1394 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1395 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1398 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1399 return getSema().BuildCoroutineBodyStmt(Args);
1402 /// \brief Build a new Objective-C \@try statement.
1404 /// By default, performs semantic analysis to build the new statement.
1405 /// Subclasses may override this routine to provide different behavior.
1406 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1408 MultiStmtArg CatchStmts,
1410 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1414 /// \brief Rebuild an Objective-C exception declaration.
1416 /// By default, performs semantic analysis to build the new declaration.
1417 /// Subclasses may override this routine to provide different behavior.
1418 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1419 TypeSourceInfo *TInfo, QualType T) {
1420 return getSema().BuildObjCExceptionDecl(TInfo, T,
1421 ExceptionDecl->getInnerLocStart(),
1422 ExceptionDecl->getLocation(),
1423 ExceptionDecl->getIdentifier());
1426 /// \brief Build a new Objective-C \@catch statement.
1428 /// By default, performs semantic analysis to build the new statement.
1429 /// Subclasses may override this routine to provide different behavior.
1430 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1431 SourceLocation RParenLoc,
1434 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1438 /// \brief Build a new Objective-C \@finally statement.
1440 /// By default, performs semantic analysis to build the new statement.
1441 /// Subclasses may override this routine to provide different behavior.
1442 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1444 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1447 /// \brief Build a new Objective-C \@throw statement.
1449 /// By default, performs semantic analysis to build the new statement.
1450 /// Subclasses may override this routine to provide different behavior.
1451 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1453 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1456 /// \brief Build a new OpenMP executable directive.
1458 /// By default, performs semantic analysis to build the new statement.
1459 /// Subclasses may override this routine to provide different behavior.
1460 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1461 DeclarationNameInfo DirName,
1462 OpenMPDirectiveKind CancelRegion,
1463 ArrayRef<OMPClause *> Clauses,
1464 Stmt *AStmt, SourceLocation StartLoc,
1465 SourceLocation EndLoc) {
1466 return getSema().ActOnOpenMPExecutableDirective(
1467 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1470 /// \brief Build a new OpenMP 'if' clause.
1472 /// By default, performs semantic analysis to build the new OpenMP clause.
1473 /// Subclasses may override this routine to provide different behavior.
1474 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1475 Expr *Condition, SourceLocation StartLoc,
1476 SourceLocation LParenLoc,
1477 SourceLocation NameModifierLoc,
1478 SourceLocation ColonLoc,
1479 SourceLocation EndLoc) {
1480 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1481 LParenLoc, NameModifierLoc, ColonLoc,
1485 /// \brief Build a new OpenMP 'final' clause.
1487 /// By default, performs semantic analysis to build the new OpenMP clause.
1488 /// Subclasses may override this routine to provide different behavior.
1489 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1490 SourceLocation LParenLoc,
1491 SourceLocation EndLoc) {
1492 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1496 /// \brief Build a new OpenMP 'num_threads' clause.
1498 /// By default, performs semantic analysis to build the new OpenMP clause.
1499 /// Subclasses may override this routine to provide different behavior.
1500 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1501 SourceLocation StartLoc,
1502 SourceLocation LParenLoc,
1503 SourceLocation EndLoc) {
1504 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1508 /// \brief Build a new OpenMP 'safelen' clause.
1510 /// By default, performs semantic analysis to build the new OpenMP clause.
1511 /// Subclasses may override this routine to provide different behavior.
1512 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1513 SourceLocation LParenLoc,
1514 SourceLocation EndLoc) {
1515 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1518 /// \brief Build a new OpenMP 'simdlen' clause.
1520 /// By default, performs semantic analysis to build the new OpenMP clause.
1521 /// Subclasses may override this routine to provide different behavior.
1522 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1523 SourceLocation LParenLoc,
1524 SourceLocation EndLoc) {
1525 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1528 /// \brief Build a new OpenMP 'collapse' clause.
1530 /// By default, performs semantic analysis to build the new OpenMP clause.
1531 /// Subclasses may override this routine to provide different behavior.
1532 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1533 SourceLocation LParenLoc,
1534 SourceLocation EndLoc) {
1535 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1539 /// \brief Build a new OpenMP 'default' clause.
1541 /// By default, performs semantic analysis to build the new OpenMP clause.
1542 /// Subclasses may override this routine to provide different behavior.
1543 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1544 SourceLocation KindKwLoc,
1545 SourceLocation StartLoc,
1546 SourceLocation LParenLoc,
1547 SourceLocation EndLoc) {
1548 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1549 StartLoc, LParenLoc, EndLoc);
1552 /// \brief Build a new OpenMP 'proc_bind' clause.
1554 /// By default, performs semantic analysis to build the new OpenMP clause.
1555 /// Subclasses may override this routine to provide different behavior.
1556 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1557 SourceLocation KindKwLoc,
1558 SourceLocation StartLoc,
1559 SourceLocation LParenLoc,
1560 SourceLocation EndLoc) {
1561 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1562 StartLoc, LParenLoc, EndLoc);
1565 /// \brief Build a new OpenMP 'schedule' clause.
1567 /// By default, performs semantic analysis to build the new OpenMP clause.
1568 /// Subclasses may override this routine to provide different behavior.
1569 OMPClause *RebuildOMPScheduleClause(
1570 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1571 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1572 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1573 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1574 return getSema().ActOnOpenMPScheduleClause(
1575 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1579 /// \brief Build a new OpenMP 'ordered' clause.
1581 /// By default, performs semantic analysis to build the new OpenMP clause.
1582 /// Subclasses may override this routine to provide different behavior.
1583 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1584 SourceLocation EndLoc,
1585 SourceLocation LParenLoc, Expr *Num) {
1586 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1589 /// \brief Build a new OpenMP 'private' clause.
1591 /// By default, performs semantic analysis to build the new OpenMP clause.
1592 /// Subclasses may override this routine to provide different behavior.
1593 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1594 SourceLocation StartLoc,
1595 SourceLocation LParenLoc,
1596 SourceLocation EndLoc) {
1597 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1601 /// \brief Build a new OpenMP 'firstprivate' clause.
1603 /// By default, performs semantic analysis to build the new OpenMP clause.
1604 /// Subclasses may override this routine to provide different behavior.
1605 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1606 SourceLocation StartLoc,
1607 SourceLocation LParenLoc,
1608 SourceLocation EndLoc) {
1609 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1613 /// \brief Build a new OpenMP 'lastprivate' clause.
1615 /// By default, performs semantic analysis to build the new OpenMP clause.
1616 /// Subclasses may override this routine to provide different behavior.
1617 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1618 SourceLocation StartLoc,
1619 SourceLocation LParenLoc,
1620 SourceLocation EndLoc) {
1621 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1625 /// \brief Build a new OpenMP 'shared' clause.
1627 /// By default, performs semantic analysis to build the new OpenMP clause.
1628 /// Subclasses may override this routine to provide different behavior.
1629 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1630 SourceLocation StartLoc,
1631 SourceLocation LParenLoc,
1632 SourceLocation EndLoc) {
1633 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1637 /// \brief Build a new OpenMP 'reduction' clause.
1639 /// By default, performs semantic analysis to build the new statement.
1640 /// Subclasses may override this routine to provide different behavior.
1641 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1642 SourceLocation StartLoc,
1643 SourceLocation LParenLoc,
1644 SourceLocation ColonLoc,
1645 SourceLocation EndLoc,
1646 CXXScopeSpec &ReductionIdScopeSpec,
1647 const DeclarationNameInfo &ReductionId,
1648 ArrayRef<Expr *> UnresolvedReductions) {
1649 return getSema().ActOnOpenMPReductionClause(
1650 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1651 ReductionId, UnresolvedReductions);
1654 /// \brief Build a new OpenMP 'linear' clause.
1656 /// By default, performs semantic analysis to build the new OpenMP clause.
1657 /// Subclasses may override this routine to provide different behavior.
1658 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1659 SourceLocation StartLoc,
1660 SourceLocation LParenLoc,
1661 OpenMPLinearClauseKind Modifier,
1662 SourceLocation ModifierLoc,
1663 SourceLocation ColonLoc,
1664 SourceLocation EndLoc) {
1665 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1666 Modifier, ModifierLoc, ColonLoc,
1670 /// \brief Build a new OpenMP 'aligned' clause.
1672 /// By default, performs semantic analysis to build the new OpenMP clause.
1673 /// Subclasses may override this routine to provide different behavior.
1674 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1675 SourceLocation StartLoc,
1676 SourceLocation LParenLoc,
1677 SourceLocation ColonLoc,
1678 SourceLocation EndLoc) {
1679 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1680 LParenLoc, ColonLoc, EndLoc);
1683 /// \brief Build a new OpenMP 'copyin' clause.
1685 /// By default, performs semantic analysis to build the new OpenMP clause.
1686 /// Subclasses may override this routine to provide different behavior.
1687 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1688 SourceLocation StartLoc,
1689 SourceLocation LParenLoc,
1690 SourceLocation EndLoc) {
1691 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1695 /// \brief Build a new OpenMP 'copyprivate' clause.
1697 /// By default, performs semantic analysis to build the new OpenMP clause.
1698 /// Subclasses may override this routine to provide different behavior.
1699 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1700 SourceLocation StartLoc,
1701 SourceLocation LParenLoc,
1702 SourceLocation EndLoc) {
1703 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1707 /// \brief Build a new OpenMP 'flush' pseudo clause.
1709 /// By default, performs semantic analysis to build the new OpenMP clause.
1710 /// Subclasses may override this routine to provide different behavior.
1711 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1712 SourceLocation StartLoc,
1713 SourceLocation LParenLoc,
1714 SourceLocation EndLoc) {
1715 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1719 /// \brief Build a new OpenMP 'depend' pseudo clause.
1721 /// By default, performs semantic analysis to build the new OpenMP clause.
1722 /// Subclasses may override this routine to provide different behavior.
1724 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1725 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1726 SourceLocation StartLoc, SourceLocation LParenLoc,
1727 SourceLocation EndLoc) {
1728 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1729 StartLoc, LParenLoc, EndLoc);
1732 /// \brief Build a new OpenMP 'device' clause.
1734 /// By default, performs semantic analysis to build the new statement.
1735 /// Subclasses may override this routine to provide different behavior.
1736 OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1737 SourceLocation LParenLoc,
1738 SourceLocation EndLoc) {
1739 return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1743 /// \brief Build a new OpenMP 'map' clause.
1745 /// By default, performs semantic analysis to build the new OpenMP clause.
1746 /// Subclasses may override this routine to provide different behavior.
1748 RebuildOMPMapClause(OpenMPMapClauseKind MapTypeModifier,
1749 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1750 SourceLocation MapLoc, SourceLocation ColonLoc,
1751 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1752 SourceLocation LParenLoc, SourceLocation EndLoc) {
1753 return getSema().ActOnOpenMPMapClause(MapTypeModifier, MapType,
1754 IsMapTypeImplicit, MapLoc, ColonLoc,
1755 VarList, StartLoc, LParenLoc, EndLoc);
1758 /// \brief Build a new OpenMP 'num_teams' clause.
1760 /// By default, performs semantic analysis to build the new statement.
1761 /// Subclasses may override this routine to provide different behavior.
1762 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1763 SourceLocation LParenLoc,
1764 SourceLocation EndLoc) {
1765 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1769 /// \brief Build a new OpenMP 'thread_limit' clause.
1771 /// By default, performs semantic analysis to build the new statement.
1772 /// Subclasses may override this routine to provide different behavior.
1773 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1774 SourceLocation StartLoc,
1775 SourceLocation LParenLoc,
1776 SourceLocation EndLoc) {
1777 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1781 /// \brief Build a new OpenMP 'priority' clause.
1783 /// By default, performs semantic analysis to build the new statement.
1784 /// Subclasses may override this routine to provide different behavior.
1785 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1786 SourceLocation LParenLoc,
1787 SourceLocation EndLoc) {
1788 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1792 /// \brief Build a new OpenMP 'grainsize' clause.
1794 /// By default, performs semantic analysis to build the new statement.
1795 /// Subclasses may override this routine to provide different behavior.
1796 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1797 SourceLocation LParenLoc,
1798 SourceLocation EndLoc) {
1799 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1803 /// \brief Build a new OpenMP 'num_tasks' clause.
1805 /// By default, performs semantic analysis to build the new statement.
1806 /// Subclasses may override this routine to provide different behavior.
1807 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1808 SourceLocation LParenLoc,
1809 SourceLocation EndLoc) {
1810 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1814 /// \brief Build a new OpenMP 'hint' clause.
1816 /// By default, performs semantic analysis to build the new statement.
1817 /// Subclasses may override this routine to provide different behavior.
1818 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1819 SourceLocation LParenLoc,
1820 SourceLocation EndLoc) {
1821 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1824 /// \brief Build a new OpenMP 'dist_schedule' clause.
1826 /// By default, performs semantic analysis to build the new OpenMP clause.
1827 /// Subclasses may override this routine to provide different behavior.
1829 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1830 Expr *ChunkSize, SourceLocation StartLoc,
1831 SourceLocation LParenLoc, SourceLocation KindLoc,
1832 SourceLocation CommaLoc, SourceLocation EndLoc) {
1833 return getSema().ActOnOpenMPDistScheduleClause(
1834 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1837 /// \brief Build a new OpenMP 'to' clause.
1839 /// By default, performs semantic analysis to build the new statement.
1840 /// Subclasses may override this routine to provide different behavior.
1841 OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1842 SourceLocation StartLoc,
1843 SourceLocation LParenLoc,
1844 SourceLocation EndLoc) {
1845 return getSema().ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
1848 /// \brief Build a new OpenMP 'from' clause.
1850 /// By default, performs semantic analysis to build the new statement.
1851 /// Subclasses may override this routine to provide different behavior.
1852 OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1853 SourceLocation StartLoc,
1854 SourceLocation LParenLoc,
1855 SourceLocation EndLoc) {
1856 return getSema().ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc,
1860 /// Build a new OpenMP 'use_device_ptr' clause.
1862 /// By default, performs semantic analysis to build the new OpenMP clause.
1863 /// Subclasses may override this routine to provide different behavior.
1864 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1865 SourceLocation StartLoc,
1866 SourceLocation LParenLoc,
1867 SourceLocation EndLoc) {
1868 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc,
1872 /// Build a new OpenMP 'is_device_ptr' clause.
1874 /// By default, performs semantic analysis to build the new OpenMP clause.
1875 /// Subclasses may override this routine to provide different behavior.
1876 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1877 SourceLocation StartLoc,
1878 SourceLocation LParenLoc,
1879 SourceLocation EndLoc) {
1880 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc,
1884 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1886 /// By default, performs semantic analysis to build the new statement.
1887 /// Subclasses may override this routine to provide different behavior.
1888 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1890 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1893 /// \brief Build a new Objective-C \@synchronized statement.
1895 /// By default, performs semantic analysis to build the new statement.
1896 /// Subclasses may override this routine to provide different behavior.
1897 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1898 Expr *Object, Stmt *Body) {
1899 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1902 /// \brief Build a new Objective-C \@autoreleasepool statement.
1904 /// By default, performs semantic analysis to build the new statement.
1905 /// Subclasses may override this routine to provide different behavior.
1906 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1908 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1911 /// \brief Build a new Objective-C fast enumeration statement.
1913 /// By default, performs semantic analysis to build the new statement.
1914 /// Subclasses may override this routine to provide different behavior.
1915 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1918 SourceLocation RParenLoc,
1920 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1924 if (ForEachStmt.isInvalid())
1927 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1930 /// \brief Build a new C++ exception declaration.
1932 /// By default, performs semantic analysis to build the new decaration.
1933 /// Subclasses may override this routine to provide different behavior.
1934 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1935 TypeSourceInfo *Declarator,
1936 SourceLocation StartLoc,
1937 SourceLocation IdLoc,
1938 IdentifierInfo *Id) {
1939 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1940 StartLoc, IdLoc, Id);
1942 getSema().CurContext->addDecl(Var);
1946 /// \brief Build a new C++ catch statement.
1948 /// By default, performs semantic analysis to build the new statement.
1949 /// Subclasses may override this routine to provide different behavior.
1950 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1951 VarDecl *ExceptionDecl,
1953 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1957 /// \brief Build a new C++ try statement.
1959 /// By default, performs semantic analysis to build the new statement.
1960 /// Subclasses may override this routine to provide different behavior.
1961 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
1962 ArrayRef<Stmt *> Handlers) {
1963 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
1966 /// \brief Build a new C++0x range-based for statement.
1968 /// By default, performs semantic analysis to build the new statement.
1969 /// Subclasses may override this routine to provide different behavior.
1970 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
1971 SourceLocation CoawaitLoc,
1972 SourceLocation ColonLoc,
1973 Stmt *Range, Stmt *Begin, Stmt *End,
1974 Expr *Cond, Expr *Inc,
1976 SourceLocation RParenLoc) {
1977 // If we've just learned that the range is actually an Objective-C
1978 // collection, treat this as an Objective-C fast enumeration loop.
1979 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
1980 if (RangeStmt->isSingleDecl()) {
1981 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
1982 if (RangeVar->isInvalidDecl())
1985 Expr *RangeExpr = RangeVar->getInit();
1986 if (!RangeExpr->isTypeDependent() &&
1987 RangeExpr->getType()->isObjCObjectPointerType())
1988 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
1994 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc,
1996 Cond, Inc, LoopVar, RParenLoc,
1997 Sema::BFRK_Rebuild);
2000 /// \brief Build a new C++0x range-based for statement.
2002 /// By default, performs semantic analysis to build the new statement.
2003 /// Subclasses may override this routine to provide different behavior.
2004 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2006 NestedNameSpecifierLoc QualifierLoc,
2007 DeclarationNameInfo NameInfo,
2009 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2010 QualifierLoc, NameInfo, Nested);
2013 /// \brief Attach body to a C++0x range-based for statement.
2015 /// By default, performs semantic analysis to finish the new statement.
2016 /// Subclasses may override this routine to provide different behavior.
2017 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2018 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2021 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2022 Stmt *TryBlock, Stmt *Handler) {
2023 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2026 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2028 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2031 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2032 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2035 /// \brief Build a new predefined expression.
2037 /// By default, performs semantic analysis to build the new expression.
2038 /// Subclasses may override this routine to provide different behavior.
2039 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2040 PredefinedExpr::IdentType IT) {
2041 return getSema().BuildPredefinedExpr(Loc, IT);
2044 /// \brief Build a new expression that references a declaration.
2046 /// By default, performs semantic analysis to build the new expression.
2047 /// Subclasses may override this routine to provide different behavior.
2048 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2051 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2055 /// \brief Build a new expression that references a declaration.
2057 /// By default, performs semantic analysis to build the new expression.
2058 /// Subclasses may override this routine to provide different behavior.
2059 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2061 const DeclarationNameInfo &NameInfo,
2062 TemplateArgumentListInfo *TemplateArgs) {
2064 SS.Adopt(QualifierLoc);
2066 // FIXME: loses template args.
2068 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
2071 /// \brief Build a new expression in parentheses.
2073 /// By default, performs semantic analysis to build the new expression.
2074 /// Subclasses may override this routine to provide different behavior.
2075 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2076 SourceLocation RParen) {
2077 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2080 /// \brief Build a new pseudo-destructor expression.
2082 /// By default, performs semantic analysis to build the new expression.
2083 /// Subclasses may override this routine to provide different behavior.
2084 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2085 SourceLocation OperatorLoc,
2088 TypeSourceInfo *ScopeType,
2089 SourceLocation CCLoc,
2090 SourceLocation TildeLoc,
2091 PseudoDestructorTypeStorage Destroyed);
2093 /// \brief Build a new unary operator expression.
2095 /// By default, performs semantic analysis to build the new expression.
2096 /// Subclasses may override this routine to provide different behavior.
2097 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2098 UnaryOperatorKind Opc,
2100 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2103 /// \brief Build a new builtin offsetof expression.
2105 /// By default, performs semantic analysis to build the new expression.
2106 /// Subclasses may override this routine to provide different behavior.
2107 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2108 TypeSourceInfo *Type,
2109 ArrayRef<Sema::OffsetOfComponent> Components,
2110 SourceLocation RParenLoc) {
2111 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2115 /// \brief Build a new sizeof, alignof or vec_step expression with a
2118 /// By default, performs semantic analysis to build the new expression.
2119 /// Subclasses may override this routine to provide different behavior.
2120 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2121 SourceLocation OpLoc,
2122 UnaryExprOrTypeTrait ExprKind,
2124 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2127 /// \brief Build a new sizeof, alignof or vec step expression with an
2128 /// expression argument.
2130 /// By default, performs semantic analysis to build the new expression.
2131 /// Subclasses may override this routine to provide different behavior.
2132 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2133 UnaryExprOrTypeTrait ExprKind,
2136 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2137 if (Result.isInvalid())
2143 /// \brief Build a new array subscript expression.
2145 /// By default, performs semantic analysis to build the new expression.
2146 /// Subclasses may override this routine to provide different behavior.
2147 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2148 SourceLocation LBracketLoc,
2150 SourceLocation RBracketLoc) {
2151 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2156 /// \brief Build a new array section expression.
2158 /// By default, performs semantic analysis to build the new expression.
2159 /// Subclasses may override this routine to provide different behavior.
2160 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2162 SourceLocation ColonLoc, Expr *Length,
2163 SourceLocation RBracketLoc) {
2164 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2165 ColonLoc, Length, RBracketLoc);
2168 /// \brief Build a new call expression.
2170 /// By default, performs semantic analysis to build the new expression.
2171 /// Subclasses may override this routine to provide different behavior.
2172 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2174 SourceLocation RParenLoc,
2175 Expr *ExecConfig = nullptr) {
2176 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
2177 Args, RParenLoc, ExecConfig);
2180 /// \brief Build a new member access expression.
2182 /// By default, performs semantic analysis to build the new expression.
2183 /// Subclasses may override this routine to provide different behavior.
2184 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2186 NestedNameSpecifierLoc QualifierLoc,
2187 SourceLocation TemplateKWLoc,
2188 const DeclarationNameInfo &MemberNameInfo,
2190 NamedDecl *FoundDecl,
2191 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2192 NamedDecl *FirstQualifierInScope) {
2193 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2195 if (!Member->getDeclName()) {
2196 // We have a reference to an unnamed field. This is always the
2197 // base of an anonymous struct/union member access, i.e. the
2198 // field is always of record type.
2199 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
2200 assert(Member->getType()->isRecordType() &&
2201 "unnamed member not of record type?");
2204 getSema().PerformObjectMemberConversion(BaseResult.get(),
2205 QualifierLoc.getNestedNameSpecifier(),
2207 if (BaseResult.isInvalid())
2209 Base = BaseResult.get();
2210 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
2211 MemberExpr *ME = new (getSema().Context)
2212 MemberExpr(Base, isArrow, OpLoc, Member, MemberNameInfo,
2213 cast<FieldDecl>(Member)->getType(), VK, OK_Ordinary);
2218 SS.Adopt(QualifierLoc);
2220 Base = BaseResult.get();
2221 QualType BaseType = Base->getType();
2223 if (isArrow && !BaseType->isPointerType())
2226 // FIXME: this involves duplicating earlier analysis in a lot of
2227 // cases; we should avoid this when possible.
2228 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2229 R.addDecl(FoundDecl);
2232 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2234 FirstQualifierInScope,
2235 R, ExplicitTemplateArgs,
2239 /// \brief Build a new binary operator expression.
2241 /// By default, performs semantic analysis to build the new expression.
2242 /// Subclasses may override this routine to provide different behavior.
2243 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2244 BinaryOperatorKind Opc,
2245 Expr *LHS, Expr *RHS) {
2246 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2249 /// \brief Build a new conditional operator expression.
2251 /// By default, performs semantic analysis to build the new expression.
2252 /// Subclasses may override this routine to provide different behavior.
2253 ExprResult RebuildConditionalOperator(Expr *Cond,
2254 SourceLocation QuestionLoc,
2256 SourceLocation ColonLoc,
2258 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2262 /// \brief Build a new C-style cast expression.
2264 /// By default, performs semantic analysis to build the new expression.
2265 /// Subclasses may override this routine to provide different behavior.
2266 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2267 TypeSourceInfo *TInfo,
2268 SourceLocation RParenLoc,
2270 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2274 /// \brief Build a new compound literal expression.
2276 /// By default, performs semantic analysis to build the new expression.
2277 /// Subclasses may override this routine to provide different behavior.
2278 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2279 TypeSourceInfo *TInfo,
2280 SourceLocation RParenLoc,
2282 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2286 /// \brief Build a new extended vector element access expression.
2288 /// By default, performs semantic analysis to build the new expression.
2289 /// Subclasses may override this routine to provide different behavior.
2290 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2291 SourceLocation OpLoc,
2292 SourceLocation AccessorLoc,
2293 IdentifierInfo &Accessor) {
2296 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2297 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2298 OpLoc, /*IsArrow*/ false,
2299 SS, SourceLocation(),
2300 /*FirstQualifierInScope*/ nullptr,
2302 /* TemplateArgs */ nullptr,
2306 /// \brief Build a new initializer list expression.
2308 /// By default, performs semantic analysis to build the new expression.
2309 /// Subclasses may override this routine to provide different behavior.
2310 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2312 SourceLocation RBraceLoc,
2313 QualType ResultTy) {
2315 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
2316 if (Result.isInvalid() || ResultTy->isDependentType())
2319 // Patch in the result type we were given, which may have been computed
2320 // when the initial InitListExpr was built.
2321 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
2322 ILE->setType(ResultTy);
2326 /// \brief Build a new designated initializer expression.
2328 /// By default, performs semantic analysis to build the new expression.
2329 /// Subclasses may override this routine to provide different behavior.
2330 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2331 MultiExprArg ArrayExprs,
2332 SourceLocation EqualOrColonLoc,
2336 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2338 if (Result.isInvalid())
2344 /// \brief Build a new value-initialized expression.
2346 /// By default, builds the implicit value initialization without performing
2347 /// any semantic analysis. Subclasses may override this routine to provide
2348 /// different behavior.
2349 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2350 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2353 /// \brief Build a new \c va_arg expression.
2355 /// By default, performs semantic analysis to build the new expression.
2356 /// Subclasses may override this routine to provide different behavior.
2357 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2358 Expr *SubExpr, TypeSourceInfo *TInfo,
2359 SourceLocation RParenLoc) {
2360 return getSema().BuildVAArgExpr(BuiltinLoc,
2365 /// \brief Build a new expression list in parentheses.
2367 /// By default, performs semantic analysis to build the new expression.
2368 /// Subclasses may override this routine to provide different behavior.
2369 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2370 MultiExprArg SubExprs,
2371 SourceLocation RParenLoc) {
2372 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2375 /// \brief Build a new address-of-label expression.
2377 /// By default, performs semantic analysis, using the name of the label
2378 /// rather than attempting to map the label statement itself.
2379 /// Subclasses may override this routine to provide different behavior.
2380 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2381 SourceLocation LabelLoc, LabelDecl *Label) {
2382 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2385 /// \brief Build a new GNU statement expression.
2387 /// By default, performs semantic analysis to build the new expression.
2388 /// Subclasses may override this routine to provide different behavior.
2389 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2391 SourceLocation RParenLoc) {
2392 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2395 /// \brief Build a new __builtin_choose_expr expression.
2397 /// By default, performs semantic analysis to build the new expression.
2398 /// Subclasses may override this routine to provide different behavior.
2399 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2400 Expr *Cond, Expr *LHS, Expr *RHS,
2401 SourceLocation RParenLoc) {
2402 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2407 /// \brief Build a new generic selection expression.
2409 /// By default, performs semantic analysis to build the new expression.
2410 /// Subclasses may override this routine to provide different behavior.
2411 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2412 SourceLocation DefaultLoc,
2413 SourceLocation RParenLoc,
2414 Expr *ControllingExpr,
2415 ArrayRef<TypeSourceInfo *> Types,
2416 ArrayRef<Expr *> Exprs) {
2417 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2418 ControllingExpr, Types, Exprs);
2421 /// \brief Build a new overloaded operator call expression.
2423 /// By default, performs semantic analysis to build the new expression.
2424 /// The semantic analysis provides the behavior of template instantiation,
2425 /// copying with transformations that turn what looks like an overloaded
2426 /// operator call into a use of a builtin operator, performing
2427 /// argument-dependent lookup, etc. Subclasses may override this routine to
2428 /// provide different behavior.
2429 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2430 SourceLocation OpLoc,
2435 /// \brief Build a new C++ "named" cast expression, such as static_cast or
2436 /// reinterpret_cast.
2438 /// By default, this routine dispatches to one of the more-specific routines
2439 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2440 /// Subclasses may override this routine to provide different behavior.
2441 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2442 Stmt::StmtClass Class,
2443 SourceLocation LAngleLoc,
2444 TypeSourceInfo *TInfo,
2445 SourceLocation RAngleLoc,
2446 SourceLocation LParenLoc,
2448 SourceLocation RParenLoc) {
2450 case Stmt::CXXStaticCastExprClass:
2451 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2452 RAngleLoc, LParenLoc,
2453 SubExpr, RParenLoc);
2455 case Stmt::CXXDynamicCastExprClass:
2456 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2457 RAngleLoc, LParenLoc,
2458 SubExpr, RParenLoc);
2460 case Stmt::CXXReinterpretCastExprClass:
2461 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2462 RAngleLoc, LParenLoc,
2466 case Stmt::CXXConstCastExprClass:
2467 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2468 RAngleLoc, LParenLoc,
2469 SubExpr, RParenLoc);
2472 llvm_unreachable("Invalid C++ named cast");
2476 /// \brief Build a new C++ static_cast expression.
2478 /// By default, performs semantic analysis to build the new expression.
2479 /// Subclasses may override this routine to provide different behavior.
2480 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2481 SourceLocation LAngleLoc,
2482 TypeSourceInfo *TInfo,
2483 SourceLocation RAngleLoc,
2484 SourceLocation LParenLoc,
2486 SourceLocation RParenLoc) {
2487 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2489 SourceRange(LAngleLoc, RAngleLoc),
2490 SourceRange(LParenLoc, RParenLoc));
2493 /// \brief Build a new C++ dynamic_cast expression.
2495 /// By default, performs semantic analysis to build the new expression.
2496 /// Subclasses may override this routine to provide different behavior.
2497 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2498 SourceLocation LAngleLoc,
2499 TypeSourceInfo *TInfo,
2500 SourceLocation RAngleLoc,
2501 SourceLocation LParenLoc,
2503 SourceLocation RParenLoc) {
2504 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2506 SourceRange(LAngleLoc, RAngleLoc),
2507 SourceRange(LParenLoc, RParenLoc));
2510 /// \brief Build a new C++ reinterpret_cast expression.
2512 /// By default, performs semantic analysis to build the new expression.
2513 /// Subclasses may override this routine to provide different behavior.
2514 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2515 SourceLocation LAngleLoc,
2516 TypeSourceInfo *TInfo,
2517 SourceLocation RAngleLoc,
2518 SourceLocation LParenLoc,
2520 SourceLocation RParenLoc) {
2521 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2523 SourceRange(LAngleLoc, RAngleLoc),
2524 SourceRange(LParenLoc, RParenLoc));
2527 /// \brief Build a new C++ const_cast expression.
2529 /// By default, performs semantic analysis to build the new expression.
2530 /// Subclasses may override this routine to provide different behavior.
2531 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2532 SourceLocation LAngleLoc,
2533 TypeSourceInfo *TInfo,
2534 SourceLocation RAngleLoc,
2535 SourceLocation LParenLoc,
2537 SourceLocation RParenLoc) {
2538 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2540 SourceRange(LAngleLoc, RAngleLoc),
2541 SourceRange(LParenLoc, RParenLoc));
2544 /// \brief Build a new C++ functional-style cast expression.
2546 /// By default, performs semantic analysis to build the new expression.
2547 /// Subclasses may override this routine to provide different behavior.
2548 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2549 SourceLocation LParenLoc,
2551 SourceLocation RParenLoc) {
2552 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2553 MultiExprArg(&Sub, 1),
2557 /// \brief Build a new C++ typeid(type) expression.
2559 /// By default, performs semantic analysis to build the new expression.
2560 /// Subclasses may override this routine to provide different behavior.
2561 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2562 SourceLocation TypeidLoc,
2563 TypeSourceInfo *Operand,
2564 SourceLocation RParenLoc) {
2565 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2570 /// \brief Build a new C++ typeid(expr) expression.
2572 /// By default, performs semantic analysis to build the new expression.
2573 /// Subclasses may override this routine to provide different behavior.
2574 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2575 SourceLocation TypeidLoc,
2577 SourceLocation RParenLoc) {
2578 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2582 /// \brief Build a new C++ __uuidof(type) expression.
2584 /// By default, performs semantic analysis to build the new expression.
2585 /// Subclasses may override this routine to provide different behavior.
2586 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2587 SourceLocation TypeidLoc,
2588 TypeSourceInfo *Operand,
2589 SourceLocation RParenLoc) {
2590 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2594 /// \brief Build a new C++ __uuidof(expr) expression.
2596 /// By default, performs semantic analysis to build the new expression.
2597 /// Subclasses may override this routine to provide different behavior.
2598 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2599 SourceLocation TypeidLoc,
2601 SourceLocation RParenLoc) {
2602 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2606 /// \brief Build a new C++ "this" expression.
2608 /// By default, builds a new "this" expression without performing any
2609 /// semantic analysis. Subclasses may override this routine to provide
2610 /// different behavior.
2611 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2614 getSema().CheckCXXThisCapture(ThisLoc);
2615 return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2618 /// \brief Build a new C++ throw expression.
2620 /// By default, performs semantic analysis to build the new expression.
2621 /// Subclasses may override this routine to provide different behavior.
2622 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2623 bool IsThrownVariableInScope) {
2624 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2627 /// \brief Build a new C++ default-argument expression.
2629 /// By default, builds a new default-argument expression, which does not
2630 /// require any semantic analysis. Subclasses may override this routine to
2631 /// provide different behavior.
2632 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2633 ParmVarDecl *Param) {
2634 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2637 /// \brief Build a new C++11 default-initialization expression.
2639 /// By default, builds a new default field initialization expression, which
2640 /// does not require any semantic analysis. Subclasses may override this
2641 /// routine to provide different behavior.
2642 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2644 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2647 /// \brief Build a new C++ zero-initialization expression.
2649 /// By default, performs semantic analysis to build the new expression.
2650 /// Subclasses may override this routine to provide different behavior.
2651 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2652 SourceLocation LParenLoc,
2653 SourceLocation RParenLoc) {
2654 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
2658 /// \brief Build a new C++ "new" expression.
2660 /// By default, performs semantic analysis to build the new expression.
2661 /// Subclasses may override this routine to provide different behavior.
2662 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2664 SourceLocation PlacementLParen,
2665 MultiExprArg PlacementArgs,
2666 SourceLocation PlacementRParen,
2667 SourceRange TypeIdParens,
2668 QualType AllocatedType,
2669 TypeSourceInfo *AllocatedTypeInfo,
2671 SourceRange DirectInitRange,
2672 Expr *Initializer) {
2673 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2685 /// \brief Build a new C++ "delete" expression.
2687 /// By default, performs semantic analysis to build the new expression.
2688 /// Subclasses may override this routine to provide different behavior.
2689 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2690 bool IsGlobalDelete,
2693 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2697 /// \brief Build a new type trait expression.
2699 /// By default, performs semantic analysis to build the new expression.
2700 /// Subclasses may override this routine to provide different behavior.
2701 ExprResult RebuildTypeTrait(TypeTrait Trait,
2702 SourceLocation StartLoc,
2703 ArrayRef<TypeSourceInfo *> Args,
2704 SourceLocation RParenLoc) {
2705 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2708 /// \brief Build a new array type trait expression.
2710 /// By default, performs semantic analysis to build the new expression.
2711 /// Subclasses may override this routine to provide different behavior.
2712 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2713 SourceLocation StartLoc,
2714 TypeSourceInfo *TSInfo,
2716 SourceLocation RParenLoc) {
2717 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2720 /// \brief Build a new expression trait expression.
2722 /// By default, performs semantic analysis to build the new expression.
2723 /// Subclasses may override this routine to provide different behavior.
2724 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2725 SourceLocation StartLoc,
2727 SourceLocation RParenLoc) {
2728 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2731 /// \brief Build a new (previously unresolved) declaration reference
2734 /// By default, performs semantic analysis to build the new expression.
2735 /// Subclasses may override this routine to provide different behavior.
2736 ExprResult RebuildDependentScopeDeclRefExpr(
2737 NestedNameSpecifierLoc QualifierLoc,
2738 SourceLocation TemplateKWLoc,
2739 const DeclarationNameInfo &NameInfo,
2740 const TemplateArgumentListInfo *TemplateArgs,
2741 bool IsAddressOfOperand,
2742 TypeSourceInfo **RecoveryTSI) {
2744 SS.Adopt(QualifierLoc);
2746 if (TemplateArgs || TemplateKWLoc.isValid())
2747 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2750 return getSema().BuildQualifiedDeclarationNameExpr(
2751 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2754 /// \brief Build a new template-id expression.
2756 /// By default, performs semantic analysis to build the new expression.
2757 /// Subclasses may override this routine to provide different behavior.
2758 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2759 SourceLocation TemplateKWLoc,
2762 const TemplateArgumentListInfo *TemplateArgs) {
2763 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2767 /// \brief Build a new object-construction expression.
2769 /// By default, performs semantic analysis to build the new expression.
2770 /// Subclasses may override this routine to provide different behavior.
2771 ExprResult RebuildCXXConstructExpr(QualType T,
2773 CXXConstructorDecl *Constructor,
2776 bool HadMultipleCandidates,
2777 bool ListInitialization,
2778 bool StdInitListInitialization,
2779 bool RequiresZeroInit,
2780 CXXConstructExpr::ConstructionKind ConstructKind,
2781 SourceRange ParenRange) {
2782 SmallVector<Expr*, 8> ConvertedArgs;
2783 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2787 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2790 HadMultipleCandidates,
2792 StdInitListInitialization,
2793 RequiresZeroInit, ConstructKind,
2797 /// \brief Build a new implicit construction via inherited constructor
2799 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2800 CXXConstructorDecl *Constructor,
2801 bool ConstructsVBase,
2802 bool InheritedFromVBase) {
2803 return new (getSema().Context) CXXInheritedCtorInitExpr(
2804 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2807 /// \brief Build a new object-construction expression.
2809 /// By default, performs semantic analysis to build the new expression.
2810 /// Subclasses may override this routine to provide different behavior.
2811 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2812 SourceLocation LParenLoc,
2814 SourceLocation RParenLoc) {
2815 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2821 /// \brief Build a new object-construction expression.
2823 /// By default, performs semantic analysis to build the new expression.
2824 /// Subclasses may override this routine to provide different behavior.
2825 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2826 SourceLocation LParenLoc,
2828 SourceLocation RParenLoc) {
2829 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2835 /// \brief Build a new member reference expression.
2837 /// By default, performs semantic analysis to build the new expression.
2838 /// Subclasses may override this routine to provide different behavior.
2839 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2842 SourceLocation OperatorLoc,
2843 NestedNameSpecifierLoc QualifierLoc,
2844 SourceLocation TemplateKWLoc,
2845 NamedDecl *FirstQualifierInScope,
2846 const DeclarationNameInfo &MemberNameInfo,
2847 const TemplateArgumentListInfo *TemplateArgs) {
2849 SS.Adopt(QualifierLoc);
2851 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2852 OperatorLoc, IsArrow,
2854 FirstQualifierInScope,
2856 TemplateArgs, /*S*/nullptr);
2859 /// \brief Build a new member reference expression.
2861 /// By default, performs semantic analysis to build the new expression.
2862 /// Subclasses may override this routine to provide different behavior.
2863 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2864 SourceLocation OperatorLoc,
2866 NestedNameSpecifierLoc QualifierLoc,
2867 SourceLocation TemplateKWLoc,
2868 NamedDecl *FirstQualifierInScope,
2870 const TemplateArgumentListInfo *TemplateArgs) {
2872 SS.Adopt(QualifierLoc);
2874 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2875 OperatorLoc, IsArrow,
2877 FirstQualifierInScope,
2878 R, TemplateArgs, /*S*/nullptr);
2881 /// \brief Build a new noexcept expression.
2883 /// By default, performs semantic analysis to build the new expression.
2884 /// Subclasses may override this routine to provide different behavior.
2885 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2886 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2889 /// \brief Build a new expression to compute the length of a parameter pack.
2890 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
2892 SourceLocation PackLoc,
2893 SourceLocation RParenLoc,
2894 Optional<unsigned> Length,
2895 ArrayRef<TemplateArgument> PartialArgs) {
2896 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
2897 RParenLoc, Length, PartialArgs);
2900 /// \brief Build a new Objective-C boxed expression.
2902 /// By default, performs semantic analysis to build the new expression.
2903 /// Subclasses may override this routine to provide different behavior.
2904 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2905 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2908 /// \brief Build a new Objective-C array literal.
2910 /// By default, performs semantic analysis to build the new expression.
2911 /// Subclasses may override this routine to provide different behavior.
2912 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2913 Expr **Elements, unsigned NumElements) {
2914 return getSema().BuildObjCArrayLiteral(Range,
2915 MultiExprArg(Elements, NumElements));
2918 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2919 Expr *Base, Expr *Key,
2920 ObjCMethodDecl *getterMethod,
2921 ObjCMethodDecl *setterMethod) {
2922 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2923 getterMethod, setterMethod);
2926 /// \brief Build a new Objective-C dictionary literal.
2928 /// By default, performs semantic analysis to build the new expression.
2929 /// Subclasses may override this routine to provide different behavior.
2930 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2931 MutableArrayRef<ObjCDictionaryElement> Elements) {
2932 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
2935 /// \brief Build a new Objective-C \@encode expression.
2937 /// By default, performs semantic analysis to build the new expression.
2938 /// Subclasses may override this routine to provide different behavior.
2939 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2940 TypeSourceInfo *EncodeTypeInfo,
2941 SourceLocation RParenLoc) {
2942 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2945 /// \brief Build a new Objective-C class message.
2946 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2948 ArrayRef<SourceLocation> SelectorLocs,
2949 ObjCMethodDecl *Method,
2950 SourceLocation LBracLoc,
2952 SourceLocation RBracLoc) {
2953 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2954 ReceiverTypeInfo->getType(),
2955 /*SuperLoc=*/SourceLocation(),
2956 Sel, Method, LBracLoc, SelectorLocs,
2960 /// \brief Build a new Objective-C instance message.
2961 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2963 ArrayRef<SourceLocation> SelectorLocs,
2964 ObjCMethodDecl *Method,
2965 SourceLocation LBracLoc,
2967 SourceLocation RBracLoc) {
2968 return SemaRef.BuildInstanceMessage(Receiver,
2969 Receiver->getType(),
2970 /*SuperLoc=*/SourceLocation(),
2971 Sel, Method, LBracLoc, SelectorLocs,
2975 /// \brief Build a new Objective-C instance/class message to 'super'.
2976 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
2978 ArrayRef<SourceLocation> SelectorLocs,
2980 ObjCMethodDecl *Method,
2981 SourceLocation LBracLoc,
2983 SourceLocation RBracLoc) {
2984 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
2987 Sel, Method, LBracLoc, SelectorLocs,
2989 : SemaRef.BuildClassMessage(nullptr,
2992 Sel, Method, LBracLoc, SelectorLocs,
2998 /// \brief Build a new Objective-C ivar reference expression.
3000 /// By default, performs semantic analysis to build the new expression.
3001 /// Subclasses may override this routine to provide different behavior.
3002 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3003 SourceLocation IvarLoc,
3004 bool IsArrow, bool IsFreeIvar) {
3006 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3007 ExprResult Result = getSema().BuildMemberReferenceExpr(
3008 BaseArg, BaseArg->getType(),
3009 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3010 /*FirstQualifierInScope=*/nullptr, NameInfo,
3011 /*TemplateArgs=*/nullptr,
3013 if (IsFreeIvar && Result.isUsable())
3014 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3018 /// \brief Build a new Objective-C property reference expression.
3020 /// By default, performs semantic analysis to build the new expression.
3021 /// Subclasses may override this routine to provide different behavior.
3022 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3023 ObjCPropertyDecl *Property,
3024 SourceLocation PropertyLoc) {
3026 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3027 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3028 /*FIXME:*/PropertyLoc,
3030 SS, SourceLocation(),
3031 /*FirstQualifierInScope=*/nullptr,
3033 /*TemplateArgs=*/nullptr,
3037 /// \brief Build a new Objective-C property reference expression.
3039 /// By default, performs semantic analysis to build the new expression.
3040 /// Subclasses may override this routine to provide different behavior.
3041 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3042 ObjCMethodDecl *Getter,
3043 ObjCMethodDecl *Setter,
3044 SourceLocation PropertyLoc) {
3045 // Since these expressions can only be value-dependent, we do not
3046 // need to perform semantic analysis again.
3048 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3049 VK_LValue, OK_ObjCProperty,
3050 PropertyLoc, Base));
3053 /// \brief Build a new Objective-C "isa" expression.
3055 /// By default, performs semantic analysis to build the new expression.
3056 /// Subclasses may override this routine to provide different behavior.
3057 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3058 SourceLocation OpLoc, bool IsArrow) {
3060 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3061 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3063 SS, SourceLocation(),
3064 /*FirstQualifierInScope=*/nullptr,
3066 /*TemplateArgs=*/nullptr,
3070 /// \brief Build a new shuffle vector expression.
3072 /// By default, performs semantic analysis to build the new expression.
3073 /// Subclasses may override this routine to provide different behavior.
3074 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3075 MultiExprArg SubExprs,
3076 SourceLocation RParenLoc) {
3077 // Find the declaration for __builtin_shufflevector
3078 const IdentifierInfo &Name
3079 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3080 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3081 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3082 assert(!Lookup.empty() && "No __builtin_shufflevector?");
3084 // Build a reference to the __builtin_shufflevector builtin
3085 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3086 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
3087 SemaRef.Context.BuiltinFnTy,
3088 VK_RValue, BuiltinLoc);
3089 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3090 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3091 CK_BuiltinFnToFnPtr).get();
3093 // Build the CallExpr
3094 ExprResult TheCall = new (SemaRef.Context) CallExpr(
3095 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3096 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3098 // Type-check the __builtin_shufflevector expression.
3099 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3102 /// \brief Build a new convert vector expression.
3103 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3104 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3105 SourceLocation RParenLoc) {
3106 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3107 BuiltinLoc, RParenLoc);
3110 /// \brief Build a new template argument pack expansion.
3112 /// By default, performs semantic analysis to build a new pack expansion
3113 /// for a template argument. Subclasses may override this routine to provide
3114 /// different behavior.
3115 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3116 SourceLocation EllipsisLoc,
3117 Optional<unsigned> NumExpansions) {
3118 switch (Pattern.getArgument().getKind()) {
3119 case TemplateArgument::Expression: {
3121 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3122 EllipsisLoc, NumExpansions);
3123 if (Result.isInvalid())
3124 return TemplateArgumentLoc();
3126 return TemplateArgumentLoc(Result.get(), Result.get());
3129 case TemplateArgument::Template:
3130 return TemplateArgumentLoc(TemplateArgument(
3131 Pattern.getArgument().getAsTemplate(),
3133 Pattern.getTemplateQualifierLoc(),
3134 Pattern.getTemplateNameLoc(),
3137 case TemplateArgument::Null:
3138 case TemplateArgument::Integral:
3139 case TemplateArgument::Declaration:
3140 case TemplateArgument::Pack:
3141 case TemplateArgument::TemplateExpansion:
3142 case TemplateArgument::NullPtr:
3143 llvm_unreachable("Pack expansion pattern has no parameter packs");
3145 case TemplateArgument::Type:
3146 if (TypeSourceInfo *Expansion
3147 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3150 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3155 return TemplateArgumentLoc();
3158 /// \brief Build a new expression pack expansion.
3160 /// By default, performs semantic analysis to build a new pack expansion
3161 /// for an expression. Subclasses may override this routine to provide
3162 /// different behavior.
3163 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3164 Optional<unsigned> NumExpansions) {
3165 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3168 /// \brief Build a new C++1z fold-expression.
3170 /// By default, performs semantic analysis in order to build a new fold
3172 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3173 BinaryOperatorKind Operator,
3174 SourceLocation EllipsisLoc, Expr *RHS,
3175 SourceLocation RParenLoc) {
3176 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3180 /// \brief Build an empty C++1z fold-expression with the given operator.
3182 /// By default, produces the fallback value for the fold-expression, or
3183 /// produce an error if there is no fallback value.
3184 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3185 BinaryOperatorKind Operator) {
3186 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3189 /// \brief Build a new atomic operation expression.
3191 /// By default, performs semantic analysis to build the new expression.
3192 /// Subclasses may override this routine to provide different behavior.
3193 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
3194 MultiExprArg SubExprs,
3196 AtomicExpr::AtomicOp Op,
3197 SourceLocation RParenLoc) {
3198 // Just create the expression; there is not any interesting semantic
3199 // analysis here because we can't actually build an AtomicExpr until
3200 // we are sure it is semantically sound.
3201 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
3206 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3207 QualType ObjectType,
3208 NamedDecl *FirstQualifierInScope,
3211 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3212 QualType ObjectType,
3213 NamedDecl *FirstQualifierInScope,
3216 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3217 NamedDecl *FirstQualifierInScope,
3220 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3221 DependentNameTypeLoc TL,
3222 bool DeducibleTSTContext);
3225 template<typename Derived>
3226 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
3230 switch (S->getStmtClass()) {
3231 case Stmt::NoStmtClass: break;
3233 // Transform individual statement nodes
3234 #define STMT(Node, Parent) \
3235 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3236 #define ABSTRACT_STMT(Node)
3237 #define EXPR(Node, Parent)
3238 #include "clang/AST/StmtNodes.inc"
3240 // Transform expressions by calling TransformExpr.
3241 #define STMT(Node, Parent)
3242 #define ABSTRACT_STMT(Stmt)
3243 #define EXPR(Node, Parent) case Stmt::Node##Class:
3244 #include "clang/AST/StmtNodes.inc"
3246 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3250 return getSema().ActOnExprStmt(E);
3257 template<typename Derived>
3258 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3262 switch (S->getClauseKind()) {
3264 // Transform individual clause nodes
3265 #define OPENMP_CLAUSE(Name, Class) \
3266 case OMPC_ ## Name : \
3267 return getDerived().Transform ## Class(cast<Class>(S));
3268 #include "clang/Basic/OpenMPKinds.def"
3275 template<typename Derived>
3276 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3280 switch (E->getStmtClass()) {
3281 case Stmt::NoStmtClass: break;
3282 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3283 #define ABSTRACT_STMT(Stmt)
3284 #define EXPR(Node, Parent) \
3285 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3286 #include "clang/AST/StmtNodes.inc"
3292 template<typename Derived>
3293 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3295 // Initializers are instantiated like expressions, except that various outer
3296 // layers are stripped.
3300 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
3301 Init = ExprTemp->getSubExpr();
3303 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3304 Init = AIL->getCommonExpr();
3306 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3307 Init = MTE->GetTemporaryExpr();
3309 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3310 Init = Binder->getSubExpr();
3312 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3313 Init = ICE->getSubExprAsWritten();
3315 if (CXXStdInitializerListExpr *ILE =
3316 dyn_cast<CXXStdInitializerListExpr>(Init))
3317 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3319 // If this is copy-initialization, we only need to reconstruct
3320 // InitListExprs. Other forms of copy-initialization will be a no-op if
3321 // the initializer is already the right type.
3322 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3323 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3324 return getDerived().TransformExpr(Init);
3326 // Revert value-initialization back to empty parens.
3327 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3328 SourceRange Parens = VIE->getSourceRange();
3329 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3333 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3334 if (isa<ImplicitValueInitExpr>(Init))
3335 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3338 // Revert initialization by constructor back to a parenthesized or braced list
3339 // of expressions. Any other form of initializer can just be reused directly.
3340 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3341 return getDerived().TransformExpr(Init);
3343 // If the initialization implicitly converted an initializer list to a
3344 // std::initializer_list object, unwrap the std::initializer_list too.
3345 if (Construct && Construct->isStdInitListInitialization())
3346 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3348 SmallVector<Expr*, 8> NewArgs;
3349 bool ArgChanged = false;
3350 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3351 /*IsCall*/true, NewArgs, &ArgChanged))
3354 // If this was list initialization, revert to list form.
3355 if (Construct->isListInitialization())
3356 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
3357 Construct->getLocEnd(),
3358 Construct->getType());
3360 // Build a ParenListExpr to represent anything else.
3361 SourceRange Parens = Construct->getParenOrBraceRange();
3362 if (Parens.isInvalid()) {
3363 // This was a variable declaration's initialization for which no initializer
3365 assert(NewArgs.empty() &&
3366 "no parens or braces but have direct init with arguments?");
3369 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3373 template<typename Derived>
3374 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3377 SmallVectorImpl<Expr *> &Outputs,
3379 for (unsigned I = 0; I != NumInputs; ++I) {
3380 // If requested, drop call arguments that need to be dropped.
3381 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3388 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3389 Expr *Pattern = Expansion->getPattern();
3391 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3392 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3393 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3395 // Determine whether the set of unexpanded parameter packs can and should
3398 bool RetainExpansion = false;
3399 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3400 Optional<unsigned> NumExpansions = OrigNumExpansions;
3401 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3402 Pattern->getSourceRange(),
3404 Expand, RetainExpansion,
3409 // The transform has determined that we should perform a simple
3410 // transformation on the pack expansion, producing another pack
3412 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3413 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3414 if (OutPattern.isInvalid())
3417 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3418 Expansion->getEllipsisLoc(),
3420 if (Out.isInvalid())
3425 Outputs.push_back(Out.get());
3429 // Record right away that the argument was changed. This needs
3430 // to happen even if the array expands to nothing.
3431 if (ArgChanged) *ArgChanged = true;
3433 // The transform has determined that we should perform an elementwise
3434 // expansion of the pattern. Do so.
3435 for (unsigned I = 0; I != *NumExpansions; ++I) {
3436 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3437 ExprResult Out = getDerived().TransformExpr(Pattern);
3438 if (Out.isInvalid())
3441 if (Out.get()->containsUnexpandedParameterPack()) {
3442 Out = getDerived().RebuildPackExpansion(
3443 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3444 if (Out.isInvalid())
3448 Outputs.push_back(Out.get());
3451 // If we're supposed to retain a pack expansion, do so by temporarily
3452 // forgetting the partially-substituted parameter pack.
3453 if (RetainExpansion) {
3454 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3456 ExprResult Out = getDerived().TransformExpr(Pattern);
3457 if (Out.isInvalid())
3460 Out = getDerived().RebuildPackExpansion(
3461 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3462 if (Out.isInvalid())
3465 Outputs.push_back(Out.get());
3472 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3473 : getDerived().TransformExpr(Inputs[I]);
3474 if (Result.isInvalid())
3477 if (Result.get() != Inputs[I] && ArgChanged)
3480 Outputs.push_back(Result.get());
3486 template <typename Derived>
3487 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3488 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3490 VarDecl *ConditionVar = cast_or_null<VarDecl>(
3491 getDerived().TransformDefinition(Var->getLocation(), Var));
3494 return Sema::ConditionError();
3496 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3500 ExprResult CondExpr = getDerived().TransformExpr(Expr);
3502 if (CondExpr.isInvalid())
3503 return Sema::ConditionError();
3505 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3508 return Sema::ConditionResult();
3511 template<typename Derived>
3512 NestedNameSpecifierLoc
3513 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3514 NestedNameSpecifierLoc NNS,
3515 QualType ObjectType,
3516 NamedDecl *FirstQualifierInScope) {
3517 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3518 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3519 Qualifier = Qualifier.getPrefix())
3520 Qualifiers.push_back(Qualifier);
3523 while (!Qualifiers.empty()) {
3524 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3525 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3527 switch (QNNS->getKind()) {
3528 case NestedNameSpecifier::Identifier: {
3529 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3530 Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3531 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3532 SS, FirstQualifierInScope, false))
3533 return NestedNameSpecifierLoc();
3537 case NestedNameSpecifier::Namespace: {
3539 = cast_or_null<NamespaceDecl>(
3540 getDerived().TransformDecl(
3541 Q.getLocalBeginLoc(),
3542 QNNS->getAsNamespace()));
3543 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3547 case NestedNameSpecifier::NamespaceAlias: {
3548 NamespaceAliasDecl *Alias
3549 = cast_or_null<NamespaceAliasDecl>(
3550 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3551 QNNS->getAsNamespaceAlias()));
3552 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3553 Q.getLocalEndLoc());
3557 case NestedNameSpecifier::Global:
3558 // There is no meaningful transformation that one could perform on the
3560 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3563 case NestedNameSpecifier::Super: {
3565 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3566 SourceLocation(), QNNS->getAsRecordDecl()));
3567 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3571 case NestedNameSpecifier::TypeSpecWithTemplate:
3572 case NestedNameSpecifier::TypeSpec: {
3573 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3574 FirstQualifierInScope, SS);
3577 return NestedNameSpecifierLoc();
3579 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3580 (SemaRef.getLangOpts().CPlusPlus11 &&
3581 TL.getType()->isEnumeralType())) {
3582 assert(!TL.getType().hasLocalQualifiers() &&
3583 "Can't get cv-qualifiers here");
3584 if (TL.getType()->isEnumeralType())
3585 SemaRef.Diag(TL.getBeginLoc(),
3586 diag::warn_cxx98_compat_enum_nested_name_spec);
3587 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3588 Q.getLocalEndLoc());
3591 // If the nested-name-specifier is an invalid type def, don't emit an
3592 // error because a previous error should have already been emitted.
3593 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3594 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3595 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3596 << TL.getType() << SS.getRange();
3598 return NestedNameSpecifierLoc();
3602 // The qualifier-in-scope and object type only apply to the leftmost entity.
3603 FirstQualifierInScope = nullptr;
3604 ObjectType = QualType();
3607 // Don't rebuild the nested-name-specifier if we don't have to.
3608 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3609 !getDerived().AlwaysRebuild())
3612 // If we can re-use the source-location data from the original
3613 // nested-name-specifier, do so.
3614 if (SS.location_size() == NNS.getDataLength() &&
3615 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3616 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3618 // Allocate new nested-name-specifier location information.
3619 return SS.getWithLocInContext(SemaRef.Context);
3622 template<typename Derived>
3624 TreeTransform<Derived>
3625 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3626 DeclarationName Name = NameInfo.getName();
3628 return DeclarationNameInfo();
3630 switch (Name.getNameKind()) {
3631 case DeclarationName::Identifier:
3632 case DeclarationName::ObjCZeroArgSelector:
3633 case DeclarationName::ObjCOneArgSelector:
3634 case DeclarationName::ObjCMultiArgSelector:
3635 case DeclarationName::CXXOperatorName:
3636 case DeclarationName::CXXLiteralOperatorName:
3637 case DeclarationName::CXXUsingDirective:
3640 case DeclarationName::CXXDeductionGuideName: {
3641 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3642 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3643 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3645 return DeclarationNameInfo();
3647 DeclarationNameInfo NewNameInfo(NameInfo);
3648 NewNameInfo.setName(
3649 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3653 case DeclarationName::CXXConstructorName:
3654 case DeclarationName::CXXDestructorName:
3655 case DeclarationName::CXXConversionFunctionName: {
3656 TypeSourceInfo *NewTInfo;
3657 CanQualType NewCanTy;
3658 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3659 NewTInfo = getDerived().TransformType(OldTInfo);
3661 return DeclarationNameInfo();
3662 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3666 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3667 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3669 return DeclarationNameInfo();
3670 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3673 DeclarationName NewName
3674 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3676 DeclarationNameInfo NewNameInfo(NameInfo);
3677 NewNameInfo.setName(NewName);
3678 NewNameInfo.setNamedTypeInfo(NewTInfo);
3683 llvm_unreachable("Unknown name kind.");
3686 template<typename Derived>
3688 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3690 SourceLocation NameLoc,
3691 QualType ObjectType,
3692 NamedDecl *FirstQualifierInScope,
3693 bool AllowInjectedClassName) {
3694 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3695 TemplateDecl *Template = QTN->getTemplateDecl();
3696 assert(Template && "qualified template name must refer to a template");
3698 TemplateDecl *TransTemplate
3699 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3702 return TemplateName();
3704 if (!getDerived().AlwaysRebuild() &&
3705 SS.getScopeRep() == QTN->getQualifier() &&
3706 TransTemplate == Template)
3709 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3713 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3714 if (SS.getScopeRep()) {
3715 // These apply to the scope specifier, not the template.
3716 ObjectType = QualType();
3717 FirstQualifierInScope = nullptr;
3720 if (!getDerived().AlwaysRebuild() &&
3721 SS.getScopeRep() == DTN->getQualifier() &&
3722 ObjectType.isNull())
3725 if (DTN->isIdentifier()) {
3726 return getDerived().RebuildTemplateName(SS,
3727 *DTN->getIdentifier(),
3730 FirstQualifierInScope,
3731 AllowInjectedClassName);
3734 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
3735 ObjectType, AllowInjectedClassName);
3738 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3739 TemplateDecl *TransTemplate
3740 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3743 return TemplateName();
3745 if (!getDerived().AlwaysRebuild() &&
3746 TransTemplate == Template)
3749 return TemplateName(TransTemplate);
3752 if (SubstTemplateTemplateParmPackStorage *SubstPack
3753 = Name.getAsSubstTemplateTemplateParmPack()) {
3754 TemplateTemplateParmDecl *TransParam
3755 = cast_or_null<TemplateTemplateParmDecl>(
3756 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3758 return TemplateName();
3760 if (!getDerived().AlwaysRebuild() &&
3761 TransParam == SubstPack->getParameterPack())
3764 return getDerived().RebuildTemplateName(TransParam,
3765 SubstPack->getArgumentPack());
3768 // These should be getting filtered out before they reach the AST.
3769 llvm_unreachable("overloaded function decl survived to here");
3772 template<typename Derived>
3773 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3774 const TemplateArgument &Arg,
3775 TemplateArgumentLoc &Output) {
3776 SourceLocation Loc = getDerived().getBaseLocation();
3777 switch (Arg.getKind()) {
3778 case TemplateArgument::Null:
3779 llvm_unreachable("null template argument in TreeTransform");
3782 case TemplateArgument::Type:
3783 Output = TemplateArgumentLoc(Arg,
3784 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3788 case TemplateArgument::Template:
3789 case TemplateArgument::TemplateExpansion: {
3790 NestedNameSpecifierLocBuilder Builder;
3791 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3792 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3793 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3794 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3795 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3797 if (Arg.getKind() == TemplateArgument::Template)
3798 Output = TemplateArgumentLoc(Arg,
3799 Builder.getWithLocInContext(SemaRef.Context),
3802 Output = TemplateArgumentLoc(Arg,
3803 Builder.getWithLocInContext(SemaRef.Context),
3809 case TemplateArgument::Expression:
3810 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3813 case TemplateArgument::Declaration:
3814 case TemplateArgument::Integral:
3815 case TemplateArgument::Pack:
3816 case TemplateArgument::NullPtr:
3817 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3822 template<typename Derived>
3823 bool TreeTransform<Derived>::TransformTemplateArgument(
3824 const TemplateArgumentLoc &Input,
3825 TemplateArgumentLoc &Output, bool Uneval) {
3826 const TemplateArgument &Arg = Input.getArgument();
3827 switch (Arg.getKind()) {
3828 case TemplateArgument::Null:
3829 case TemplateArgument::Integral:
3830 case TemplateArgument::Pack:
3831 case TemplateArgument::Declaration:
3832 case TemplateArgument::NullPtr:
3833 llvm_unreachable("Unexpected TemplateArgument");
3835 case TemplateArgument::Type: {
3836 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3838 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3840 DI = getDerived().TransformType(DI);
3841 if (!DI) return true;
3843 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3847 case TemplateArgument::Template: {
3848 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3850 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3856 SS.Adopt(QualifierLoc);
3857 TemplateName Template
3858 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3859 Input.getTemplateNameLoc());
3860 if (Template.isNull())
3863 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3864 Input.getTemplateNameLoc());
3868 case TemplateArgument::TemplateExpansion:
3869 llvm_unreachable("Caller should expand pack expansions");
3871 case TemplateArgument::Expression: {
3872 // Template argument expressions are constant expressions.
3873 EnterExpressionEvaluationContext Unevaluated(
3875 ? Sema::ExpressionEvaluationContext::Unevaluated
3876 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
3878 Expr *InputExpr = Input.getSourceExpression();
3879 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3881 ExprResult E = getDerived().TransformExpr(InputExpr);
3882 E = SemaRef.ActOnConstantExpression(E);
3883 if (E.isInvalid()) return true;
3884 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3889 // Work around bogus GCC warning
3893 /// \brief Iterator adaptor that invents template argument location information
3894 /// for each of the template arguments in its underlying iterator.
3895 template<typename Derived, typename InputIterator>
3896 class TemplateArgumentLocInventIterator {
3897 TreeTransform<Derived> &Self;
3901 typedef TemplateArgumentLoc value_type;
3902 typedef TemplateArgumentLoc reference;
3903 typedef typename std::iterator_traits<InputIterator>::difference_type
3905 typedef std::input_iterator_tag iterator_category;
3908 TemplateArgumentLoc Arg;
3911 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3913 const TemplateArgumentLoc *operator->() const { return &Arg; }
3916 TemplateArgumentLocInventIterator() { }
3918 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3920 : Self(Self), Iter(Iter) { }
3922 TemplateArgumentLocInventIterator &operator++() {
3927 TemplateArgumentLocInventIterator operator++(int) {
3928 TemplateArgumentLocInventIterator Old(*this);
3933 reference operator*() const {
3934 TemplateArgumentLoc Result;
3935 Self.InventTemplateArgumentLoc(*Iter, Result);
3939 pointer operator->() const { return pointer(**this); }
3941 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3942 const TemplateArgumentLocInventIterator &Y) {
3943 return X.Iter == Y.Iter;
3946 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3947 const TemplateArgumentLocInventIterator &Y) {
3948 return X.Iter != Y.Iter;
3952 template<typename Derived>
3953 template<typename InputIterator>
3954 bool TreeTransform<Derived>::TransformTemplateArguments(
3955 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
3957 for (; First != Last; ++First) {
3958 TemplateArgumentLoc Out;
3959 TemplateArgumentLoc In = *First;
3961 if (In.getArgument().getKind() == TemplateArgument::Pack) {
3962 // Unpack argument packs, which we translate them into separate
3964 // FIXME: We could do much better if we could guarantee that the
3965 // TemplateArgumentLocInfo for the pack expansion would be usable for
3966 // all of the template arguments in the argument pack.
3967 typedef TemplateArgumentLocInventIterator<Derived,
3968 TemplateArgument::pack_iterator>
3970 if (TransformTemplateArguments(PackLocIterator(*this,
3971 In.getArgument().pack_begin()),
3972 PackLocIterator(*this,
3973 In.getArgument().pack_end()),
3980 if (In.getArgument().isPackExpansion()) {
3981 // We have a pack expansion, for which we will be substituting into
3983 SourceLocation Ellipsis;
3984 Optional<unsigned> OrigNumExpansions;
3985 TemplateArgumentLoc Pattern
3986 = getSema().getTemplateArgumentPackExpansionPattern(
3987 In, Ellipsis, OrigNumExpansions);
3989 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3990 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3991 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3993 // Determine whether the set of unexpanded parameter packs can and should
3996 bool RetainExpansion = false;
3997 Optional<unsigned> NumExpansions = OrigNumExpansions;
3998 if (getDerived().TryExpandParameterPacks(Ellipsis,
3999 Pattern.getSourceRange(),
4007 // The transform has determined that we should perform a simple
4008 // transformation on the pack expansion, producing another pack
4010 TemplateArgumentLoc OutPattern;
4011 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4012 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4015 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4017 if (Out.getArgument().isNull())
4020 Outputs.addArgument(Out);
4024 // The transform has determined that we should perform an elementwise
4025 // expansion of the pattern. Do so.
4026 for (unsigned I = 0; I != *NumExpansions; ++I) {
4027 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4029 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4032 if (Out.getArgument().containsUnexpandedParameterPack()) {
4033 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4035 if (Out.getArgument().isNull())
4039 Outputs.addArgument(Out);
4042 // If we're supposed to retain a pack expansion, do so by temporarily
4043 // forgetting the partially-substituted parameter pack.
4044 if (RetainExpansion) {
4045 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4047 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4050 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4052 if (Out.getArgument().isNull())
4055 Outputs.addArgument(Out);
4062 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4065 Outputs.addArgument(Out);
4072 //===----------------------------------------------------------------------===//
4073 // Type transformation
4074 //===----------------------------------------------------------------------===//
4076 template<typename Derived>
4077 QualType TreeTransform<Derived>::TransformType(QualType T) {
4078 if (getDerived().AlreadyTransformed(T))
4081 // Temporary workaround. All of these transformations should
4082 // eventually turn into transformations on TypeLocs.
4083 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4084 getDerived().getBaseLocation());
4086 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4091 return NewDI->getType();
4094 template<typename Derived>
4095 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4096 // Refine the base location to the type's location.
4097 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4098 getDerived().getBaseEntity());
4099 if (getDerived().AlreadyTransformed(DI->getType()))
4104 TypeLoc TL = DI->getTypeLoc();
4105 TLB.reserve(TL.getFullDataSize());
4107 QualType Result = getDerived().TransformType(TLB, TL);
4108 if (Result.isNull())
4111 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4114 template<typename Derived>
4116 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4117 switch (T.getTypeLocClass()) {
4118 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4119 #define TYPELOC(CLASS, PARENT) \
4120 case TypeLoc::CLASS: \
4121 return getDerived().Transform##CLASS##Type(TLB, \
4122 T.castAs<CLASS##TypeLoc>());
4123 #include "clang/AST/TypeLocNodes.def"
4126 llvm_unreachable("unhandled type loc!");
4129 template<typename Derived>
4130 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4131 if (!isa<DependentNameType>(T))
4132 return TransformType(T);
4134 if (getDerived().AlreadyTransformed(T))
4136 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4137 getDerived().getBaseLocation());
4138 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4139 return NewDI ? NewDI->getType() : QualType();
4142 template<typename Derived>
4144 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4145 if (!isa<DependentNameType>(DI->getType()))
4146 return TransformType(DI);
4148 // Refine the base location to the type's location.
4149 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4150 getDerived().getBaseEntity());
4151 if (getDerived().AlreadyTransformed(DI->getType()))
4156 TypeLoc TL = DI->getTypeLoc();
4157 TLB.reserve(TL.getFullDataSize());
4160 auto QTL = TL.getAs<QualifiedTypeLoc>();
4162 TL = QTL.getUnqualifiedLoc();
4164 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4166 QualType Result = getDerived().TransformDependentNameType(
4167 TLB, DNTL, /*DeducedTSTContext*/true);
4168 if (Result.isNull())
4172 Result = getDerived().RebuildQualifiedType(
4173 Result, QTL.getBeginLoc(), QTL.getType().getLocalQualifiers());
4174 TLB.TypeWasModifiedSafely(Result);
4177 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4180 template<typename Derived>
4182 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4183 QualifiedTypeLoc T) {
4184 Qualifiers Quals = T.getType().getLocalQualifiers();
4186 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4187 if (Result.isNull())
4190 Result = getDerived().RebuildQualifiedType(Result, T.getBeginLoc(), Quals);
4192 // RebuildQualifiedType might have updated the type, but not in a way
4193 // that invalidates the TypeLoc. (There's no location information for
4195 TLB.TypeWasModifiedSafely(Result);
4200 template<typename Derived>
4201 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4205 // [When] adding cv-qualifications on top of the function type [...] the
4206 // cv-qualifiers are ignored.
4208 // when the cv-qualifiers are introduced through the use of a typedef-name
4209 // or decltype-specifier [...] the cv-qualifiers are ignored.
4210 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4211 // applied to a reference type.
4212 // FIXME: This removes all qualifiers, not just cv-qualifiers!
4213 if (T->isFunctionType() || T->isReferenceType())
4216 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4218 if (Quals.hasObjCLifetime()) {
4219 if (!T->isObjCLifetimeType() && !T->isDependentType())
4220 Quals.removeObjCLifetime();
4221 else if (T.getObjCLifetime()) {
4223 // A lifetime qualifier applied to a substituted template parameter
4224 // overrides the lifetime qualifier from the template argument.
4225 const AutoType *AutoTy;
4226 if (const SubstTemplateTypeParmType *SubstTypeParam
4227 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4228 QualType Replacement = SubstTypeParam->getReplacementType();
4229 Qualifiers Qs = Replacement.getQualifiers();
4230 Qs.removeObjCLifetime();
4231 Replacement = SemaRef.Context.getQualifiedType(
4232 Replacement.getUnqualifiedType(), Qs);
4233 T = SemaRef.Context.getSubstTemplateTypeParmType(
4234 SubstTypeParam->getReplacedParameter(), Replacement);
4235 } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4236 // 'auto' types behave the same way as template parameters.
4237 QualType Deduced = AutoTy->getDeducedType();
4238 Qualifiers Qs = Deduced.getQualifiers();
4239 Qs.removeObjCLifetime();
4241 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4242 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4243 AutoTy->isDependentType());
4245 // Otherwise, complain about the addition of a qualifier to an
4246 // already-qualified type.
4247 // FIXME: Why is this check not in Sema::BuildQualifiedType?
4248 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4249 Quals.removeObjCLifetime();
4254 return SemaRef.BuildQualifiedType(T, Loc, Quals);
4257 template<typename Derived>
4259 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4260 QualType ObjectType,
4261 NamedDecl *UnqualLookup,
4263 if (getDerived().AlreadyTransformed(TL.getType()))
4266 TypeSourceInfo *TSI =
4267 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4269 return TSI->getTypeLoc();
4273 template<typename Derived>
4275 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4276 QualType ObjectType,
4277 NamedDecl *UnqualLookup,
4279 if (getDerived().AlreadyTransformed(TSInfo->getType()))
4282 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4286 template <typename Derived>
4287 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4288 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4290 QualType T = TL.getType();
4291 assert(!getDerived().AlreadyTransformed(T));
4296 if (isa<TemplateSpecializationType>(T)) {
4297 TemplateSpecializationTypeLoc SpecTL =
4298 TL.castAs<TemplateSpecializationTypeLoc>();
4300 TemplateName Template = getDerived().TransformTemplateName(
4301 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4302 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4303 if (Template.isNull())
4306 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4308 } else if (isa<DependentTemplateSpecializationType>(T)) {
4309 DependentTemplateSpecializationTypeLoc SpecTL =
4310 TL.castAs<DependentTemplateSpecializationTypeLoc>();
4312 TemplateName Template
4313 = getDerived().RebuildTemplateName(SS,
4314 *SpecTL.getTypePtr()->getIdentifier(),
4315 SpecTL.getTemplateNameLoc(),
4316 ObjectType, UnqualLookup,
4317 /*AllowInjectedClassName*/true);
4318 if (Template.isNull())
4321 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4326 // Nothing special needs to be done for these.
4327 Result = getDerived().TransformType(TLB, TL);
4330 if (Result.isNull())
4333 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4336 template <class TyLoc> static inline
4337 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4338 TyLoc NewT = TLB.push<TyLoc>(T.getType());
4339 NewT.setNameLoc(T.getNameLoc());
4343 template<typename Derived>
4344 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4346 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4347 NewT.setBuiltinLoc(T.getBuiltinLoc());
4348 if (T.needsExtraLocalData())
4349 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4353 template<typename Derived>
4354 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4357 return TransformTypeSpecType(TLB, T);
4360 template <typename Derived>
4361 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4362 AdjustedTypeLoc TL) {
4363 // Adjustments applied during transformation are handled elsewhere.
4364 return getDerived().TransformType(TLB, TL.getOriginalLoc());
4367 template<typename Derived>
4368 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4369 DecayedTypeLoc TL) {
4370 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4371 if (OriginalType.isNull())
4374 QualType Result = TL.getType();
4375 if (getDerived().AlwaysRebuild() ||
4376 OriginalType != TL.getOriginalLoc().getType())
4377 Result = SemaRef.Context.getDecayedType(OriginalType);
4378 TLB.push<DecayedTypeLoc>(Result);
4379 // Nothing to set for DecayedTypeLoc.
4383 template<typename Derived>
4384 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4385 PointerTypeLoc TL) {
4386 QualType PointeeType
4387 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4388 if (PointeeType.isNull())
4391 QualType Result = TL.getType();
4392 if (PointeeType->getAs<ObjCObjectType>()) {
4393 // A dependent pointer type 'T *' has is being transformed such
4394 // that an Objective-C class type is being replaced for 'T'. The
4395 // resulting pointer type is an ObjCObjectPointerType, not a
4397 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4399 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4400 NewT.setStarLoc(TL.getStarLoc());
4404 if (getDerived().AlwaysRebuild() ||
4405 PointeeType != TL.getPointeeLoc().getType()) {
4406 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4407 if (Result.isNull())
4411 // Objective-C ARC can add lifetime qualifiers to the type that we're
4413 TLB.TypeWasModifiedSafely(Result->getPointeeType());
4415 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4416 NewT.setSigilLoc(TL.getSigilLoc());
4420 template<typename Derived>
4422 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4423 BlockPointerTypeLoc TL) {
4424 QualType PointeeType
4425 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4426 if (PointeeType.isNull())
4429 QualType Result = TL.getType();
4430 if (getDerived().AlwaysRebuild() ||
4431 PointeeType != TL.getPointeeLoc().getType()) {
4432 Result = getDerived().RebuildBlockPointerType(PointeeType,
4434 if (Result.isNull())
4438 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4439 NewT.setSigilLoc(TL.getSigilLoc());
4443 /// Transforms a reference type. Note that somewhat paradoxically we
4444 /// don't care whether the type itself is an l-value type or an r-value
4445 /// type; we only care if the type was *written* as an l-value type
4446 /// or an r-value type.
4447 template<typename Derived>
4449 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4450 ReferenceTypeLoc TL) {
4451 const ReferenceType *T = TL.getTypePtr();
4453 // Note that this works with the pointee-as-written.
4454 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4455 if (PointeeType.isNull())
4458 QualType Result = TL.getType();
4459 if (getDerived().AlwaysRebuild() ||
4460 PointeeType != T->getPointeeTypeAsWritten()) {
4461 Result = getDerived().RebuildReferenceType(PointeeType,
4462 T->isSpelledAsLValue(),
4464 if (Result.isNull())
4468 // Objective-C ARC can add lifetime qualifiers to the type that we're
4470 TLB.TypeWasModifiedSafely(
4471 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4473 // r-value references can be rebuilt as l-value references.
4474 ReferenceTypeLoc NewTL;
4475 if (isa<LValueReferenceType>(Result))
4476 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4478 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4479 NewTL.setSigilLoc(TL.getSigilLoc());
4484 template<typename Derived>
4486 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4487 LValueReferenceTypeLoc TL) {
4488 return TransformReferenceType(TLB, TL);
4491 template<typename Derived>
4493 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4494 RValueReferenceTypeLoc TL) {
4495 return TransformReferenceType(TLB, TL);
4498 template<typename Derived>
4500 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4501 MemberPointerTypeLoc TL) {
4502 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4503 if (PointeeType.isNull())
4506 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4507 TypeSourceInfo *NewClsTInfo = nullptr;
4509 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4514 const MemberPointerType *T = TL.getTypePtr();
4515 QualType OldClsType = QualType(T->getClass(), 0);
4516 QualType NewClsType;
4518 NewClsType = NewClsTInfo->getType();
4520 NewClsType = getDerived().TransformType(OldClsType);
4521 if (NewClsType.isNull())
4525 QualType Result = TL.getType();
4526 if (getDerived().AlwaysRebuild() ||
4527 PointeeType != T->getPointeeType() ||
4528 NewClsType != OldClsType) {
4529 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4531 if (Result.isNull())
4535 // If we had to adjust the pointee type when building a member pointer, make
4536 // sure to push TypeLoc info for it.
4537 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4538 if (MPT && PointeeType != MPT->getPointeeType()) {
4539 assert(isa<AdjustedType>(MPT->getPointeeType()));
4540 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4543 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4544 NewTL.setSigilLoc(TL.getSigilLoc());
4545 NewTL.setClassTInfo(NewClsTInfo);
4550 template<typename Derived>
4552 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4553 ConstantArrayTypeLoc TL) {
4554 const ConstantArrayType *T = TL.getTypePtr();
4555 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4556 if (ElementType.isNull())
4559 QualType Result = TL.getType();
4560 if (getDerived().AlwaysRebuild() ||
4561 ElementType != T->getElementType()) {
4562 Result = getDerived().RebuildConstantArrayType(ElementType,
4563 T->getSizeModifier(),
4565 T->getIndexTypeCVRQualifiers(),
4566 TL.getBracketsRange());
4567 if (Result.isNull())
4571 // We might have either a ConstantArrayType or a VariableArrayType now:
4572 // a ConstantArrayType is allowed to have an element type which is a
4573 // VariableArrayType if the type is dependent. Fortunately, all array
4574 // types have the same location layout.
4575 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4576 NewTL.setLBracketLoc(TL.getLBracketLoc());
4577 NewTL.setRBracketLoc(TL.getRBracketLoc());
4579 Expr *Size = TL.getSizeExpr();
4581 EnterExpressionEvaluationContext Unevaluated(
4582 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4583 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4584 Size = SemaRef.ActOnConstantExpression(Size).get();
4586 NewTL.setSizeExpr(Size);
4591 template<typename Derived>
4592 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4593 TypeLocBuilder &TLB,
4594 IncompleteArrayTypeLoc TL) {
4595 const IncompleteArrayType *T = TL.getTypePtr();
4596 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4597 if (ElementType.isNull())
4600 QualType Result = TL.getType();
4601 if (getDerived().AlwaysRebuild() ||
4602 ElementType != T->getElementType()) {
4603 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4604 T->getSizeModifier(),
4605 T->getIndexTypeCVRQualifiers(),
4606 TL.getBracketsRange());
4607 if (Result.isNull())
4611 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4612 NewTL.setLBracketLoc(TL.getLBracketLoc());
4613 NewTL.setRBracketLoc(TL.getRBracketLoc());
4614 NewTL.setSizeExpr(nullptr);
4619 template<typename Derived>
4621 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4622 VariableArrayTypeLoc TL) {
4623 const VariableArrayType *T = TL.getTypePtr();
4624 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4625 if (ElementType.isNull())
4628 ExprResult SizeResult;
4630 EnterExpressionEvaluationContext Context(
4631 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4632 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4634 if (SizeResult.isInvalid())
4636 SizeResult = SemaRef.ActOnFinishFullExpr(SizeResult.get());
4637 if (SizeResult.isInvalid())
4640 Expr *Size = SizeResult.get();
4642 QualType Result = TL.getType();
4643 if (getDerived().AlwaysRebuild() ||
4644 ElementType != T->getElementType() ||
4645 Size != T->getSizeExpr()) {
4646 Result = getDerived().RebuildVariableArrayType(ElementType,
4647 T->getSizeModifier(),
4649 T->getIndexTypeCVRQualifiers(),
4650 TL.getBracketsRange());
4651 if (Result.isNull())
4655 // We might have constant size array now, but fortunately it has the same
4657 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4658 NewTL.setLBracketLoc(TL.getLBracketLoc());
4659 NewTL.setRBracketLoc(TL.getRBracketLoc());
4660 NewTL.setSizeExpr(Size);
4665 template<typename Derived>
4667 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4668 DependentSizedArrayTypeLoc TL) {
4669 const DependentSizedArrayType *T = TL.getTypePtr();
4670 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4671 if (ElementType.isNull())
4674 // Array bounds are constant expressions.
4675 EnterExpressionEvaluationContext Unevaluated(
4676 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4678 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4679 Expr *origSize = TL.getSizeExpr();
4680 if (!origSize) origSize = T->getSizeExpr();
4682 ExprResult sizeResult
4683 = getDerived().TransformExpr(origSize);
4684 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4685 if (sizeResult.isInvalid())
4688 Expr *size = sizeResult.get();
4690 QualType Result = TL.getType();
4691 if (getDerived().AlwaysRebuild() ||
4692 ElementType != T->getElementType() ||
4694 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4695 T->getSizeModifier(),
4697 T->getIndexTypeCVRQualifiers(),
4698 TL.getBracketsRange());
4699 if (Result.isNull())
4703 // We might have any sort of array type now, but fortunately they
4704 // all have the same location layout.
4705 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4706 NewTL.setLBracketLoc(TL.getLBracketLoc());
4707 NewTL.setRBracketLoc(TL.getRBracketLoc());
4708 NewTL.setSizeExpr(size);
4713 template<typename Derived>
4714 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4715 TypeLocBuilder &TLB,
4716 DependentSizedExtVectorTypeLoc TL) {
4717 const DependentSizedExtVectorType *T = TL.getTypePtr();
4719 // FIXME: ext vector locs should be nested
4720 QualType ElementType = getDerived().TransformType(T->getElementType());
4721 if (ElementType.isNull())
4724 // Vector sizes are constant expressions.
4725 EnterExpressionEvaluationContext Unevaluated(
4726 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4728 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4729 Size = SemaRef.ActOnConstantExpression(Size);
4730 if (Size.isInvalid())
4733 QualType Result = TL.getType();
4734 if (getDerived().AlwaysRebuild() ||
4735 ElementType != T->getElementType() ||
4736 Size.get() != T->getSizeExpr()) {
4737 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4739 T->getAttributeLoc());
4740 if (Result.isNull())
4744 // Result might be dependent or not.
4745 if (isa<DependentSizedExtVectorType>(Result)) {
4746 DependentSizedExtVectorTypeLoc NewTL
4747 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4748 NewTL.setNameLoc(TL.getNameLoc());
4750 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4751 NewTL.setNameLoc(TL.getNameLoc());
4757 template<typename Derived>
4758 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4760 const VectorType *T = TL.getTypePtr();
4761 QualType ElementType = getDerived().TransformType(T->getElementType());
4762 if (ElementType.isNull())
4765 QualType Result = TL.getType();
4766 if (getDerived().AlwaysRebuild() ||
4767 ElementType != T->getElementType()) {
4768 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
4769 T->getVectorKind());
4770 if (Result.isNull())
4774 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4775 NewTL.setNameLoc(TL.getNameLoc());
4780 template<typename Derived>
4781 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
4782 ExtVectorTypeLoc TL) {
4783 const VectorType *T = TL.getTypePtr();
4784 QualType ElementType = getDerived().TransformType(T->getElementType());
4785 if (ElementType.isNull())
4788 QualType Result = TL.getType();
4789 if (getDerived().AlwaysRebuild() ||
4790 ElementType != T->getElementType()) {
4791 Result = getDerived().RebuildExtVectorType(ElementType,
4792 T->getNumElements(),
4793 /*FIXME*/ SourceLocation());
4794 if (Result.isNull())
4798 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4799 NewTL.setNameLoc(TL.getNameLoc());
4804 template <typename Derived>
4805 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
4806 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
4807 bool ExpectParameterPack) {
4808 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
4809 TypeSourceInfo *NewDI = nullptr;
4811 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
4812 // If we're substituting into a pack expansion type and we know the
4813 // length we want to expand to, just substitute for the pattern.
4814 TypeLoc OldTL = OldDI->getTypeLoc();
4815 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4818 TypeLoc NewTL = OldDI->getTypeLoc();
4819 TLB.reserve(NewTL.getFullDataSize());
4821 QualType Result = getDerived().TransformType(TLB,
4822 OldExpansionTL.getPatternLoc());
4823 if (Result.isNull())
4826 Result = RebuildPackExpansionType(Result,
4827 OldExpansionTL.getPatternLoc().getSourceRange(),
4828 OldExpansionTL.getEllipsisLoc(),
4830 if (Result.isNull())
4833 PackExpansionTypeLoc NewExpansionTL
4834 = TLB.push<PackExpansionTypeLoc>(Result);
4835 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4836 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4838 NewDI = getDerived().TransformType(OldDI);
4842 if (NewDI == OldDI && indexAdjustment == 0)
4845 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4846 OldParm->getDeclContext(),
4847 OldParm->getInnerLocStart(),
4848 OldParm->getLocation(),
4849 OldParm->getIdentifier(),
4852 OldParm->getStorageClass(),
4853 /* DefArg */ nullptr);
4854 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4855 OldParm->getFunctionScopeIndex() + indexAdjustment);
4859 template <typename Derived>
4860 bool TreeTransform<Derived>::TransformFunctionTypeParams(
4861 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
4862 const QualType *ParamTypes,
4863 const FunctionProtoType::ExtParameterInfo *ParamInfos,
4864 SmallVectorImpl<QualType> &OutParamTypes,
4865 SmallVectorImpl<ParmVarDecl *> *PVars,
4866 Sema::ExtParameterInfoBuilder &PInfos) {
4867 int indexAdjustment = 0;
4869 unsigned NumParams = Params.size();
4870 for (unsigned i = 0; i != NumParams; ++i) {
4871 if (ParmVarDecl *OldParm = Params[i]) {
4872 assert(OldParm->getFunctionScopeIndex() == i);
4874 Optional<unsigned> NumExpansions;
4875 ParmVarDecl *NewParm = nullptr;
4876 if (OldParm->isParameterPack()) {
4877 // We have a function parameter pack that may need to be expanded.
4878 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4880 // Find the parameter packs that could be expanded.
4881 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4882 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4883 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4884 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4885 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4887 // Determine whether we should expand the parameter packs.
4888 bool ShouldExpand = false;
4889 bool RetainExpansion = false;
4890 Optional<unsigned> OrigNumExpansions =
4891 ExpansionTL.getTypePtr()->getNumExpansions();
4892 NumExpansions = OrigNumExpansions;
4893 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4894 Pattern.getSourceRange(),
4903 // Expand the function parameter pack into multiple, separate
4905 getDerived().ExpandingFunctionParameterPack(OldParm);
4906 for (unsigned I = 0; I != *NumExpansions; ++I) {
4907 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4908 ParmVarDecl *NewParm
4909 = getDerived().TransformFunctionTypeParam(OldParm,
4912 /*ExpectParameterPack=*/false);
4917 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
4918 OutParamTypes.push_back(NewParm->getType());
4920 PVars->push_back(NewParm);
4923 // If we're supposed to retain a pack expansion, do so by temporarily
4924 // forgetting the partially-substituted parameter pack.
4925 if (RetainExpansion) {
4926 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4927 ParmVarDecl *NewParm
4928 = getDerived().TransformFunctionTypeParam(OldParm,
4931 /*ExpectParameterPack=*/false);
4936 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
4937 OutParamTypes.push_back(NewParm->getType());
4939 PVars->push_back(NewParm);
4942 // The next parameter should have the same adjustment as the
4943 // last thing we pushed, but we post-incremented indexAdjustment
4944 // on every push. Also, if we push nothing, the adjustment should
4948 // We're done with the pack expansion.
4952 // We'll substitute the parameter now without expanding the pack
4954 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4955 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4958 /*ExpectParameterPack=*/true);
4960 NewParm = getDerived().TransformFunctionTypeParam(
4961 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4968 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
4969 OutParamTypes.push_back(NewParm->getType());
4971 PVars->push_back(NewParm);
4975 // Deal with the possibility that we don't have a parameter
4976 // declaration for this parameter.
4977 QualType OldType = ParamTypes[i];
4978 bool IsPackExpansion = false;
4979 Optional<unsigned> NumExpansions;
4981 if (const PackExpansionType *Expansion
4982 = dyn_cast<PackExpansionType>(OldType)) {
4983 // We have a function parameter pack that may need to be expanded.
4984 QualType Pattern = Expansion->getPattern();
4985 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4986 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4988 // Determine whether we should expand the parameter packs.
4989 bool ShouldExpand = false;
4990 bool RetainExpansion = false;
4991 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5000 // Expand the function parameter pack into multiple, separate
5002 for (unsigned I = 0; I != *NumExpansions; ++I) {
5003 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5004 QualType NewType = getDerived().TransformType(Pattern);
5005 if (NewType.isNull())
5008 if (NewType->containsUnexpandedParameterPack()) {
5010 getSema().getASTContext().getPackExpansionType(NewType, None);
5012 if (NewType.isNull())
5017 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5018 OutParamTypes.push_back(NewType);
5020 PVars->push_back(nullptr);
5023 // We're done with the pack expansion.
5027 // If we're supposed to retain a pack expansion, do so by temporarily
5028 // forgetting the partially-substituted parameter pack.
5029 if (RetainExpansion) {
5030 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5031 QualType NewType = getDerived().TransformType(Pattern);
5032 if (NewType.isNull())
5036 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5037 OutParamTypes.push_back(NewType);
5039 PVars->push_back(nullptr);
5042 // We'll substitute the parameter now without expanding the pack
5044 OldType = Expansion->getPattern();
5045 IsPackExpansion = true;
5046 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5047 NewType = getDerived().TransformType(OldType);
5049 NewType = getDerived().TransformType(OldType);
5052 if (NewType.isNull())
5055 if (IsPackExpansion)
5056 NewType = getSema().Context.getPackExpansionType(NewType,
5060 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5061 OutParamTypes.push_back(NewType);
5063 PVars->push_back(nullptr);
5068 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5069 if (ParmVarDecl *parm = (*PVars)[i])
5070 assert(parm->getFunctionScopeIndex() == i);
5077 template<typename Derived>
5079 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5080 FunctionProtoTypeLoc TL) {
5081 SmallVector<QualType, 4> ExceptionStorage;
5082 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5083 return getDerived().TransformFunctionProtoType(
5084 TLB, TL, nullptr, 0,
5085 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5086 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5087 ExceptionStorage, Changed);
5091 template<typename Derived> template<typename Fn>
5092 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5093 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5094 unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
5096 // Transform the parameters and return type.
5098 // We are required to instantiate the params and return type in source order.
5099 // When the function has a trailing return type, we instantiate the
5100 // parameters before the return type, since the return type can then refer
5101 // to the parameters themselves (via decltype, sizeof, etc.).
5103 SmallVector<QualType, 4> ParamTypes;
5104 SmallVector<ParmVarDecl*, 4> ParamDecls;
5105 Sema::ExtParameterInfoBuilder ExtParamInfos;
5106 const FunctionProtoType *T = TL.getTypePtr();
5108 QualType ResultType;
5110 if (T->hasTrailingReturn()) {
5111 if (getDerived().TransformFunctionTypeParams(
5112 TL.getBeginLoc(), TL.getParams(),
5113 TL.getTypePtr()->param_type_begin(),
5114 T->getExtParameterInfosOrNull(),
5115 ParamTypes, &ParamDecls, ExtParamInfos))
5119 // C++11 [expr.prim.general]p3:
5120 // If a declaration declares a member function or member function
5121 // template of a class X, the expression this is a prvalue of type
5122 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5123 // and the end of the function-definition, member-declarator, or
5125 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5127 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5128 if (ResultType.isNull())
5133 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5134 if (ResultType.isNull())
5137 if (getDerived().TransformFunctionTypeParams(
5138 TL.getBeginLoc(), TL.getParams(),
5139 TL.getTypePtr()->param_type_begin(),
5140 T->getExtParameterInfosOrNull(),
5141 ParamTypes, &ParamDecls, ExtParamInfos))
5145 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5147 bool EPIChanged = false;
5148 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5151 // Handle extended parameter information.
5152 if (auto NewExtParamInfos =
5153 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5154 if (!EPI.ExtParameterInfos ||
5155 llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5156 != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5159 EPI.ExtParameterInfos = NewExtParamInfos;
5160 } else if (EPI.ExtParameterInfos) {
5162 EPI.ExtParameterInfos = nullptr;
5165 QualType Result = TL.getType();
5166 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5167 T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5168 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5169 if (Result.isNull())
5173 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5174 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5175 NewTL.setLParenLoc(TL.getLParenLoc());
5176 NewTL.setRParenLoc(TL.getRParenLoc());
5177 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5178 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5179 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5180 NewTL.setParam(i, ParamDecls[i]);
5185 template<typename Derived>
5186 bool TreeTransform<Derived>::TransformExceptionSpec(
5187 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5188 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5189 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5191 // Instantiate a dynamic noexcept expression, if any.
5192 if (ESI.Type == EST_ComputedNoexcept) {
5193 EnterExpressionEvaluationContext Unevaluated(
5194 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5195 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5196 if (NoexceptExpr.isInvalid())
5199 // FIXME: This is bogus, a noexcept expression is not a condition.
5200 NoexceptExpr = getSema().CheckBooleanCondition(Loc, NoexceptExpr.get());
5201 if (NoexceptExpr.isInvalid())
5204 if (!NoexceptExpr.get()->isValueDependent()) {
5205 NoexceptExpr = getSema().VerifyIntegerConstantExpression(
5206 NoexceptExpr.get(), nullptr,
5207 diag::err_noexcept_needs_constant_expression,
5208 /*AllowFold*/false);
5209 if (NoexceptExpr.isInvalid())
5213 if (ESI.NoexceptExpr != NoexceptExpr.get())
5215 ESI.NoexceptExpr = NoexceptExpr.get();
5218 if (ESI.Type != EST_Dynamic)
5221 // Instantiate a dynamic exception specification's type.
5222 for (QualType T : ESI.Exceptions) {
5223 if (const PackExpansionType *PackExpansion =
5224 T->getAs<PackExpansionType>()) {
5227 // We have a pack expansion. Instantiate it.
5228 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5229 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5231 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5233 // Determine whether the set of unexpanded parameter packs can and
5236 bool Expand = false;
5237 bool RetainExpansion = false;
5238 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5239 // FIXME: Track the location of the ellipsis (and track source location
5240 // information for the types in the exception specification in general).
5241 if (getDerived().TryExpandParameterPacks(
5242 Loc, SourceRange(), Unexpanded, Expand,
5243 RetainExpansion, NumExpansions))
5247 // We can't expand this pack expansion into separate arguments yet;
5248 // just substitute into the pattern and create a new pack expansion
5250 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5251 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5255 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5256 Exceptions.push_back(U);
5260 // Substitute into the pack expansion pattern for each slice of the
5262 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5263 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5265 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5266 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5269 Exceptions.push_back(U);
5272 QualType U = getDerived().TransformType(T);
5273 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5278 Exceptions.push_back(U);
5282 ESI.Exceptions = Exceptions;
5283 if (ESI.Exceptions.empty())
5284 ESI.Type = EST_DynamicNone;
5288 template<typename Derived>
5289 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5290 TypeLocBuilder &TLB,
5291 FunctionNoProtoTypeLoc TL) {
5292 const FunctionNoProtoType *T = TL.getTypePtr();
5293 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5294 if (ResultType.isNull())
5297 QualType Result = TL.getType();
5298 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5299 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5301 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5302 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5303 NewTL.setLParenLoc(TL.getLParenLoc());
5304 NewTL.setRParenLoc(TL.getRParenLoc());
5305 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5310 template<typename Derived> QualType
5311 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5312 UnresolvedUsingTypeLoc TL) {
5313 const UnresolvedUsingType *T = TL.getTypePtr();
5314 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5318 QualType Result = TL.getType();
5319 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5320 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5321 if (Result.isNull())
5325 // We might get an arbitrary type spec type back. We should at
5326 // least always get a type spec type, though.
5327 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5328 NewTL.setNameLoc(TL.getNameLoc());
5333 template<typename Derived>
5334 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5335 TypedefTypeLoc TL) {
5336 const TypedefType *T = TL.getTypePtr();
5337 TypedefNameDecl *Typedef
5338 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5343 QualType Result = TL.getType();
5344 if (getDerived().AlwaysRebuild() ||
5345 Typedef != T->getDecl()) {
5346 Result = getDerived().RebuildTypedefType(Typedef);
5347 if (Result.isNull())
5351 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5352 NewTL.setNameLoc(TL.getNameLoc());
5357 template<typename Derived>
5358 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5359 TypeOfExprTypeLoc TL) {
5360 // typeof expressions are not potentially evaluated contexts
5361 EnterExpressionEvaluationContext Unevaluated(
5362 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5363 Sema::ReuseLambdaContextDecl);
5365 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5369 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5373 QualType Result = TL.getType();
5374 if (getDerived().AlwaysRebuild() ||
5375 E.get() != TL.getUnderlyingExpr()) {
5376 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5377 if (Result.isNull())
5382 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5383 NewTL.setTypeofLoc(TL.getTypeofLoc());
5384 NewTL.setLParenLoc(TL.getLParenLoc());
5385 NewTL.setRParenLoc(TL.getRParenLoc());
5390 template<typename Derived>
5391 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5393 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5394 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5398 QualType Result = TL.getType();
5399 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5400 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5401 if (Result.isNull())
5405 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5406 NewTL.setTypeofLoc(TL.getTypeofLoc());
5407 NewTL.setLParenLoc(TL.getLParenLoc());
5408 NewTL.setRParenLoc(TL.getRParenLoc());
5409 NewTL.setUnderlyingTInfo(New_Under_TI);
5414 template<typename Derived>
5415 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5416 DecltypeTypeLoc TL) {
5417 const DecltypeType *T = TL.getTypePtr();
5419 // decltype expressions are not potentially evaluated contexts
5420 EnterExpressionEvaluationContext Unevaluated(
5421 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5422 /*IsDecltype=*/true);
5424 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5428 E = getSema().ActOnDecltypeExpression(E.get());
5432 QualType Result = TL.getType();
5433 if (getDerived().AlwaysRebuild() ||
5434 E.get() != T->getUnderlyingExpr()) {
5435 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5436 if (Result.isNull())
5441 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5442 NewTL.setNameLoc(TL.getNameLoc());
5447 template<typename Derived>
5448 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5449 TypeLocBuilder &TLB,
5450 UnaryTransformTypeLoc TL) {
5451 QualType Result = TL.getType();
5452 if (Result->isDependentType()) {
5453 const UnaryTransformType *T = TL.getTypePtr();
5455 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5456 Result = getDerived().RebuildUnaryTransformType(NewBase,
5459 if (Result.isNull())
5463 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5464 NewTL.setKWLoc(TL.getKWLoc());
5465 NewTL.setParensRange(TL.getParensRange());
5466 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5470 template<typename Derived>
5471 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5473 const AutoType *T = TL.getTypePtr();
5474 QualType OldDeduced = T->getDeducedType();
5475 QualType NewDeduced;
5476 if (!OldDeduced.isNull()) {
5477 NewDeduced = getDerived().TransformType(OldDeduced);
5478 if (NewDeduced.isNull())
5482 QualType Result = TL.getType();
5483 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5484 T->isDependentType()) {
5485 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5486 if (Result.isNull())
5490 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5491 NewTL.setNameLoc(TL.getNameLoc());
5496 template<typename Derived>
5497 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5498 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5499 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5502 TemplateName TemplateName = getDerived().TransformTemplateName(
5503 SS, T->getTemplateName(), TL.getTemplateNameLoc());
5504 if (TemplateName.isNull())
5507 QualType OldDeduced = T->getDeducedType();
5508 QualType NewDeduced;
5509 if (!OldDeduced.isNull()) {
5510 NewDeduced = getDerived().TransformType(OldDeduced);
5511 if (NewDeduced.isNull())
5515 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5516 TemplateName, NewDeduced);
5517 if (Result.isNull())
5520 DeducedTemplateSpecializationTypeLoc NewTL =
5521 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5522 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5527 template<typename Derived>
5528 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5530 const RecordType *T = TL.getTypePtr();
5532 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5537 QualType Result = TL.getType();
5538 if (getDerived().AlwaysRebuild() ||
5539 Record != T->getDecl()) {
5540 Result = getDerived().RebuildRecordType(Record);
5541 if (Result.isNull())
5545 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5546 NewTL.setNameLoc(TL.getNameLoc());
5551 template<typename Derived>
5552 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5554 const EnumType *T = TL.getTypePtr();
5556 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5561 QualType Result = TL.getType();
5562 if (getDerived().AlwaysRebuild() ||
5563 Enum != T->getDecl()) {
5564 Result = getDerived().RebuildEnumType(Enum);
5565 if (Result.isNull())
5569 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5570 NewTL.setNameLoc(TL.getNameLoc());
5575 template<typename Derived>
5576 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5577 TypeLocBuilder &TLB,
5578 InjectedClassNameTypeLoc TL) {
5579 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5580 TL.getTypePtr()->getDecl());
5581 if (!D) return QualType();
5583 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5584 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5588 template<typename Derived>
5589 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5590 TypeLocBuilder &TLB,
5591 TemplateTypeParmTypeLoc TL) {
5592 return TransformTypeSpecType(TLB, TL);
5595 template<typename Derived>
5596 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5597 TypeLocBuilder &TLB,
5598 SubstTemplateTypeParmTypeLoc TL) {
5599 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5601 // Substitute into the replacement type, which itself might involve something
5602 // that needs to be transformed. This only tends to occur with default
5603 // template arguments of template template parameters.
5604 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5605 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5606 if (Replacement.isNull())
5609 // Always canonicalize the replacement type.
5610 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5612 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5615 // Propagate type-source information.
5616 SubstTemplateTypeParmTypeLoc NewTL
5617 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5618 NewTL.setNameLoc(TL.getNameLoc());
5623 template<typename Derived>
5624 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5625 TypeLocBuilder &TLB,
5626 SubstTemplateTypeParmPackTypeLoc TL) {
5627 return TransformTypeSpecType(TLB, TL);
5630 template<typename Derived>
5631 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5632 TypeLocBuilder &TLB,
5633 TemplateSpecializationTypeLoc TL) {
5634 const TemplateSpecializationType *T = TL.getTypePtr();
5636 // The nested-name-specifier never matters in a TemplateSpecializationType,
5637 // because we can't have a dependent nested-name-specifier anyway.
5639 TemplateName Template
5640 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5641 TL.getTemplateNameLoc());
5642 if (Template.isNull())
5645 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5648 template<typename Derived>
5649 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5651 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5652 if (ValueType.isNull())
5655 QualType Result = TL.getType();
5656 if (getDerived().AlwaysRebuild() ||
5657 ValueType != TL.getValueLoc().getType()) {
5658 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5659 if (Result.isNull())
5663 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5664 NewTL.setKWLoc(TL.getKWLoc());
5665 NewTL.setLParenLoc(TL.getLParenLoc());
5666 NewTL.setRParenLoc(TL.getRParenLoc());
5671 template <typename Derived>
5672 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5674 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5675 if (ValueType.isNull())
5678 QualType Result = TL.getType();
5679 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5680 const PipeType *PT = Result->getAs<PipeType>();
5681 bool isReadPipe = PT->isReadOnly();
5682 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5683 if (Result.isNull())
5687 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5688 NewTL.setKWLoc(TL.getKWLoc());
5693 /// \brief Simple iterator that traverses the template arguments in a
5694 /// container that provides a \c getArgLoc() member function.
5696 /// This iterator is intended to be used with the iterator form of
5697 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5698 template<typename ArgLocContainer>
5699 class TemplateArgumentLocContainerIterator {
5700 ArgLocContainer *Container;
5704 typedef TemplateArgumentLoc value_type;
5705 typedef TemplateArgumentLoc reference;
5706 typedef int difference_type;
5707 typedef std::input_iterator_tag iterator_category;
5710 TemplateArgumentLoc Arg;
5713 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5715 const TemplateArgumentLoc *operator->() const {
5721 TemplateArgumentLocContainerIterator() {}
5723 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5725 : Container(&Container), Index(Index) { }
5727 TemplateArgumentLocContainerIterator &operator++() {
5732 TemplateArgumentLocContainerIterator operator++(int) {
5733 TemplateArgumentLocContainerIterator Old(*this);
5738 TemplateArgumentLoc operator*() const {
5739 return Container->getArgLoc(Index);
5742 pointer operator->() const {
5743 return pointer(Container->getArgLoc(Index));
5746 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5747 const TemplateArgumentLocContainerIterator &Y) {
5748 return X.Container == Y.Container && X.Index == Y.Index;
5751 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
5752 const TemplateArgumentLocContainerIterator &Y) {
5758 template <typename Derived>
5759 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5760 TypeLocBuilder &TLB,
5761 TemplateSpecializationTypeLoc TL,
5762 TemplateName Template) {
5763 TemplateArgumentListInfo NewTemplateArgs;
5764 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5765 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5766 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
5768 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5769 ArgIterator(TL, TL.getNumArgs()),
5773 // FIXME: maybe don't rebuild if all the template arguments are the same.
5776 getDerived().RebuildTemplateSpecializationType(Template,
5777 TL.getTemplateNameLoc(),
5780 if (!Result.isNull()) {
5781 // Specializations of template template parameters are represented as
5782 // TemplateSpecializationTypes, and substitution of type alias templates
5783 // within a dependent context can transform them into
5784 // DependentTemplateSpecializationTypes.
5785 if (isa<DependentTemplateSpecializationType>(Result)) {
5786 DependentTemplateSpecializationTypeLoc NewTL
5787 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5788 NewTL.setElaboratedKeywordLoc(SourceLocation());
5789 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
5790 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5791 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5792 NewTL.setLAngleLoc(TL.getLAngleLoc());
5793 NewTL.setRAngleLoc(TL.getRAngleLoc());
5794 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5795 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5799 TemplateSpecializationTypeLoc NewTL
5800 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5801 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5802 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5803 NewTL.setLAngleLoc(TL.getLAngleLoc());
5804 NewTL.setRAngleLoc(TL.getRAngleLoc());
5805 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5806 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5812 template <typename Derived>
5813 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
5814 TypeLocBuilder &TLB,
5815 DependentTemplateSpecializationTypeLoc TL,
5816 TemplateName Template,
5818 TemplateArgumentListInfo NewTemplateArgs;
5819 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5820 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5821 typedef TemplateArgumentLocContainerIterator<
5822 DependentTemplateSpecializationTypeLoc> ArgIterator;
5823 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5824 ArgIterator(TL, TL.getNumArgs()),
5828 // FIXME: maybe don't rebuild if all the template arguments are the same.
5830 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
5832 = getSema().Context.getDependentTemplateSpecializationType(
5833 TL.getTypePtr()->getKeyword(),
5834 DTN->getQualifier(),
5835 DTN->getIdentifier(),
5838 DependentTemplateSpecializationTypeLoc NewTL
5839 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5840 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5841 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
5842 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5843 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5844 NewTL.setLAngleLoc(TL.getLAngleLoc());
5845 NewTL.setRAngleLoc(TL.getRAngleLoc());
5846 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5847 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5852 = getDerived().RebuildTemplateSpecializationType(Template,
5853 TL.getTemplateNameLoc(),
5856 if (!Result.isNull()) {
5857 /// FIXME: Wrap this in an elaborated-type-specifier?
5858 TemplateSpecializationTypeLoc NewTL
5859 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5860 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5861 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5862 NewTL.setLAngleLoc(TL.getLAngleLoc());
5863 NewTL.setRAngleLoc(TL.getRAngleLoc());
5864 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5865 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5871 template<typename Derived>
5873 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
5874 ElaboratedTypeLoc TL) {
5875 const ElaboratedType *T = TL.getTypePtr();
5877 NestedNameSpecifierLoc QualifierLoc;
5878 // NOTE: the qualifier in an ElaboratedType is optional.
5879 if (TL.getQualifierLoc()) {
5881 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5886 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
5887 if (NamedT.isNull())
5890 // C++0x [dcl.type.elab]p2:
5891 // If the identifier resolves to a typedef-name or the simple-template-id
5892 // resolves to an alias template specialization, the
5893 // elaborated-type-specifier is ill-formed.
5894 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
5895 if (const TemplateSpecializationType *TST =
5896 NamedT->getAs<TemplateSpecializationType>()) {
5897 TemplateName Template = TST->getTemplateName();
5898 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
5899 Template.getAsTemplateDecl())) {
5900 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
5901 diag::err_tag_reference_non_tag)
5902 << TAT << Sema::NTK_TypeAliasTemplate
5903 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
5904 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
5909 QualType Result = TL.getType();
5910 if (getDerived().AlwaysRebuild() ||
5911 QualifierLoc != TL.getQualifierLoc() ||
5912 NamedT != T->getNamedType()) {
5913 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
5915 QualifierLoc, NamedT);
5916 if (Result.isNull())
5920 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5921 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5922 NewTL.setQualifierLoc(QualifierLoc);
5926 template<typename Derived>
5927 QualType TreeTransform<Derived>::TransformAttributedType(
5928 TypeLocBuilder &TLB,
5929 AttributedTypeLoc TL) {
5930 const AttributedType *oldType = TL.getTypePtr();
5931 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
5932 if (modifiedType.isNull())
5935 QualType result = TL.getType();
5937 // FIXME: dependent operand expressions?
5938 if (getDerived().AlwaysRebuild() ||
5939 modifiedType != oldType->getModifiedType()) {
5940 // TODO: this is really lame; we should really be rebuilding the
5941 // equivalent type from first principles.
5942 QualType equivalentType
5943 = getDerived().TransformType(oldType->getEquivalentType());
5944 if (equivalentType.isNull())
5947 // Check whether we can add nullability; it is only represented as
5948 // type sugar, and therefore cannot be diagnosed in any other way.
5949 if (auto nullability = oldType->getImmediateNullability()) {
5950 if (!modifiedType->canHaveNullability()) {
5951 SemaRef.Diag(TL.getAttrNameLoc(), diag::err_nullability_nonpointer)
5952 << DiagNullabilityKind(*nullability, false) << modifiedType;
5957 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
5962 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
5963 newTL.setAttrNameLoc(TL.getAttrNameLoc());
5964 if (TL.hasAttrOperand())
5965 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5966 if (TL.hasAttrExprOperand())
5967 newTL.setAttrExprOperand(TL.getAttrExprOperand());
5968 else if (TL.hasAttrEnumOperand())
5969 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
5974 template<typename Derived>
5976 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
5978 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
5982 QualType Result = TL.getType();
5983 if (getDerived().AlwaysRebuild() ||
5984 Inner != TL.getInnerLoc().getType()) {
5985 Result = getDerived().RebuildParenType(Inner);
5986 if (Result.isNull())
5990 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
5991 NewTL.setLParenLoc(TL.getLParenLoc());
5992 NewTL.setRParenLoc(TL.getRParenLoc());
5996 template<typename Derived>
5997 QualType TreeTransform<Derived>::TransformDependentNameType(
5998 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
5999 return TransformDependentNameType(TLB, TL, false);
6002 template<typename Derived>
6003 QualType TreeTransform<Derived>::TransformDependentNameType(
6004 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6005 const DependentNameType *T = TL.getTypePtr();
6007 NestedNameSpecifierLoc QualifierLoc
6008 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6013 = getDerived().RebuildDependentNameType(T->getKeyword(),
6014 TL.getElaboratedKeywordLoc(),
6019 if (Result.isNull())
6022 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6023 QualType NamedT = ElabT->getNamedType();
6024 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6026 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6027 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6028 NewTL.setQualifierLoc(QualifierLoc);
6030 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6031 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6032 NewTL.setQualifierLoc(QualifierLoc);
6033 NewTL.setNameLoc(TL.getNameLoc());
6038 template<typename Derived>
6039 QualType TreeTransform<Derived>::
6040 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6041 DependentTemplateSpecializationTypeLoc TL) {
6042 NestedNameSpecifierLoc QualifierLoc;
6043 if (TL.getQualifierLoc()) {
6045 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6051 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6054 template<typename Derived>
6055 QualType TreeTransform<Derived>::
6056 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6057 DependentTemplateSpecializationTypeLoc TL,
6058 NestedNameSpecifierLoc QualifierLoc) {
6059 const DependentTemplateSpecializationType *T = TL.getTypePtr();
6061 TemplateArgumentListInfo NewTemplateArgs;
6062 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6063 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6065 typedef TemplateArgumentLocContainerIterator<
6066 DependentTemplateSpecializationTypeLoc> ArgIterator;
6067 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6068 ArgIterator(TL, TL.getNumArgs()),
6072 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6073 T->getKeyword(), QualifierLoc, T->getIdentifier(),
6074 TL.getTemplateNameLoc(), NewTemplateArgs,
6075 /*AllowInjectedClassName*/ false);
6076 if (Result.isNull())
6079 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6080 QualType NamedT = ElabT->getNamedType();
6082 // Copy information relevant to the template specialization.
6083 TemplateSpecializationTypeLoc NamedTL
6084 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6085 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6086 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6087 NamedTL.setLAngleLoc(TL.getLAngleLoc());
6088 NamedTL.setRAngleLoc(TL.getRAngleLoc());
6089 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6090 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6092 // Copy information relevant to the elaborated type.
6093 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6094 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6095 NewTL.setQualifierLoc(QualifierLoc);
6096 } else if (isa<DependentTemplateSpecializationType>(Result)) {
6097 DependentTemplateSpecializationTypeLoc SpecTL
6098 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6099 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6100 SpecTL.setQualifierLoc(QualifierLoc);
6101 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6102 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6103 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6104 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6105 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6106 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6108 TemplateSpecializationTypeLoc SpecTL
6109 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6110 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6111 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6112 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6113 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6114 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6115 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6120 template<typename Derived>
6121 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6122 PackExpansionTypeLoc TL) {
6124 = getDerived().TransformType(TLB, TL.getPatternLoc());
6125 if (Pattern.isNull())
6128 QualType Result = TL.getType();
6129 if (getDerived().AlwaysRebuild() ||
6130 Pattern != TL.getPatternLoc().getType()) {
6131 Result = getDerived().RebuildPackExpansionType(Pattern,
6132 TL.getPatternLoc().getSourceRange(),
6133 TL.getEllipsisLoc(),
6134 TL.getTypePtr()->getNumExpansions());
6135 if (Result.isNull())
6139 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6140 NewT.setEllipsisLoc(TL.getEllipsisLoc());
6144 template<typename Derived>
6146 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6147 ObjCInterfaceTypeLoc TL) {
6148 // ObjCInterfaceType is never dependent.
6149 TLB.pushFullCopy(TL);
6150 return TL.getType();
6153 template<typename Derived>
6155 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6156 ObjCTypeParamTypeLoc TL) {
6157 const ObjCTypeParamType *T = TL.getTypePtr();
6158 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6159 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6163 QualType Result = TL.getType();
6164 if (getDerived().AlwaysRebuild() ||
6165 OTP != T->getDecl()) {
6166 Result = getDerived().RebuildObjCTypeParamType(OTP,
6167 TL.getProtocolLAngleLoc(),
6168 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6169 TL.getNumProtocols()),
6170 TL.getProtocolLocs(),
6171 TL.getProtocolRAngleLoc());
6172 if (Result.isNull())
6176 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6177 if (TL.getNumProtocols()) {
6178 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6179 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6180 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6181 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6186 template<typename Derived>
6188 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6189 ObjCObjectTypeLoc TL) {
6190 // Transform base type.
6191 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6192 if (BaseType.isNull())
6195 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6197 // Transform type arguments.
6198 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6199 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6200 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6201 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6202 QualType TypeArg = TypeArgInfo->getType();
6203 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6206 // We have a pack expansion. Instantiate it.
6207 const auto *PackExpansion = PackExpansionLoc.getType()
6208 ->castAs<PackExpansionType>();
6209 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6210 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6212 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6214 // Determine whether the set of unexpanded parameter packs can
6215 // and should be expanded.
6216 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6217 bool Expand = false;
6218 bool RetainExpansion = false;
6219 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6220 if (getDerived().TryExpandParameterPacks(
6221 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6222 Unexpanded, Expand, RetainExpansion, NumExpansions))
6226 // We can't expand this pack expansion into separate arguments yet;
6227 // just substitute into the pattern and create a new pack expansion
6229 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6231 TypeLocBuilder TypeArgBuilder;
6232 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6233 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6235 if (NewPatternType.isNull())
6238 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6239 NewPatternType, NumExpansions);
6240 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6241 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6242 NewTypeArgInfos.push_back(
6243 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6247 // Substitute into the pack expansion pattern for each slice of the
6249 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6250 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6252 TypeLocBuilder TypeArgBuilder;
6253 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6255 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6257 if (NewTypeArg.isNull())
6260 NewTypeArgInfos.push_back(
6261 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6267 TypeLocBuilder TypeArgBuilder;
6268 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6269 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6270 if (NewTypeArg.isNull())
6273 // If nothing changed, just keep the old TypeSourceInfo.
6274 if (NewTypeArg == TypeArg) {
6275 NewTypeArgInfos.push_back(TypeArgInfo);
6279 NewTypeArgInfos.push_back(
6280 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6284 QualType Result = TL.getType();
6285 if (getDerived().AlwaysRebuild() || AnyChanged) {
6286 // Rebuild the type.
6287 Result = getDerived().RebuildObjCObjectType(
6290 TL.getTypeArgsLAngleLoc(),
6292 TL.getTypeArgsRAngleLoc(),
6293 TL.getProtocolLAngleLoc(),
6294 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6295 TL.getNumProtocols()),
6296 TL.getProtocolLocs(),
6297 TL.getProtocolRAngleLoc());
6299 if (Result.isNull())
6303 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6304 NewT.setHasBaseTypeAsWritten(true);
6305 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6306 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6307 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6308 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6309 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6310 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6311 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6312 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6316 template<typename Derived>
6318 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6319 ObjCObjectPointerTypeLoc TL) {
6320 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6321 if (PointeeType.isNull())
6324 QualType Result = TL.getType();
6325 if (getDerived().AlwaysRebuild() ||
6326 PointeeType != TL.getPointeeLoc().getType()) {
6327 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6329 if (Result.isNull())
6333 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6334 NewT.setStarLoc(TL.getStarLoc());
6338 //===----------------------------------------------------------------------===//
6339 // Statement transformation
6340 //===----------------------------------------------------------------------===//
6341 template<typename Derived>
6343 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6347 template<typename Derived>
6349 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6350 return getDerived().TransformCompoundStmt(S, false);
6353 template<typename Derived>
6355 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6357 Sema::CompoundScopeRAII CompoundScope(getSema());
6359 bool SubStmtInvalid = false;
6360 bool SubStmtChanged = false;
6361 SmallVector<Stmt*, 8> Statements;
6362 for (auto *B : S->body()) {
6363 StmtResult Result = getDerived().TransformStmt(B);
6364 if (Result.isInvalid()) {
6365 // Immediately fail if this was a DeclStmt, since it's very
6366 // likely that this will cause problems for future statements.
6367 if (isa<DeclStmt>(B))
6370 // Otherwise, just keep processing substatements and fail later.
6371 SubStmtInvalid = true;
6375 SubStmtChanged = SubStmtChanged || Result.get() != B;
6376 Statements.push_back(Result.getAs<Stmt>());
6382 if (!getDerived().AlwaysRebuild() &&
6386 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6392 template<typename Derived>
6394 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6395 ExprResult LHS, RHS;
6397 EnterExpressionEvaluationContext Unevaluated(
6398 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6400 // Transform the left-hand case value.
6401 LHS = getDerived().TransformExpr(S->getLHS());
6402 LHS = SemaRef.ActOnConstantExpression(LHS);
6403 if (LHS.isInvalid())
6406 // Transform the right-hand case value (for the GNU case-range extension).
6407 RHS = getDerived().TransformExpr(S->getRHS());
6408 RHS = SemaRef.ActOnConstantExpression(RHS);
6409 if (RHS.isInvalid())
6413 // Build the case statement.
6414 // Case statements are always rebuilt so that they will attached to their
6415 // transformed switch statement.
6416 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6418 S->getEllipsisLoc(),
6421 if (Case.isInvalid())
6424 // Transform the statement following the case
6425 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6426 if (SubStmt.isInvalid())
6429 // Attach the body to the case statement
6430 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6433 template<typename Derived>
6435 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6436 // Transform the statement following the default case
6437 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6438 if (SubStmt.isInvalid())
6441 // Default statements are always rebuilt
6442 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6446 template<typename Derived>
6448 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
6449 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6450 if (SubStmt.isInvalid())
6453 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6459 // FIXME: Pass the real colon location in.
6460 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6461 cast<LabelDecl>(LD), SourceLocation(),
6465 template <typename Derived>
6466 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6470 switch (R->getKind()) {
6471 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6473 #define PRAGMA_SPELLING_ATTR(X) \
6475 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6476 #include "clang/Basic/AttrList.inc"
6482 template <typename Derived>
6483 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
6484 bool AttrsChanged = false;
6485 SmallVector<const Attr *, 1> Attrs;
6487 // Visit attributes and keep track if any are transformed.
6488 for (const auto *I : S->getAttrs()) {
6489 const Attr *R = getDerived().TransformAttr(I);
6490 AttrsChanged |= (I != R);
6494 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6495 if (SubStmt.isInvalid())
6498 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6501 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6505 template<typename Derived>
6507 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6508 // Transform the initialization statement
6509 StmtResult Init = getDerived().TransformStmt(S->getInit());
6510 if (Init.isInvalid())
6513 // Transform the condition
6514 Sema::ConditionResult Cond = getDerived().TransformCondition(
6515 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6516 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6517 : Sema::ConditionKind::Boolean);
6518 if (Cond.isInvalid())
6521 // If this is a constexpr if, determine which arm we should instantiate.
6522 llvm::Optional<bool> ConstexprConditionValue;
6523 if (S->isConstexpr())
6524 ConstexprConditionValue = Cond.getKnownValue();
6526 // Transform the "then" branch.
6528 if (!ConstexprConditionValue || *ConstexprConditionValue) {
6529 Then = getDerived().TransformStmt(S->getThen());
6530 if (Then.isInvalid())
6533 Then = new (getSema().Context) NullStmt(S->getThen()->getLocStart());
6536 // Transform the "else" branch.
6538 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6539 Else = getDerived().TransformStmt(S->getElse());
6540 if (Else.isInvalid())
6544 if (!getDerived().AlwaysRebuild() &&
6545 Init.get() == S->getInit() &&
6546 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6547 Then.get() == S->getThen() &&
6548 Else.get() == S->getElse())
6551 return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6552 Init.get(), Then.get(), S->getElseLoc(),
6556 template<typename Derived>
6558 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6559 // Transform the initialization statement
6560 StmtResult Init = getDerived().TransformStmt(S->getInit());
6561 if (Init.isInvalid())
6564 // Transform the condition.
6565 Sema::ConditionResult Cond = getDerived().TransformCondition(
6566 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6567 Sema::ConditionKind::Switch);
6568 if (Cond.isInvalid())
6571 // Rebuild the switch statement.
6573 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(),
6574 S->getInit(), Cond);
6575 if (Switch.isInvalid())
6578 // Transform the body of the switch statement.
6579 StmtResult Body = getDerived().TransformStmt(S->getBody());
6580 if (Body.isInvalid())
6583 // Complete the switch statement.
6584 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6588 template<typename Derived>
6590 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6591 // Transform the condition
6592 Sema::ConditionResult Cond = getDerived().TransformCondition(
6593 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6594 Sema::ConditionKind::Boolean);
6595 if (Cond.isInvalid())
6598 // Transform the body
6599 StmtResult Body = getDerived().TransformStmt(S->getBody());
6600 if (Body.isInvalid())
6603 if (!getDerived().AlwaysRebuild() &&
6604 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6605 Body.get() == S->getBody())
6608 return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6611 template<typename Derived>
6613 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6614 // Transform the body
6615 StmtResult Body = getDerived().TransformStmt(S->getBody());
6616 if (Body.isInvalid())
6619 // Transform the condition
6620 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6621 if (Cond.isInvalid())
6624 if (!getDerived().AlwaysRebuild() &&
6625 Cond.get() == S->getCond() &&
6626 Body.get() == S->getBody())
6629 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6630 /*FIXME:*/S->getWhileLoc(), Cond.get(),
6634 template<typename Derived>
6636 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6637 // Transform the initialization statement
6638 StmtResult Init = getDerived().TransformStmt(S->getInit());
6639 if (Init.isInvalid())
6642 // In OpenMP loop region loop control variable must be captured and be
6643 // private. Perform analysis of first part (if any).
6644 if (getSema().getLangOpts().OpenMP && Init.isUsable())
6645 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6647 // Transform the condition
6648 Sema::ConditionResult Cond = getDerived().TransformCondition(
6649 S->getForLoc(), S->getConditionVariable(), S->getCond(),
6650 Sema::ConditionKind::Boolean);
6651 if (Cond.isInvalid())
6654 // Transform the increment
6655 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6656 if (Inc.isInvalid())
6659 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6660 if (S->getInc() && !FullInc.get())
6663 // Transform the body
6664 StmtResult Body = getDerived().TransformStmt(S->getBody());
6665 if (Body.isInvalid())
6668 if (!getDerived().AlwaysRebuild() &&
6669 Init.get() == S->getInit() &&
6670 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6671 Inc.get() == S->getInc() &&
6672 Body.get() == S->getBody())
6675 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6676 Init.get(), Cond, FullInc,
6677 S->getRParenLoc(), Body.get());
6680 template<typename Derived>
6682 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6683 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6688 // Goto statements must always be rebuilt, to resolve the label.
6689 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6690 cast<LabelDecl>(LD));
6693 template<typename Derived>
6695 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6696 ExprResult Target = getDerived().TransformExpr(S->getTarget());
6697 if (Target.isInvalid())
6699 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6701 if (!getDerived().AlwaysRebuild() &&
6702 Target.get() == S->getTarget())
6705 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6709 template<typename Derived>
6711 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6715 template<typename Derived>
6717 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6721 template<typename Derived>
6723 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
6724 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
6725 /*NotCopyInit*/false);
6726 if (Result.isInvalid())
6729 // FIXME: We always rebuild the return statement because there is no way
6730 // to tell whether the return type of the function has changed.
6731 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
6734 template<typename Derived>
6736 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
6737 bool DeclChanged = false;
6738 SmallVector<Decl *, 4> Decls;
6739 for (auto *D : S->decls()) {
6740 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
6744 if (Transformed != D)
6747 Decls.push_back(Transformed);
6750 if (!getDerived().AlwaysRebuild() && !DeclChanged)
6753 return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
6756 template<typename Derived>
6758 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
6760 SmallVector<Expr*, 8> Constraints;
6761 SmallVector<Expr*, 8> Exprs;
6762 SmallVector<IdentifierInfo *, 4> Names;
6764 ExprResult AsmString;
6765 SmallVector<Expr*, 8> Clobbers;
6767 bool ExprsChanged = false;
6769 // Go through the outputs.
6770 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
6771 Names.push_back(S->getOutputIdentifier(I));
6773 // No need to transform the constraint literal.
6774 Constraints.push_back(S->getOutputConstraintLiteral(I));
6776 // Transform the output expr.
6777 Expr *OutputExpr = S->getOutputExpr(I);
6778 ExprResult Result = getDerived().TransformExpr(OutputExpr);
6779 if (Result.isInvalid())
6782 ExprsChanged |= Result.get() != OutputExpr;
6784 Exprs.push_back(Result.get());
6787 // Go through the inputs.
6788 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
6789 Names.push_back(S->getInputIdentifier(I));
6791 // No need to transform the constraint literal.
6792 Constraints.push_back(S->getInputConstraintLiteral(I));
6794 // Transform the input expr.
6795 Expr *InputExpr = S->getInputExpr(I);
6796 ExprResult Result = getDerived().TransformExpr(InputExpr);
6797 if (Result.isInvalid())
6800 ExprsChanged |= Result.get() != InputExpr;
6802 Exprs.push_back(Result.get());
6805 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
6808 // Go through the clobbers.
6809 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
6810 Clobbers.push_back(S->getClobberStringLiteral(I));
6812 // No need to transform the asm string literal.
6813 AsmString = S->getAsmString();
6814 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
6815 S->isVolatile(), S->getNumOutputs(),
6816 S->getNumInputs(), Names.data(),
6817 Constraints, Exprs, AsmString.get(),
6818 Clobbers, S->getRParenLoc());
6821 template<typename Derived>
6823 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
6824 ArrayRef<Token> AsmToks =
6825 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
6827 bool HadError = false, HadChange = false;
6829 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
6830 SmallVector<Expr*, 8> TransformedExprs;
6831 TransformedExprs.reserve(SrcExprs.size());
6832 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
6833 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
6834 if (!Result.isUsable()) {
6837 HadChange |= (Result.get() != SrcExprs[i]);
6838 TransformedExprs.push_back(Result.get());
6842 if (HadError) return StmtError();
6843 if (!HadChange && !getDerived().AlwaysRebuild())
6846 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
6847 AsmToks, S->getAsmString(),
6848 S->getNumOutputs(), S->getNumInputs(),
6849 S->getAllConstraints(), S->getClobbers(),
6850 TransformedExprs, S->getEndLoc());
6853 // C++ Coroutines TS
6855 template<typename Derived>
6857 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
6858 auto *ScopeInfo = SemaRef.getCurFunction();
6859 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
6860 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
6861 ScopeInfo->NeedsCoroutineSuspends &&
6862 ScopeInfo->CoroutineSuspends.first == nullptr &&
6863 ScopeInfo->CoroutineSuspends.second == nullptr &&
6864 "expected clean scope info");
6866 // Set that we have (possibly-invalid) suspend points before we do anything
6868 ScopeInfo->setNeedsCoroutineSuspends(false);
6870 // The new CoroutinePromise object needs to be built and put into the current
6871 // FunctionScopeInfo before any transformations or rebuilding occurs.
6872 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
6875 getDerived().transformedLocalDecl(S->getPromiseDecl(), Promise);
6876 ScopeInfo->CoroutinePromise = Promise;
6878 // Transform the implicit coroutine statements we built during the initial
6880 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
6881 if (InitSuspend.isInvalid())
6883 StmtResult FinalSuspend =
6884 getDerived().TransformStmt(S->getFinalSuspendStmt());
6885 if (FinalSuspend.isInvalid())
6887 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
6888 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
6890 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
6891 if (BodyRes.isInvalid())
6894 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
6895 if (Builder.isInvalid())
6898 Expr *ReturnObject = S->getReturnValueInit();
6899 assert(ReturnObject && "the return object is expected to be valid");
6900 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
6901 /*NoCopyInit*/ false);
6902 if (Res.isInvalid())
6904 Builder.ReturnValue = Res.get();
6906 if (S->hasDependentPromiseType()) {
6907 assert(!Promise->getType()->isDependentType() &&
6908 "the promise type must no longer be dependent");
6909 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
6910 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
6911 "these nodes should not have been built yet");
6912 if (!Builder.buildDependentStatements())
6915 if (auto *OnFallthrough = S->getFallthroughHandler()) {
6916 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
6917 if (Res.isInvalid())
6919 Builder.OnFallthrough = Res.get();
6922 if (auto *OnException = S->getExceptionHandler()) {
6923 StmtResult Res = getDerived().TransformStmt(OnException);
6924 if (Res.isInvalid())
6926 Builder.OnException = Res.get();
6929 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
6930 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
6931 if (Res.isInvalid())
6933 Builder.ReturnStmtOnAllocFailure = Res.get();
6936 // Transform any additional statements we may have already built
6937 assert(S->getAllocate() && S->getDeallocate() &&
6938 "allocation and deallocation calls must already be built");
6939 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
6940 if (AllocRes.isInvalid())
6942 Builder.Allocate = AllocRes.get();
6944 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
6945 if (DeallocRes.isInvalid())
6947 Builder.Deallocate = DeallocRes.get();
6950 return getDerived().RebuildCoroutineBodyStmt(Builder);
6953 template<typename Derived>
6955 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
6956 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
6957 /*NotCopyInit*/false);
6958 if (Result.isInvalid())
6961 // Always rebuild; we don't know if this needs to be injected into a new
6962 // context or if the promise type has changed.
6963 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
6967 template<typename Derived>
6969 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
6970 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
6971 /*NotCopyInit*/false);
6972 if (Result.isInvalid())
6975 // Always rebuild; we don't know if this needs to be injected into a new
6976 // context or if the promise type has changed.
6977 return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
6981 template <typename Derived>
6983 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
6984 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
6985 /*NotCopyInit*/ false);
6986 if (OperandResult.isInvalid())
6989 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
6990 E->getOperatorCoawaitLookup());
6992 if (LookupResult.isInvalid())
6995 // Always rebuild; we don't know if this needs to be injected into a new
6996 // context or if the promise type has changed.
6997 return getDerived().RebuildDependentCoawaitExpr(
6998 E->getKeywordLoc(), OperandResult.get(),
6999 cast<UnresolvedLookupExpr>(LookupResult.get()));
7002 template<typename Derived>
7004 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7005 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7006 /*NotCopyInit*/false);
7007 if (Result.isInvalid())
7010 // Always rebuild; we don't know if this needs to be injected into a new
7011 // context or if the promise type has changed.
7012 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7015 // Objective-C Statements.
7017 template<typename Derived>
7019 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7020 // Transform the body of the @try.
7021 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7022 if (TryBody.isInvalid())
7025 // Transform the @catch statements (if present).
7026 bool AnyCatchChanged = false;
7027 SmallVector<Stmt*, 8> CatchStmts;
7028 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7029 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7030 if (Catch.isInvalid())
7032 if (Catch.get() != S->getCatchStmt(I))
7033 AnyCatchChanged = true;
7034 CatchStmts.push_back(Catch.get());
7037 // Transform the @finally statement (if present).
7039 if (S->getFinallyStmt()) {
7040 Finally = getDerived().TransformStmt(S->getFinallyStmt());
7041 if (Finally.isInvalid())
7045 // If nothing changed, just retain this statement.
7046 if (!getDerived().AlwaysRebuild() &&
7047 TryBody.get() == S->getTryBody() &&
7049 Finally.get() == S->getFinallyStmt())
7052 // Build a new statement.
7053 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7054 CatchStmts, Finally.get());
7057 template<typename Derived>
7059 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7060 // Transform the @catch parameter, if there is one.
7061 VarDecl *Var = nullptr;
7062 if (VarDecl *FromVar = S->getCatchParamDecl()) {
7063 TypeSourceInfo *TSInfo = nullptr;
7064 if (FromVar->getTypeSourceInfo()) {
7065 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7072 T = TSInfo->getType();
7074 T = getDerived().TransformType(FromVar->getType());
7079 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7084 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7085 if (Body.isInvalid())
7088 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7093 template<typename Derived>
7095 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7096 // Transform the body.
7097 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7098 if (Body.isInvalid())
7101 // If nothing changed, just retain this statement.
7102 if (!getDerived().AlwaysRebuild() &&
7103 Body.get() == S->getFinallyBody())
7106 // Build a new statement.
7107 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7111 template<typename Derived>
7113 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7115 if (S->getThrowExpr()) {
7116 Operand = getDerived().TransformExpr(S->getThrowExpr());
7117 if (Operand.isInvalid())
7121 if (!getDerived().AlwaysRebuild() &&
7122 Operand.get() == S->getThrowExpr())
7125 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7128 template<typename Derived>
7130 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7131 ObjCAtSynchronizedStmt *S) {
7132 // Transform the object we are locking.
7133 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7134 if (Object.isInvalid())
7137 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7139 if (Object.isInvalid())
7142 // Transform the body.
7143 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7144 if (Body.isInvalid())
7147 // If nothing change, just retain the current statement.
7148 if (!getDerived().AlwaysRebuild() &&
7149 Object.get() == S->getSynchExpr() &&
7150 Body.get() == S->getSynchBody())
7153 // Build a new statement.
7154 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7155 Object.get(), Body.get());
7158 template<typename Derived>
7160 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7161 ObjCAutoreleasePoolStmt *S) {
7162 // Transform the body.
7163 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7164 if (Body.isInvalid())
7167 // If nothing changed, just retain this statement.
7168 if (!getDerived().AlwaysRebuild() &&
7169 Body.get() == S->getSubStmt())
7172 // Build a new statement.
7173 return getDerived().RebuildObjCAutoreleasePoolStmt(
7174 S->getAtLoc(), Body.get());
7177 template<typename Derived>
7179 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7180 ObjCForCollectionStmt *S) {
7181 // Transform the element statement.
7182 StmtResult Element = getDerived().TransformStmt(S->getElement());
7183 if (Element.isInvalid())
7186 // Transform the collection expression.
7187 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7188 if (Collection.isInvalid())
7191 // Transform the body.
7192 StmtResult Body = getDerived().TransformStmt(S->getBody());
7193 if (Body.isInvalid())
7196 // If nothing changed, just retain this statement.
7197 if (!getDerived().AlwaysRebuild() &&
7198 Element.get() == S->getElement() &&
7199 Collection.get() == S->getCollection() &&
7200 Body.get() == S->getBody())
7203 // Build a new statement.
7204 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7211 template <typename Derived>
7212 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7213 // Transform the exception declaration, if any.
7214 VarDecl *Var = nullptr;
7215 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7217 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7221 Var = getDerived().RebuildExceptionDecl(
7222 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7223 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7224 if (!Var || Var->isInvalidDecl())
7228 // Transform the actual exception handler.
7229 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7230 if (Handler.isInvalid())
7233 if (!getDerived().AlwaysRebuild() && !Var &&
7234 Handler.get() == S->getHandlerBlock())
7237 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7240 template <typename Derived>
7241 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7242 // Transform the try block itself.
7243 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7244 if (TryBlock.isInvalid())
7247 // Transform the handlers.
7248 bool HandlerChanged = false;
7249 SmallVector<Stmt *, 8> Handlers;
7250 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7251 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7252 if (Handler.isInvalid())
7255 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7256 Handlers.push_back(Handler.getAs<Stmt>());
7259 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7263 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7267 template<typename Derived>
7269 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7270 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7271 if (Range.isInvalid())
7274 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7275 if (Begin.isInvalid())
7277 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7278 if (End.isInvalid())
7281 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7282 if (Cond.isInvalid())
7285 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7286 if (Cond.isInvalid())
7289 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7291 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7292 if (Inc.isInvalid())
7295 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7297 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7298 if (LoopVar.isInvalid())
7301 StmtResult NewStmt = S;
7302 if (getDerived().AlwaysRebuild() ||
7303 Range.get() != S->getRangeStmt() ||
7304 Begin.get() != S->getBeginStmt() ||
7305 End.get() != S->getEndStmt() ||
7306 Cond.get() != S->getCond() ||
7307 Inc.get() != S->getInc() ||
7308 LoopVar.get() != S->getLoopVarStmt()) {
7309 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7311 S->getColonLoc(), Range.get(),
7312 Begin.get(), End.get(),
7314 Inc.get(), LoopVar.get(),
7316 if (NewStmt.isInvalid())
7320 StmtResult Body = getDerived().TransformStmt(S->getBody());
7321 if (Body.isInvalid())
7324 // Body has changed but we didn't rebuild the for-range statement. Rebuild
7325 // it now so we have a new statement to attach the body to.
7326 if (Body.get() != S->getBody() && NewStmt.get() == S) {
7327 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7329 S->getColonLoc(), Range.get(),
7330 Begin.get(), End.get(),
7332 Inc.get(), LoopVar.get(),
7334 if (NewStmt.isInvalid())
7338 if (NewStmt.get() == S)
7341 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7344 template<typename Derived>
7346 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7347 MSDependentExistsStmt *S) {
7348 // Transform the nested-name-specifier, if any.
7349 NestedNameSpecifierLoc QualifierLoc;
7350 if (S->getQualifierLoc()) {
7352 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7357 // Transform the declaration name.
7358 DeclarationNameInfo NameInfo = S->getNameInfo();
7359 if (NameInfo.getName()) {
7360 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7361 if (!NameInfo.getName())
7365 // Check whether anything changed.
7366 if (!getDerived().AlwaysRebuild() &&
7367 QualifierLoc == S->getQualifierLoc() &&
7368 NameInfo.getName() == S->getNameInfo().getName())
7371 // Determine whether this name exists, if we can.
7373 SS.Adopt(QualifierLoc);
7374 bool Dependent = false;
7375 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7376 case Sema::IER_Exists:
7377 if (S->isIfExists())
7380 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7382 case Sema::IER_DoesNotExist:
7383 if (S->isIfNotExists())
7386 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7388 case Sema::IER_Dependent:
7392 case Sema::IER_Error:
7396 // We need to continue with the instantiation, so do so now.
7397 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7398 if (SubStmt.isInvalid())
7401 // If we have resolved the name, just transform to the substatement.
7405 // The name is still dependent, so build a dependent expression again.
7406 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7413 template<typename Derived>
7415 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7416 NestedNameSpecifierLoc QualifierLoc;
7417 if (E->getQualifierLoc()) {
7419 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7424 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7425 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7429 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7430 if (Base.isInvalid())
7433 return new (SemaRef.getASTContext())
7434 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7435 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7436 QualifierLoc, E->getMemberLoc());
7439 template <typename Derived>
7440 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7441 MSPropertySubscriptExpr *E) {
7442 auto BaseRes = getDerived().TransformExpr(E->getBase());
7443 if (BaseRes.isInvalid())
7445 auto IdxRes = getDerived().TransformExpr(E->getIdx());
7446 if (IdxRes.isInvalid())
7449 if (!getDerived().AlwaysRebuild() &&
7450 BaseRes.get() == E->getBase() &&
7451 IdxRes.get() == E->getIdx())
7454 return getDerived().RebuildArraySubscriptExpr(
7455 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7458 template <typename Derived>
7459 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7460 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7461 if (TryBlock.isInvalid())
7464 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7465 if (Handler.isInvalid())
7468 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7469 Handler.get() == S->getHandler())
7472 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7473 TryBlock.get(), Handler.get());
7476 template <typename Derived>
7477 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7478 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7479 if (Block.isInvalid())
7482 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7485 template <typename Derived>
7486 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7487 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7488 if (FilterExpr.isInvalid())
7491 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7492 if (Block.isInvalid())
7495 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7499 template <typename Derived>
7500 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7501 if (isa<SEHFinallyStmt>(Handler))
7502 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7504 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7507 template<typename Derived>
7509 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7513 //===----------------------------------------------------------------------===//
7514 // OpenMP directive transformation
7515 //===----------------------------------------------------------------------===//
7516 template <typename Derived>
7517 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7518 OMPExecutableDirective *D) {
7520 // Transform the clauses
7521 llvm::SmallVector<OMPClause *, 16> TClauses;
7522 ArrayRef<OMPClause *> Clauses = D->clauses();
7523 TClauses.reserve(Clauses.size());
7524 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7527 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7528 OMPClause *Clause = getDerived().TransformOMPClause(*I);
7529 getDerived().getSema().EndOpenMPClause();
7531 TClauses.push_back(Clause);
7533 TClauses.push_back(nullptr);
7536 StmtResult AssociatedStmt;
7537 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7538 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7539 /*CurScope=*/nullptr);
7542 Sema::CompoundScopeRAII CompoundScope(getSema());
7543 int ThisCaptureLevel =
7544 Sema::getOpenMPCaptureLevels(D->getDirectiveKind());
7545 Stmt *CS = D->getAssociatedStmt();
7546 while (--ThisCaptureLevel >= 0)
7547 CS = cast<CapturedStmt>(CS)->getCapturedStmt();
7548 Body = getDerived().TransformStmt(CS);
7551 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7552 if (AssociatedStmt.isInvalid()) {
7556 if (TClauses.size() != Clauses.size()) {
7560 // Transform directive name for 'omp critical' directive.
7561 DeclarationNameInfo DirName;
7562 if (D->getDirectiveKind() == OMPD_critical) {
7563 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7564 DirName = getDerived().TransformDeclarationNameInfo(DirName);
7566 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7567 if (D->getDirectiveKind() == OMPD_cancellation_point) {
7568 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7569 } else if (D->getDirectiveKind() == OMPD_cancel) {
7570 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7573 return getDerived().RebuildOMPExecutableDirective(
7574 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7575 AssociatedStmt.get(), D->getLocStart(), D->getLocEnd());
7578 template <typename Derived>
7580 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7581 DeclarationNameInfo DirName;
7582 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7584 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7585 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7589 template <typename Derived>
7591 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7592 DeclarationNameInfo DirName;
7593 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7595 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7596 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7600 template <typename Derived>
7602 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7603 DeclarationNameInfo DirName;
7604 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7606 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7607 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7611 template <typename Derived>
7613 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7614 DeclarationNameInfo DirName;
7615 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7617 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7618 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7622 template <typename Derived>
7624 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7625 DeclarationNameInfo DirName;
7626 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7628 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7629 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7633 template <typename Derived>
7635 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7636 DeclarationNameInfo DirName;
7637 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7639 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7640 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7644 template <typename Derived>
7646 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7647 DeclarationNameInfo DirName;
7648 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7650 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7651 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7655 template <typename Derived>
7657 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
7658 DeclarationNameInfo DirName;
7659 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
7661 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7662 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7666 template <typename Derived>
7668 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
7669 getDerived().getSema().StartOpenMPDSABlock(
7670 OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
7671 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7672 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7676 template <typename Derived>
7677 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
7678 OMPParallelForDirective *D) {
7679 DeclarationNameInfo DirName;
7680 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
7681 nullptr, D->getLocStart());
7682 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7683 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7687 template <typename Derived>
7688 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
7689 OMPParallelForSimdDirective *D) {
7690 DeclarationNameInfo DirName;
7691 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
7692 nullptr, D->getLocStart());
7693 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7694 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7698 template <typename Derived>
7699 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
7700 OMPParallelSectionsDirective *D) {
7701 DeclarationNameInfo DirName;
7702 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
7703 nullptr, D->getLocStart());
7704 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7705 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7709 template <typename Derived>
7711 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
7712 DeclarationNameInfo DirName;
7713 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
7715 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7716 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7720 template <typename Derived>
7721 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
7722 OMPTaskyieldDirective *D) {
7723 DeclarationNameInfo DirName;
7724 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
7726 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7727 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7731 template <typename Derived>
7733 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
7734 DeclarationNameInfo DirName;
7735 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
7737 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7738 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7742 template <typename Derived>
7744 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
7745 DeclarationNameInfo DirName;
7746 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
7748 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7749 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7753 template <typename Derived>
7754 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
7755 OMPTaskgroupDirective *D) {
7756 DeclarationNameInfo DirName;
7757 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
7759 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7760 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7764 template <typename Derived>
7766 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
7767 DeclarationNameInfo DirName;
7768 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
7770 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7771 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7775 template <typename Derived>
7777 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
7778 DeclarationNameInfo DirName;
7779 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
7781 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7782 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7786 template <typename Derived>
7788 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
7789 DeclarationNameInfo DirName;
7790 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
7792 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7793 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7797 template <typename Derived>
7799 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
7800 DeclarationNameInfo DirName;
7801 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
7803 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7804 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7808 template <typename Derived>
7809 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
7810 OMPTargetDataDirective *D) {
7811 DeclarationNameInfo DirName;
7812 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
7814 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7815 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7819 template <typename Derived>
7820 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
7821 OMPTargetEnterDataDirective *D) {
7822 DeclarationNameInfo DirName;
7823 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
7824 nullptr, D->getLocStart());
7825 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7826 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7830 template <typename Derived>
7831 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
7832 OMPTargetExitDataDirective *D) {
7833 DeclarationNameInfo DirName;
7834 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
7835 nullptr, D->getLocStart());
7836 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7837 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7841 template <typename Derived>
7842 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
7843 OMPTargetParallelDirective *D) {
7844 DeclarationNameInfo DirName;
7845 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
7846 nullptr, D->getLocStart());
7847 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7848 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7852 template <typename Derived>
7853 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
7854 OMPTargetParallelForDirective *D) {
7855 DeclarationNameInfo DirName;
7856 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
7857 nullptr, D->getLocStart());
7858 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7859 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7863 template <typename Derived>
7864 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
7865 OMPTargetUpdateDirective *D) {
7866 DeclarationNameInfo DirName;
7867 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
7868 nullptr, D->getLocStart());
7869 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7870 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7874 template <typename Derived>
7876 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
7877 DeclarationNameInfo DirName;
7878 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
7880 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7881 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7885 template <typename Derived>
7886 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
7887 OMPCancellationPointDirective *D) {
7888 DeclarationNameInfo DirName;
7889 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
7890 nullptr, D->getLocStart());
7891 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7892 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7896 template <typename Derived>
7898 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
7899 DeclarationNameInfo DirName;
7900 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
7902 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7903 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7907 template <typename Derived>
7909 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
7910 DeclarationNameInfo DirName;
7911 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
7913 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7914 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7918 template <typename Derived>
7919 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
7920 OMPTaskLoopSimdDirective *D) {
7921 DeclarationNameInfo DirName;
7922 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
7923 nullptr, D->getLocStart());
7924 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7925 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7929 template <typename Derived>
7930 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
7931 OMPDistributeDirective *D) {
7932 DeclarationNameInfo DirName;
7933 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
7935 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7936 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7940 template <typename Derived>
7941 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
7942 OMPDistributeParallelForDirective *D) {
7943 DeclarationNameInfo DirName;
7944 getDerived().getSema().StartOpenMPDSABlock(
7945 OMPD_distribute_parallel_for, DirName, nullptr, D->getLocStart());
7946 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7947 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7951 template <typename Derived>
7953 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
7954 OMPDistributeParallelForSimdDirective *D) {
7955 DeclarationNameInfo DirName;
7956 getDerived().getSema().StartOpenMPDSABlock(
7957 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getLocStart());
7958 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7959 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7963 template <typename Derived>
7964 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
7965 OMPDistributeSimdDirective *D) {
7966 DeclarationNameInfo DirName;
7967 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
7968 nullptr, D->getLocStart());
7969 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7970 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7974 template <typename Derived>
7975 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
7976 OMPTargetParallelForSimdDirective *D) {
7977 DeclarationNameInfo DirName;
7978 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for_simd,
7981 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7982 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7986 template <typename Derived>
7987 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
7988 OMPTargetSimdDirective *D) {
7989 DeclarationNameInfo DirName;
7990 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
7992 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7993 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7997 template <typename Derived>
7998 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
7999 OMPTeamsDistributeDirective *D) {
8000 DeclarationNameInfo DirName;
8001 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8002 nullptr, D->getLocStart());
8003 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8004 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8008 template <typename Derived>
8009 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8010 OMPTeamsDistributeSimdDirective *D) {
8011 DeclarationNameInfo DirName;
8012 getDerived().getSema().StartOpenMPDSABlock(
8013 OMPD_teams_distribute_simd, DirName, nullptr, D->getLocStart());
8014 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8015 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8019 template <typename Derived>
8020 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8021 OMPTeamsDistributeParallelForSimdDirective *D) {
8022 DeclarationNameInfo DirName;
8023 getDerived().getSema().StartOpenMPDSABlock(
8024 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr, D->getLocStart());
8025 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8026 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8030 template <typename Derived>
8031 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8032 OMPTeamsDistributeParallelForDirective *D) {
8033 DeclarationNameInfo DirName;
8034 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute_parallel_for,
8035 DirName, nullptr, D->getLocStart());
8036 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8037 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8041 template <typename Derived>
8042 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8043 OMPTargetTeamsDirective *D) {
8044 DeclarationNameInfo DirName;
8045 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8046 nullptr, D->getLocStart());
8047 auto Res = getDerived().TransformOMPExecutableDirective(D);
8048 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8052 template <typename Derived>
8053 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8054 OMPTargetTeamsDistributeDirective *D) {
8055 DeclarationNameInfo DirName;
8056 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_distribute,
8057 DirName, nullptr, D->getLocStart());
8058 auto Res = getDerived().TransformOMPExecutableDirective(D);
8059 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8063 template <typename Derived>
8065 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8066 OMPTargetTeamsDistributeParallelForDirective *D) {
8067 DeclarationNameInfo DirName;
8068 getDerived().getSema().StartOpenMPDSABlock(
8069 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8071 auto Res = getDerived().TransformOMPExecutableDirective(D);
8072 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8076 template <typename Derived>
8077 StmtResult TreeTransform<Derived>::
8078 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8079 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8080 DeclarationNameInfo DirName;
8081 getDerived().getSema().StartOpenMPDSABlock(
8082 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8084 auto Res = getDerived().TransformOMPExecutableDirective(D);
8085 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8089 template <typename Derived>
8091 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8092 OMPTargetTeamsDistributeSimdDirective *D) {
8093 DeclarationNameInfo DirName;
8094 getDerived().getSema().StartOpenMPDSABlock(
8095 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getLocStart());
8096 auto Res = getDerived().TransformOMPExecutableDirective(D);
8097 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8102 //===----------------------------------------------------------------------===//
8103 // OpenMP clause transformation
8104 //===----------------------------------------------------------------------===//
8105 template <typename Derived>
8106 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8107 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8108 if (Cond.isInvalid())
8110 return getDerived().RebuildOMPIfClause(
8111 C->getNameModifier(), Cond.get(), C->getLocStart(), C->getLParenLoc(),
8112 C->getNameModifierLoc(), C->getColonLoc(), C->getLocEnd());
8115 template <typename Derived>
8116 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8117 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8118 if (Cond.isInvalid())
8120 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
8121 C->getLParenLoc(), C->getLocEnd());
8124 template <typename Derived>
8126 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8127 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8128 if (NumThreads.isInvalid())
8130 return getDerived().RebuildOMPNumThreadsClause(
8131 NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8134 template <typename Derived>
8136 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8137 ExprResult E = getDerived().TransformExpr(C->getSafelen());
8140 return getDerived().RebuildOMPSafelenClause(
8141 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8144 template <typename Derived>
8146 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8147 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8150 return getDerived().RebuildOMPSimdlenClause(
8151 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8154 template <typename Derived>
8156 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8157 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8160 return getDerived().RebuildOMPCollapseClause(
8161 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8164 template <typename Derived>
8166 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8167 return getDerived().RebuildOMPDefaultClause(
8168 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
8169 C->getLParenLoc(), C->getLocEnd());
8172 template <typename Derived>
8174 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8175 return getDerived().RebuildOMPProcBindClause(
8176 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
8177 C->getLParenLoc(), C->getLocEnd());
8180 template <typename Derived>
8182 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8183 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8186 return getDerived().RebuildOMPScheduleClause(
8187 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8188 C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
8189 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8190 C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
8193 template <typename Derived>
8195 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8197 if (auto *Num = C->getNumForLoops()) {
8198 E = getDerived().TransformExpr(Num);
8202 return getDerived().RebuildOMPOrderedClause(C->getLocStart(), C->getLocEnd(),
8203 C->getLParenLoc(), E.get());
8206 template <typename Derived>
8208 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8209 // No need to rebuild this clause, no template-dependent parameters.
8213 template <typename Derived>
8215 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8216 // No need to rebuild this clause, no template-dependent parameters.
8220 template <typename Derived>
8222 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8223 // No need to rebuild this clause, no template-dependent parameters.
8227 template <typename Derived>
8228 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8229 // No need to rebuild this clause, no template-dependent parameters.
8233 template <typename Derived>
8234 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8235 // No need to rebuild this clause, no template-dependent parameters.
8239 template <typename Derived>
8241 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8242 // No need to rebuild this clause, no template-dependent parameters.
8246 template <typename Derived>
8248 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8249 // No need to rebuild this clause, no template-dependent parameters.
8253 template <typename Derived>
8255 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8256 // No need to rebuild this clause, no template-dependent parameters.
8260 template <typename Derived>
8262 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8263 // No need to rebuild this clause, no template-dependent parameters.
8267 template <typename Derived>
8268 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8269 // No need to rebuild this clause, no template-dependent parameters.
8273 template <typename Derived>
8275 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8276 // No need to rebuild this clause, no template-dependent parameters.
8280 template <typename Derived>
8282 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8283 llvm::SmallVector<Expr *, 16> Vars;
8284 Vars.reserve(C->varlist_size());
8285 for (auto *VE : C->varlists()) {
8286 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8287 if (EVar.isInvalid())
8289 Vars.push_back(EVar.get());
8291 return getDerived().RebuildOMPPrivateClause(
8292 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8295 template <typename Derived>
8296 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8297 OMPFirstprivateClause *C) {
8298 llvm::SmallVector<Expr *, 16> Vars;
8299 Vars.reserve(C->varlist_size());
8300 for (auto *VE : C->varlists()) {
8301 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8302 if (EVar.isInvalid())
8304 Vars.push_back(EVar.get());
8306 return getDerived().RebuildOMPFirstprivateClause(
8307 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8310 template <typename Derived>
8312 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8313 llvm::SmallVector<Expr *, 16> Vars;
8314 Vars.reserve(C->varlist_size());
8315 for (auto *VE : C->varlists()) {
8316 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8317 if (EVar.isInvalid())
8319 Vars.push_back(EVar.get());
8321 return getDerived().RebuildOMPLastprivateClause(
8322 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8325 template <typename Derived>
8327 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8328 llvm::SmallVector<Expr *, 16> Vars;
8329 Vars.reserve(C->varlist_size());
8330 for (auto *VE : C->varlists()) {
8331 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8332 if (EVar.isInvalid())
8334 Vars.push_back(EVar.get());
8336 return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
8337 C->getLParenLoc(), C->getLocEnd());
8340 template <typename Derived>
8342 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8343 llvm::SmallVector<Expr *, 16> Vars;
8344 Vars.reserve(C->varlist_size());
8345 for (auto *VE : C->varlists()) {
8346 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8347 if (EVar.isInvalid())
8349 Vars.push_back(EVar.get());
8351 CXXScopeSpec ReductionIdScopeSpec;
8352 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8354 DeclarationNameInfo NameInfo = C->getNameInfo();
8355 if (NameInfo.getName()) {
8356 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8357 if (!NameInfo.getName())
8360 // Build a list of all UDR decls with the same names ranged by the Scopes.
8361 // The Scope boundary is a duplication of the previous decl.
8362 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8363 for (auto *E : C->reduction_ops()) {
8364 // Transform all the decls.
8366 auto *ULE = cast<UnresolvedLookupExpr>(E);
8367 UnresolvedSet<8> Decls;
8368 for (auto *D : ULE->decls()) {
8370 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8371 Decls.addDecl(InstD, InstD->getAccess());
8373 UnresolvedReductions.push_back(
8374 UnresolvedLookupExpr::Create(
8375 SemaRef.Context, /*NamingClass=*/nullptr,
8376 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8377 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8378 Decls.begin(), Decls.end()));
8380 UnresolvedReductions.push_back(nullptr);
8382 return getDerived().RebuildOMPReductionClause(
8383 Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
8384 C->getLocEnd(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8387 template <typename Derived>
8389 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8390 llvm::SmallVector<Expr *, 16> Vars;
8391 Vars.reserve(C->varlist_size());
8392 for (auto *VE : C->varlists()) {
8393 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8394 if (EVar.isInvalid())
8396 Vars.push_back(EVar.get());
8398 ExprResult Step = getDerived().TransformExpr(C->getStep());
8399 if (Step.isInvalid())
8401 return getDerived().RebuildOMPLinearClause(
8402 Vars, Step.get(), C->getLocStart(), C->getLParenLoc(), C->getModifier(),
8403 C->getModifierLoc(), C->getColonLoc(), C->getLocEnd());
8406 template <typename Derived>
8408 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8409 llvm::SmallVector<Expr *, 16> Vars;
8410 Vars.reserve(C->varlist_size());
8411 for (auto *VE : C->varlists()) {
8412 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8413 if (EVar.isInvalid())
8415 Vars.push_back(EVar.get());
8417 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8418 if (Alignment.isInvalid())
8420 return getDerived().RebuildOMPAlignedClause(
8421 Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
8422 C->getColonLoc(), C->getLocEnd());
8425 template <typename Derived>
8427 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8428 llvm::SmallVector<Expr *, 16> Vars;
8429 Vars.reserve(C->varlist_size());
8430 for (auto *VE : C->varlists()) {
8431 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8432 if (EVar.isInvalid())
8434 Vars.push_back(EVar.get());
8436 return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
8437 C->getLParenLoc(), C->getLocEnd());
8440 template <typename Derived>
8442 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8443 llvm::SmallVector<Expr *, 16> Vars;
8444 Vars.reserve(C->varlist_size());
8445 for (auto *VE : C->varlists()) {
8446 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8447 if (EVar.isInvalid())
8449 Vars.push_back(EVar.get());
8451 return getDerived().RebuildOMPCopyprivateClause(
8452 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8455 template <typename Derived>
8456 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8457 llvm::SmallVector<Expr *, 16> Vars;
8458 Vars.reserve(C->varlist_size());
8459 for (auto *VE : C->varlists()) {
8460 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8461 if (EVar.isInvalid())
8463 Vars.push_back(EVar.get());
8465 return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
8466 C->getLParenLoc(), C->getLocEnd());
8469 template <typename Derived>
8471 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8472 llvm::SmallVector<Expr *, 16> Vars;
8473 Vars.reserve(C->varlist_size());
8474 for (auto *VE : C->varlists()) {
8475 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8476 if (EVar.isInvalid())
8478 Vars.push_back(EVar.get());
8480 return getDerived().RebuildOMPDependClause(
8481 C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8482 C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8485 template <typename Derived>
8487 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
8488 ExprResult E = getDerived().TransformExpr(C->getDevice());
8491 return getDerived().RebuildOMPDeviceClause(
8492 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8495 template <typename Derived>
8496 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
8497 llvm::SmallVector<Expr *, 16> Vars;
8498 Vars.reserve(C->varlist_size());
8499 for (auto *VE : C->varlists()) {
8500 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8501 if (EVar.isInvalid())
8503 Vars.push_back(EVar.get());
8505 return getDerived().RebuildOMPMapClause(
8506 C->getMapTypeModifier(), C->getMapType(), C->isImplicitMapType(),
8507 C->getMapLoc(), C->getColonLoc(), Vars, C->getLocStart(),
8508 C->getLParenLoc(), C->getLocEnd());
8511 template <typename Derived>
8513 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
8514 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
8517 return getDerived().RebuildOMPNumTeamsClause(
8518 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8521 template <typename Derived>
8523 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
8524 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
8527 return getDerived().RebuildOMPThreadLimitClause(
8528 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8531 template <typename Derived>
8533 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
8534 ExprResult E = getDerived().TransformExpr(C->getPriority());
8537 return getDerived().RebuildOMPPriorityClause(
8538 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8541 template <typename Derived>
8543 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
8544 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
8547 return getDerived().RebuildOMPGrainsizeClause(
8548 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8551 template <typename Derived>
8553 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
8554 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
8557 return getDerived().RebuildOMPNumTasksClause(
8558 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8561 template <typename Derived>
8562 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
8563 ExprResult E = getDerived().TransformExpr(C->getHint());
8566 return getDerived().RebuildOMPHintClause(E.get(), C->getLocStart(),
8567 C->getLParenLoc(), C->getLocEnd());
8570 template <typename Derived>
8571 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
8572 OMPDistScheduleClause *C) {
8573 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8576 return getDerived().RebuildOMPDistScheduleClause(
8577 C->getDistScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
8578 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
8581 template <typename Derived>
8583 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
8587 template <typename Derived>
8588 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
8589 llvm::SmallVector<Expr *, 16> Vars;
8590 Vars.reserve(C->varlist_size());
8591 for (auto *VE : C->varlists()) {
8592 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8593 if (EVar.isInvalid())
8595 Vars.push_back(EVar.get());
8597 return getDerived().RebuildOMPToClause(Vars, C->getLocStart(),
8598 C->getLParenLoc(), C->getLocEnd());
8601 template <typename Derived>
8602 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
8603 llvm::SmallVector<Expr *, 16> Vars;
8604 Vars.reserve(C->varlist_size());
8605 for (auto *VE : C->varlists()) {
8606 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8607 if (EVar.isInvalid())
8609 Vars.push_back(EVar.get());
8611 return getDerived().RebuildOMPFromClause(Vars, C->getLocStart(),
8612 C->getLParenLoc(), C->getLocEnd());
8615 template <typename Derived>
8616 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
8617 OMPUseDevicePtrClause *C) {
8618 llvm::SmallVector<Expr *, 16> Vars;
8619 Vars.reserve(C->varlist_size());
8620 for (auto *VE : C->varlists()) {
8621 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8622 if (EVar.isInvalid())
8624 Vars.push_back(EVar.get());
8626 return getDerived().RebuildOMPUseDevicePtrClause(
8627 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8630 template <typename Derived>
8632 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
8633 llvm::SmallVector<Expr *, 16> Vars;
8634 Vars.reserve(C->varlist_size());
8635 for (auto *VE : C->varlists()) {
8636 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8637 if (EVar.isInvalid())
8639 Vars.push_back(EVar.get());
8641 return getDerived().RebuildOMPIsDevicePtrClause(
8642 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8645 //===----------------------------------------------------------------------===//
8646 // Expression transformation
8647 //===----------------------------------------------------------------------===//
8648 template<typename Derived>
8650 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
8651 if (!E->isTypeDependent())
8654 return getDerived().RebuildPredefinedExpr(E->getLocation(),
8658 template<typename Derived>
8660 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
8661 NestedNameSpecifierLoc QualifierLoc;
8662 if (E->getQualifierLoc()) {
8664 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8670 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
8675 DeclarationNameInfo NameInfo = E->getNameInfo();
8676 if (NameInfo.getName()) {
8677 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8678 if (!NameInfo.getName())
8682 if (!getDerived().AlwaysRebuild() &&
8683 QualifierLoc == E->getQualifierLoc() &&
8684 ND == E->getDecl() &&
8685 NameInfo.getName() == E->getDecl()->getDeclName() &&
8686 !E->hasExplicitTemplateArgs()) {
8688 // Mark it referenced in the new context regardless.
8689 // FIXME: this is a bit instantiation-specific.
8690 SemaRef.MarkDeclRefReferenced(E);
8695 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
8696 if (E->hasExplicitTemplateArgs()) {
8697 TemplateArgs = &TransArgs;
8698 TransArgs.setLAngleLoc(E->getLAngleLoc());
8699 TransArgs.setRAngleLoc(E->getRAngleLoc());
8700 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
8701 E->getNumTemplateArgs(),
8706 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
8710 template<typename Derived>
8712 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
8716 template<typename Derived>
8718 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
8722 template<typename Derived>
8724 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
8728 template<typename Derived>
8730 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
8734 template<typename Derived>
8736 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
8740 template<typename Derived>
8742 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
8743 if (FunctionDecl *FD = E->getDirectCallee())
8744 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
8745 return SemaRef.MaybeBindToTemporary(E);
8748 template<typename Derived>
8750 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
8751 ExprResult ControllingExpr =
8752 getDerived().TransformExpr(E->getControllingExpr());
8753 if (ControllingExpr.isInvalid())
8756 SmallVector<Expr *, 4> AssocExprs;
8757 SmallVector<TypeSourceInfo *, 4> AssocTypes;
8758 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
8759 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
8761 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
8764 AssocTypes.push_back(AssocType);
8766 AssocTypes.push_back(nullptr);
8769 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
8770 if (AssocExpr.isInvalid())
8772 AssocExprs.push_back(AssocExpr.get());
8775 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
8778 ControllingExpr.get(),
8783 template<typename Derived>
8785 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
8786 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8787 if (SubExpr.isInvalid())
8790 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
8793 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
8797 /// \brief The operand of a unary address-of operator has special rules: it's
8798 /// allowed to refer to a non-static member of a class even if there's no 'this'
8799 /// object available.
8800 template<typename Derived>
8802 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
8803 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
8804 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
8806 return getDerived().TransformExpr(E);
8809 template<typename Derived>
8811 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
8813 if (E->getOpcode() == UO_AddrOf)
8814 SubExpr = TransformAddressOfOperand(E->getSubExpr());
8816 SubExpr = TransformExpr(E->getSubExpr());
8817 if (SubExpr.isInvalid())
8820 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
8823 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
8828 template<typename Derived>
8830 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
8831 // Transform the type.
8832 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
8836 // Transform all of the components into components similar to what the
8838 // FIXME: It would be slightly more efficient in the non-dependent case to
8839 // just map FieldDecls, rather than requiring the rebuilder to look for
8840 // the fields again. However, __builtin_offsetof is rare enough in
8841 // template code that we don't care.
8842 bool ExprChanged = false;
8843 typedef Sema::OffsetOfComponent Component;
8844 SmallVector<Component, 4> Components;
8845 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
8846 const OffsetOfNode &ON = E->getComponent(I);
8848 Comp.isBrackets = true;
8849 Comp.LocStart = ON.getSourceRange().getBegin();
8850 Comp.LocEnd = ON.getSourceRange().getEnd();
8851 switch (ON.getKind()) {
8852 case OffsetOfNode::Array: {
8853 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
8854 ExprResult Index = getDerived().TransformExpr(FromIndex);
8855 if (Index.isInvalid())
8858 ExprChanged = ExprChanged || Index.get() != FromIndex;
8859 Comp.isBrackets = true;
8860 Comp.U.E = Index.get();
8864 case OffsetOfNode::Field:
8865 case OffsetOfNode::Identifier:
8866 Comp.isBrackets = false;
8867 Comp.U.IdentInfo = ON.getFieldName();
8868 if (!Comp.U.IdentInfo)
8873 case OffsetOfNode::Base:
8874 // Will be recomputed during the rebuild.
8878 Components.push_back(Comp);
8881 // If nothing changed, retain the existing expression.
8882 if (!getDerived().AlwaysRebuild() &&
8883 Type == E->getTypeSourceInfo() &&
8887 // Build a new offsetof expression.
8888 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
8889 Components, E->getRParenLoc());
8892 template<typename Derived>
8894 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
8895 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
8896 "opaque value expression requires transformation");
8900 template<typename Derived>
8902 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
8906 template<typename Derived>
8908 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
8909 // Rebuild the syntactic form. The original syntactic form has
8910 // opaque-value expressions in it, so strip those away and rebuild
8911 // the result. This is a really awful way of doing this, but the
8912 // better solution (rebuilding the semantic expressions and
8913 // rebinding OVEs as necessary) doesn't work; we'd need
8914 // TreeTransform to not strip away implicit conversions.
8915 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
8916 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
8917 if (result.isInvalid()) return ExprError();
8919 // If that gives us a pseudo-object result back, the pseudo-object
8920 // expression must have been an lvalue-to-rvalue conversion which we
8922 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
8923 result = SemaRef.checkPseudoObjectRValue(result.get());
8928 template<typename Derived>
8930 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
8931 UnaryExprOrTypeTraitExpr *E) {
8932 if (E->isArgumentType()) {
8933 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
8935 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
8939 if (!getDerived().AlwaysRebuild() && OldT == NewT)
8942 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
8944 E->getSourceRange());
8947 // C++0x [expr.sizeof]p1:
8948 // The operand is either an expression, which is an unevaluated operand
8950 EnterExpressionEvaluationContext Unevaluated(
8951 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
8952 Sema::ReuseLambdaContextDecl);
8954 // Try to recover if we have something like sizeof(T::X) where X is a type.
8955 // Notably, there must be *exactly* one set of parens if X is a type.
8956 TypeSourceInfo *RecoveryTSI = nullptr;
8958 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
8960 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
8961 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
8962 PE, DRE, false, &RecoveryTSI);
8964 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
8967 return getDerived().RebuildUnaryExprOrTypeTrait(
8968 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
8969 } else if (SubExpr.isInvalid())
8972 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
8975 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
8976 E->getOperatorLoc(),
8978 E->getSourceRange());
8981 template<typename Derived>
8983 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
8984 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8985 if (LHS.isInvalid())
8988 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
8989 if (RHS.isInvalid())
8993 if (!getDerived().AlwaysRebuild() &&
8994 LHS.get() == E->getLHS() &&
8995 RHS.get() == E->getRHS())
8998 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
8999 /*FIXME:*/E->getLHS()->getLocStart(),
9001 E->getRBracketLoc());
9004 template <typename Derived>
9006 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9007 ExprResult Base = getDerived().TransformExpr(E->getBase());
9008 if (Base.isInvalid())
9011 ExprResult LowerBound;
9012 if (E->getLowerBound()) {
9013 LowerBound = getDerived().TransformExpr(E->getLowerBound());
9014 if (LowerBound.isInvalid())
9019 if (E->getLength()) {
9020 Length = getDerived().TransformExpr(E->getLength());
9021 if (Length.isInvalid())
9025 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9026 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9029 return getDerived().RebuildOMPArraySectionExpr(
9030 Base.get(), E->getBase()->getLocEnd(), LowerBound.get(), E->getColonLoc(),
9031 Length.get(), E->getRBracketLoc());
9034 template<typename Derived>
9036 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9037 // Transform the callee.
9038 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9039 if (Callee.isInvalid())
9042 // Transform arguments.
9043 bool ArgChanged = false;
9044 SmallVector<Expr*, 8> Args;
9045 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9049 if (!getDerived().AlwaysRebuild() &&
9050 Callee.get() == E->getCallee() &&
9052 return SemaRef.MaybeBindToTemporary(E);
9054 // FIXME: Wrong source location information for the '('.
9055 SourceLocation FakeLParenLoc
9056 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9057 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9062 template<typename Derived>
9064 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9065 ExprResult Base = getDerived().TransformExpr(E->getBase());
9066 if (Base.isInvalid())
9069 NestedNameSpecifierLoc QualifierLoc;
9070 if (E->hasQualifier()) {
9072 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9077 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9080 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9081 E->getMemberDecl()));
9085 NamedDecl *FoundDecl = E->getFoundDecl();
9086 if (FoundDecl == E->getMemberDecl()) {
9089 FoundDecl = cast_or_null<NamedDecl>(
9090 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9095 if (!getDerived().AlwaysRebuild() &&
9096 Base.get() == E->getBase() &&
9097 QualifierLoc == E->getQualifierLoc() &&
9098 Member == E->getMemberDecl() &&
9099 FoundDecl == E->getFoundDecl() &&
9100 !E->hasExplicitTemplateArgs()) {
9102 // Mark it referenced in the new context regardless.
9103 // FIXME: this is a bit instantiation-specific.
9104 SemaRef.MarkMemberReferenced(E);
9109 TemplateArgumentListInfo TransArgs;
9110 if (E->hasExplicitTemplateArgs()) {
9111 TransArgs.setLAngleLoc(E->getLAngleLoc());
9112 TransArgs.setRAngleLoc(E->getRAngleLoc());
9113 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9114 E->getNumTemplateArgs(),
9119 // FIXME: Bogus source location for the operator
9120 SourceLocation FakeOperatorLoc =
9121 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9123 // FIXME: to do this check properly, we will need to preserve the
9124 // first-qualifier-in-scope here, just in case we had a dependent
9125 // base (and therefore couldn't do the check) and a
9126 // nested-name-qualifier (and therefore could do the lookup).
9127 NamedDecl *FirstQualifierInScope = nullptr;
9128 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9129 if (MemberNameInfo.getName()) {
9130 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9131 if (!MemberNameInfo.getName())
9135 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9142 (E->hasExplicitTemplateArgs()
9143 ? &TransArgs : nullptr),
9144 FirstQualifierInScope);
9147 template<typename Derived>
9149 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9150 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9151 if (LHS.isInvalid())
9154 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9155 if (RHS.isInvalid())
9158 if (!getDerived().AlwaysRebuild() &&
9159 LHS.get() == E->getLHS() &&
9160 RHS.get() == E->getRHS())
9163 Sema::FPContractStateRAII FPContractState(getSema());
9164 getSema().FPFeatures = E->getFPFeatures();
9166 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9167 LHS.get(), RHS.get());
9170 template<typename Derived>
9172 TreeTransform<Derived>::TransformCompoundAssignOperator(
9173 CompoundAssignOperator *E) {
9174 return getDerived().TransformBinaryOperator(E);
9177 template<typename Derived>
9178 ExprResult TreeTransform<Derived>::
9179 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9180 // Just rebuild the common and RHS expressions and see whether we
9183 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9184 if (commonExpr.isInvalid())
9187 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9188 if (rhs.isInvalid())
9191 if (!getDerived().AlwaysRebuild() &&
9192 commonExpr.get() == e->getCommon() &&
9193 rhs.get() == e->getFalseExpr())
9196 return getDerived().RebuildConditionalOperator(commonExpr.get(),
9197 e->getQuestionLoc(),
9203 template<typename Derived>
9205 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9206 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9207 if (Cond.isInvalid())
9210 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9211 if (LHS.isInvalid())
9214 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9215 if (RHS.isInvalid())
9218 if (!getDerived().AlwaysRebuild() &&
9219 Cond.get() == E->getCond() &&
9220 LHS.get() == E->getLHS() &&
9221 RHS.get() == E->getRHS())
9224 return getDerived().RebuildConditionalOperator(Cond.get(),
9225 E->getQuestionLoc(),
9231 template<typename Derived>
9233 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9234 // Implicit casts are eliminated during transformation, since they
9235 // will be recomputed by semantic analysis after transformation.
9236 return getDerived().TransformExpr(E->getSubExprAsWritten());
9239 template<typename Derived>
9241 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9242 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9247 = getDerived().TransformExpr(E->getSubExprAsWritten());
9248 if (SubExpr.isInvalid())
9251 if (!getDerived().AlwaysRebuild() &&
9252 Type == E->getTypeInfoAsWritten() &&
9253 SubExpr.get() == E->getSubExpr())
9256 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9262 template<typename Derived>
9264 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9265 TypeSourceInfo *OldT = E->getTypeSourceInfo();
9266 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9270 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9271 if (Init.isInvalid())
9274 if (!getDerived().AlwaysRebuild() &&
9276 Init.get() == E->getInitializer())
9277 return SemaRef.MaybeBindToTemporary(E);
9279 // Note: the expression type doesn't necessarily match the
9280 // type-as-written, but that's okay, because it should always be
9281 // derivable from the initializer.
9283 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
9284 /*FIXME:*/E->getInitializer()->getLocEnd(),
9288 template<typename Derived>
9290 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9291 ExprResult Base = getDerived().TransformExpr(E->getBase());
9292 if (Base.isInvalid())
9295 if (!getDerived().AlwaysRebuild() &&
9296 Base.get() == E->getBase())
9299 // FIXME: Bad source location
9300 SourceLocation FakeOperatorLoc =
9301 SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
9302 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9303 E->getAccessorLoc(),
9307 template<typename Derived>
9309 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9310 if (InitListExpr *Syntactic = E->getSyntacticForm())
9313 bool InitChanged = false;
9315 SmallVector<Expr*, 4> Inits;
9316 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9317 Inits, &InitChanged))
9320 if (!getDerived().AlwaysRebuild() && !InitChanged) {
9321 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9322 // in some cases. We can't reuse it in general, because the syntactic and
9323 // semantic forms are linked, and we can't know that semantic form will
9324 // match even if the syntactic form does.
9327 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9328 E->getRBraceLoc(), E->getType());
9331 template<typename Derived>
9333 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9336 // transform the initializer value
9337 ExprResult Init = getDerived().TransformExpr(E->getInit());
9338 if (Init.isInvalid())
9341 // transform the designators.
9342 SmallVector<Expr*, 4> ArrayExprs;
9343 bool ExprChanged = false;
9344 for (const DesignatedInitExpr::Designator &D : E->designators()) {
9345 if (D.isFieldDesignator()) {
9346 Desig.AddDesignator(Designator::getField(D.getFieldName(),
9350 FieldDecl *Field = cast_or_null<FieldDecl>(
9351 getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
9352 if (Field != D.getField())
9353 // Rebuild the expression when the transformed FieldDecl is
9354 // different to the already assigned FieldDecl.
9357 // Ensure that the designator expression is rebuilt when there isn't
9358 // a resolved FieldDecl in the designator as we don't want to assign
9359 // a FieldDecl to a pattern designator that will be instantiated again.
9365 if (D.isArrayDesignator()) {
9366 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
9367 if (Index.isInvalid())
9370 Desig.AddDesignator(
9371 Designator::getArray(Index.get(), D.getLBracketLoc()));
9373 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
9374 ArrayExprs.push_back(Index.get());
9378 assert(D.isArrayRangeDesignator() && "New kind of designator?");
9380 = getDerived().TransformExpr(E->getArrayRangeStart(D));
9381 if (Start.isInvalid())
9384 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
9385 if (End.isInvalid())
9388 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
9391 D.getEllipsisLoc()));
9393 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
9394 End.get() != E->getArrayRangeEnd(D);
9396 ArrayExprs.push_back(Start.get());
9397 ArrayExprs.push_back(End.get());
9400 if (!getDerived().AlwaysRebuild() &&
9401 Init.get() == E->getInit() &&
9405 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
9406 E->getEqualOrColonLoc(),
9407 E->usesGNUSyntax(), Init.get());
9410 // Seems that if TransformInitListExpr() only works on the syntactic form of an
9411 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
9412 template<typename Derived>
9414 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
9415 DesignatedInitUpdateExpr *E) {
9416 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
9421 template<typename Derived>
9423 TreeTransform<Derived>::TransformNoInitExpr(
9425 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
9429 template<typename Derived>
9431 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
9432 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
9436 template<typename Derived>
9438 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
9439 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
9443 template<typename Derived>
9445 TreeTransform<Derived>::TransformImplicitValueInitExpr(
9446 ImplicitValueInitExpr *E) {
9447 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
9449 // FIXME: Will we ever have proper type location here? Will we actually
9450 // need to transform the type?
9451 QualType T = getDerived().TransformType(E->getType());
9455 if (!getDerived().AlwaysRebuild() &&
9459 return getDerived().RebuildImplicitValueInitExpr(T);
9462 template<typename Derived>
9464 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
9465 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
9469 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9470 if (SubExpr.isInvalid())
9473 if (!getDerived().AlwaysRebuild() &&
9474 TInfo == E->getWrittenTypeInfo() &&
9475 SubExpr.get() == E->getSubExpr())
9478 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
9479 TInfo, E->getRParenLoc());
9482 template<typename Derived>
9484 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
9485 bool ArgumentChanged = false;
9486 SmallVector<Expr*, 4> Inits;
9487 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
9491 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
9496 /// \brief Transform an address-of-label expression.
9498 /// By default, the transformation of an address-of-label expression always
9499 /// rebuilds the expression, so that the label identifier can be resolved to
9500 /// the corresponding label statement by semantic analysis.
9501 template<typename Derived>
9503 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
9504 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
9509 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
9510 cast<LabelDecl>(LD));
9513 template<typename Derived>
9515 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
9516 SemaRef.ActOnStartStmtExpr();
9518 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
9519 if (SubStmt.isInvalid()) {
9520 SemaRef.ActOnStmtExprError();
9524 if (!getDerived().AlwaysRebuild() &&
9525 SubStmt.get() == E->getSubStmt()) {
9526 // Calling this an 'error' is unintuitive, but it does the right thing.
9527 SemaRef.ActOnStmtExprError();
9528 return SemaRef.MaybeBindToTemporary(E);
9531 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
9536 template<typename Derived>
9538 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
9539 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9540 if (Cond.isInvalid())
9543 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9544 if (LHS.isInvalid())
9547 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9548 if (RHS.isInvalid())
9551 if (!getDerived().AlwaysRebuild() &&
9552 Cond.get() == E->getCond() &&
9553 LHS.get() == E->getLHS() &&
9554 RHS.get() == E->getRHS())
9557 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
9558 Cond.get(), LHS.get(), RHS.get(),
9562 template<typename Derived>
9564 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
9568 template<typename Derived>
9570 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9571 switch (E->getOperator()) {
9575 case OO_Array_Delete:
9576 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
9579 // This is a call to an object's operator().
9580 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
9582 // Transform the object itself.
9583 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
9584 if (Object.isInvalid())
9587 // FIXME: Poor location information
9588 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
9589 static_cast<Expr *>(Object.get())->getLocEnd());
9591 // Transform the call arguments.
9592 SmallVector<Expr*, 8> Args;
9593 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
9597 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
9602 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9604 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
9605 #include "clang/Basic/OperatorKinds.def"
9610 case OO_Conditional:
9611 llvm_unreachable("conditional operator is not actually overloadable");
9614 case NUM_OVERLOADED_OPERATORS:
9615 llvm_unreachable("not an overloaded operator?");
9618 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9619 if (Callee.isInvalid())
9623 if (E->getOperator() == OO_Amp)
9624 First = getDerived().TransformAddressOfOperand(E->getArg(0));
9626 First = getDerived().TransformExpr(E->getArg(0));
9627 if (First.isInvalid())
9631 if (E->getNumArgs() == 2) {
9632 Second = getDerived().TransformExpr(E->getArg(1));
9633 if (Second.isInvalid())
9637 if (!getDerived().AlwaysRebuild() &&
9638 Callee.get() == E->getCallee() &&
9639 First.get() == E->getArg(0) &&
9640 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
9641 return SemaRef.MaybeBindToTemporary(E);
9643 Sema::FPContractStateRAII FPContractState(getSema());
9644 getSema().FPFeatures = E->getFPFeatures();
9646 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
9647 E->getOperatorLoc(),
9653 template<typename Derived>
9655 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
9656 return getDerived().TransformCallExpr(E);
9659 template<typename Derived>
9661 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
9662 // Transform the callee.
9663 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9664 if (Callee.isInvalid())
9667 // Transform exec config.
9668 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
9672 // Transform arguments.
9673 bool ArgChanged = false;
9674 SmallVector<Expr*, 8> Args;
9675 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9679 if (!getDerived().AlwaysRebuild() &&
9680 Callee.get() == E->getCallee() &&
9682 return SemaRef.MaybeBindToTemporary(E);
9684 // FIXME: Wrong source location information for the '('.
9685 SourceLocation FakeLParenLoc
9686 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9687 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9689 E->getRParenLoc(), EC.get());
9692 template<typename Derived>
9694 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
9695 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9700 = getDerived().TransformExpr(E->getSubExprAsWritten());
9701 if (SubExpr.isInvalid())
9704 if (!getDerived().AlwaysRebuild() &&
9705 Type == E->getTypeInfoAsWritten() &&
9706 SubExpr.get() == E->getSubExpr())
9708 return getDerived().RebuildCXXNamedCastExpr(
9709 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
9710 Type, E->getAngleBrackets().getEnd(),
9711 // FIXME. this should be '(' location
9712 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
9715 template<typename Derived>
9717 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
9718 return getDerived().TransformCXXNamedCastExpr(E);
9721 template<typename Derived>
9723 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
9724 return getDerived().TransformCXXNamedCastExpr(E);
9727 template<typename Derived>
9729 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
9730 CXXReinterpretCastExpr *E) {
9731 return getDerived().TransformCXXNamedCastExpr(E);
9734 template<typename Derived>
9736 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
9737 return getDerived().TransformCXXNamedCastExpr(E);
9740 template<typename Derived>
9742 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
9743 CXXFunctionalCastExpr *E) {
9744 TypeSourceInfo *Type =
9745 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
9750 = getDerived().TransformExpr(E->getSubExprAsWritten());
9751 if (SubExpr.isInvalid())
9754 if (!getDerived().AlwaysRebuild() &&
9755 Type == E->getTypeInfoAsWritten() &&
9756 SubExpr.get() == E->getSubExpr())
9759 return getDerived().RebuildCXXFunctionalCastExpr(Type,
9765 template<typename Derived>
9767 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
9768 if (E->isTypeOperand()) {
9769 TypeSourceInfo *TInfo
9770 = getDerived().TransformType(E->getTypeOperandSourceInfo());
9774 if (!getDerived().AlwaysRebuild() &&
9775 TInfo == E->getTypeOperandSourceInfo())
9778 return getDerived().RebuildCXXTypeidExpr(E->getType(),
9784 // We don't know whether the subexpression is potentially evaluated until
9785 // after we perform semantic analysis. We speculatively assume it is
9786 // unevaluated; it will get fixed later if the subexpression is in fact
9787 // potentially evaluated.
9788 EnterExpressionEvaluationContext Unevaluated(
9789 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9790 Sema::ReuseLambdaContextDecl);
9792 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
9793 if (SubExpr.isInvalid())
9796 if (!getDerived().AlwaysRebuild() &&
9797 SubExpr.get() == E->getExprOperand())
9800 return getDerived().RebuildCXXTypeidExpr(E->getType(),
9806 template<typename Derived>
9808 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
9809 if (E->isTypeOperand()) {
9810 TypeSourceInfo *TInfo
9811 = getDerived().TransformType(E->getTypeOperandSourceInfo());
9815 if (!getDerived().AlwaysRebuild() &&
9816 TInfo == E->getTypeOperandSourceInfo())
9819 return getDerived().RebuildCXXUuidofExpr(E->getType(),
9825 EnterExpressionEvaluationContext Unevaluated(
9826 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
9828 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
9829 if (SubExpr.isInvalid())
9832 if (!getDerived().AlwaysRebuild() &&
9833 SubExpr.get() == E->getExprOperand())
9836 return getDerived().RebuildCXXUuidofExpr(E->getType(),
9842 template<typename Derived>
9844 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
9848 template<typename Derived>
9850 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
9851 CXXNullPtrLiteralExpr *E) {
9855 template<typename Derived>
9857 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
9858 QualType T = getSema().getCurrentThisType();
9860 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
9861 // Make sure that we capture 'this'.
9862 getSema().CheckCXXThisCapture(E->getLocStart());
9866 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
9869 template<typename Derived>
9871 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
9872 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9873 if (SubExpr.isInvalid())
9876 if (!getDerived().AlwaysRebuild() &&
9877 SubExpr.get() == E->getSubExpr())
9880 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
9881 E->isThrownVariableInScope());
9884 template<typename Derived>
9886 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9888 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
9893 if (!getDerived().AlwaysRebuild() &&
9894 Param == E->getParam())
9897 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
9900 template<typename Derived>
9902 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
9904 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
9909 if (!getDerived().AlwaysRebuild() && Field == E->getField())
9912 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
9915 template<typename Derived>
9917 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
9918 CXXScalarValueInitExpr *E) {
9919 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9923 if (!getDerived().AlwaysRebuild() &&
9924 T == E->getTypeSourceInfo())
9927 return getDerived().RebuildCXXScalarValueInitExpr(T,
9928 /*FIXME:*/T->getTypeLoc().getEndLoc(),
9932 template<typename Derived>
9934 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
9935 // Transform the type that we're allocating
9936 TypeSourceInfo *AllocTypeInfo =
9937 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
9941 // Transform the size of the array we're allocating (if any).
9942 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
9943 if (ArraySize.isInvalid())
9946 // Transform the placement arguments (if any).
9947 bool ArgumentChanged = false;
9948 SmallVector<Expr*, 8> PlacementArgs;
9949 if (getDerived().TransformExprs(E->getPlacementArgs(),
9950 E->getNumPlacementArgs(), true,
9951 PlacementArgs, &ArgumentChanged))
9954 // Transform the initializer (if any).
9955 Expr *OldInit = E->getInitializer();
9958 NewInit = getDerived().TransformInitializer(OldInit, true);
9959 if (NewInit.isInvalid())
9962 // Transform new operator and delete operator.
9963 FunctionDecl *OperatorNew = nullptr;
9964 if (E->getOperatorNew()) {
9965 OperatorNew = cast_or_null<FunctionDecl>(
9966 getDerived().TransformDecl(E->getLocStart(),
9967 E->getOperatorNew()));
9972 FunctionDecl *OperatorDelete = nullptr;
9973 if (E->getOperatorDelete()) {
9974 OperatorDelete = cast_or_null<FunctionDecl>(
9975 getDerived().TransformDecl(E->getLocStart(),
9976 E->getOperatorDelete()));
9977 if (!OperatorDelete)
9981 if (!getDerived().AlwaysRebuild() &&
9982 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
9983 ArraySize.get() == E->getArraySize() &&
9984 NewInit.get() == OldInit &&
9985 OperatorNew == E->getOperatorNew() &&
9986 OperatorDelete == E->getOperatorDelete() &&
9988 // Mark any declarations we need as referenced.
9989 // FIXME: instantiation-specific.
9991 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
9993 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
9995 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
9996 QualType ElementType
9997 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
9998 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
9999 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10000 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10001 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
10009 QualType AllocType = AllocTypeInfo->getType();
10010 if (!ArraySize.get()) {
10011 // If no array size was specified, but the new expression was
10012 // instantiated with an array type (e.g., "new T" where T is
10013 // instantiated with "int[4]"), extract the outer bound from the
10014 // array type as our array size. We do this with constant and
10015 // dependently-sized array types.
10016 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10019 } else if (const ConstantArrayType *ConsArrayT
10020 = dyn_cast<ConstantArrayType>(ArrayT)) {
10021 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10022 SemaRef.Context.getSizeType(),
10023 /*FIXME:*/ E->getLocStart());
10024 AllocType = ConsArrayT->getElementType();
10025 } else if (const DependentSizedArrayType *DepArrayT
10026 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10027 if (DepArrayT->getSizeExpr()) {
10028 ArraySize = DepArrayT->getSizeExpr();
10029 AllocType = DepArrayT->getElementType();
10034 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
10036 /*FIXME:*/E->getLocStart(),
10038 /*FIXME:*/E->getLocStart(),
10039 E->getTypeIdParens(),
10043 E->getDirectInitRange(),
10047 template<typename Derived>
10049 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10050 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10051 if (Operand.isInvalid())
10052 return ExprError();
10054 // Transform the delete operator, if known.
10055 FunctionDecl *OperatorDelete = nullptr;
10056 if (E->getOperatorDelete()) {
10057 OperatorDelete = cast_or_null<FunctionDecl>(
10058 getDerived().TransformDecl(E->getLocStart(),
10059 E->getOperatorDelete()));
10060 if (!OperatorDelete)
10061 return ExprError();
10064 if (!getDerived().AlwaysRebuild() &&
10065 Operand.get() == E->getArgument() &&
10066 OperatorDelete == E->getOperatorDelete()) {
10067 // Mark any declarations we need as referenced.
10068 // FIXME: instantiation-specific.
10069 if (OperatorDelete)
10070 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
10072 if (!E->getArgument()->isTypeDependent()) {
10073 QualType Destroyed = SemaRef.Context.getBaseElementType(
10074 E->getDestroyedType());
10075 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10076 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10077 SemaRef.MarkFunctionReferenced(E->getLocStart(),
10078 SemaRef.LookupDestructor(Record));
10085 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
10086 E->isGlobalDelete(),
10091 template<typename Derived>
10093 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10094 CXXPseudoDestructorExpr *E) {
10095 ExprResult Base = getDerived().TransformExpr(E->getBase());
10096 if (Base.isInvalid())
10097 return ExprError();
10099 ParsedType ObjectTypePtr;
10100 bool MayBePseudoDestructor = false;
10101 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10102 E->getOperatorLoc(),
10103 E->isArrow()? tok::arrow : tok::period,
10105 MayBePseudoDestructor);
10106 if (Base.isInvalid())
10107 return ExprError();
10109 QualType ObjectType = ObjectTypePtr.get();
10110 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10111 if (QualifierLoc) {
10113 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10115 return ExprError();
10118 SS.Adopt(QualifierLoc);
10120 PseudoDestructorTypeStorage Destroyed;
10121 if (E->getDestroyedTypeInfo()) {
10122 TypeSourceInfo *DestroyedTypeInfo
10123 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10124 ObjectType, nullptr, SS);
10125 if (!DestroyedTypeInfo)
10126 return ExprError();
10127 Destroyed = DestroyedTypeInfo;
10128 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10129 // We aren't likely to be able to resolve the identifier down to a type
10130 // now anyway, so just retain the identifier.
10131 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10132 E->getDestroyedTypeLoc());
10134 // Look for a destructor known with the given name.
10135 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10136 *E->getDestroyedTypeIdentifier(),
10137 E->getDestroyedTypeLoc(),
10142 return ExprError();
10145 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10146 E->getDestroyedTypeLoc());
10149 TypeSourceInfo *ScopeTypeInfo = nullptr;
10150 if (E->getScopeTypeInfo()) {
10151 CXXScopeSpec EmptySS;
10152 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10153 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10154 if (!ScopeTypeInfo)
10155 return ExprError();
10158 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10159 E->getOperatorLoc(),
10163 E->getColonColonLoc(),
10168 template <typename Derived>
10169 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10172 // Transform all the decls.
10173 bool AllEmptyPacks = true;
10174 for (auto *OldD : Old->decls()) {
10175 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10177 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10178 // This can happen because of dependent hiding.
10179 if (isa<UsingShadowDecl>(OldD))
10187 // Expand using pack declarations.
10188 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10189 ArrayRef<NamedDecl*> Decls = SingleDecl;
10190 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10191 Decls = UPD->expansions();
10193 // Expand using declarations.
10194 for (auto *D : Decls) {
10195 if (auto *UD = dyn_cast<UsingDecl>(D)) {
10196 for (auto *SD : UD->shadows())
10203 AllEmptyPacks &= Decls.empty();
10206 // C++ [temp.res]/8.4.2:
10207 // The program is ill-formed, no diagnostic required, if [...] lookup for
10208 // a name in the template definition found a using-declaration, but the
10209 // lookup in the corresponding scope in the instantiation odoes not find
10210 // any declarations because the using-declaration was a pack expansion and
10211 // the corresponding pack is empty
10212 if (AllEmptyPacks && !RequiresADL) {
10213 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10214 << isa<UnresolvedMemberExpr>(Old) << Old->getNameInfo().getName();
10218 // Resolve a kind, but don't do any further analysis. If it's
10219 // ambiguous, the callee needs to deal with it.
10224 template<typename Derived>
10226 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10227 UnresolvedLookupExpr *Old) {
10228 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10229 Sema::LookupOrdinaryName);
10231 // Transform the declaration set.
10232 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10233 return ExprError();
10235 // Rebuild the nested-name qualifier, if present.
10237 if (Old->getQualifierLoc()) {
10238 NestedNameSpecifierLoc QualifierLoc
10239 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10241 return ExprError();
10243 SS.Adopt(QualifierLoc);
10246 if (Old->getNamingClass()) {
10247 CXXRecordDecl *NamingClass
10248 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10250 Old->getNamingClass()));
10251 if (!NamingClass) {
10253 return ExprError();
10256 R.setNamingClass(NamingClass);
10259 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10261 // If we have neither explicit template arguments, nor the template keyword,
10262 // it's a normal declaration name or member reference.
10263 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10264 NamedDecl *D = R.getAsSingle<NamedDecl>();
10265 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10266 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10267 // give a good diagnostic.
10268 if (D && D->isCXXInstanceMember()) {
10269 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10270 /*TemplateArgs=*/nullptr,
10271 /*Scope=*/nullptr);
10274 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10277 // If we have template arguments, rebuild them, then rebuild the
10278 // templateid expression.
10279 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10280 if (Old->hasExplicitTemplateArgs() &&
10281 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10282 Old->getNumTemplateArgs(),
10285 return ExprError();
10288 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10289 Old->requiresADL(), &TransArgs);
10292 template<typename Derived>
10294 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10295 bool ArgChanged = false;
10296 SmallVector<TypeSourceInfo *, 4> Args;
10297 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10298 TypeSourceInfo *From = E->getArg(I);
10299 TypeLoc FromTL = From->getTypeLoc();
10300 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10301 TypeLocBuilder TLB;
10302 TLB.reserve(FromTL.getFullDataSize());
10303 QualType To = getDerived().TransformType(TLB, FromTL);
10305 return ExprError();
10307 if (To == From->getType())
10308 Args.push_back(From);
10310 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10318 // We have a pack expansion. Instantiate it.
10319 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10320 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10321 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10322 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
10324 // Determine whether the set of unexpanded parameter packs can and should
10326 bool Expand = true;
10327 bool RetainExpansion = false;
10328 Optional<unsigned> OrigNumExpansions =
10329 ExpansionTL.getTypePtr()->getNumExpansions();
10330 Optional<unsigned> NumExpansions = OrigNumExpansions;
10331 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
10332 PatternTL.getSourceRange(),
10334 Expand, RetainExpansion,
10336 return ExprError();
10339 // The transform has determined that we should perform a simple
10340 // transformation on the pack expansion, producing another pack
10342 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10344 TypeLocBuilder TLB;
10345 TLB.reserve(From->getTypeLoc().getFullDataSize());
10347 QualType To = getDerived().TransformType(TLB, PatternTL);
10349 return ExprError();
10351 To = getDerived().RebuildPackExpansionType(To,
10352 PatternTL.getSourceRange(),
10353 ExpansionTL.getEllipsisLoc(),
10356 return ExprError();
10358 PackExpansionTypeLoc ToExpansionTL
10359 = TLB.push<PackExpansionTypeLoc>(To);
10360 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10361 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10365 // Expand the pack expansion by substituting for each argument in the
10367 for (unsigned I = 0; I != *NumExpansions; ++I) {
10368 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
10369 TypeLocBuilder TLB;
10370 TLB.reserve(PatternTL.getFullDataSize());
10371 QualType To = getDerived().TransformType(TLB, PatternTL);
10373 return ExprError();
10375 if (To->containsUnexpandedParameterPack()) {
10376 To = getDerived().RebuildPackExpansionType(To,
10377 PatternTL.getSourceRange(),
10378 ExpansionTL.getEllipsisLoc(),
10381 return ExprError();
10383 PackExpansionTypeLoc ToExpansionTL
10384 = TLB.push<PackExpansionTypeLoc>(To);
10385 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10388 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10391 if (!RetainExpansion)
10394 // If we're supposed to retain a pack expansion, do so by temporarily
10395 // forgetting the partially-substituted parameter pack.
10396 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10398 TypeLocBuilder TLB;
10399 TLB.reserve(From->getTypeLoc().getFullDataSize());
10401 QualType To = getDerived().TransformType(TLB, PatternTL);
10403 return ExprError();
10405 To = getDerived().RebuildPackExpansionType(To,
10406 PatternTL.getSourceRange(),
10407 ExpansionTL.getEllipsisLoc(),
10410 return ExprError();
10412 PackExpansionTypeLoc ToExpansionTL
10413 = TLB.push<PackExpansionTypeLoc>(To);
10414 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10415 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10418 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10421 return getDerived().RebuildTypeTrait(E->getTrait(),
10427 template<typename Derived>
10429 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
10430 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
10432 return ExprError();
10434 if (!getDerived().AlwaysRebuild() &&
10435 T == E->getQueriedTypeSourceInfo())
10438 ExprResult SubExpr;
10440 EnterExpressionEvaluationContext Unevaluated(
10441 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10442 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
10443 if (SubExpr.isInvalid())
10444 return ExprError();
10446 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
10450 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
10457 template<typename Derived>
10459 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
10460 ExprResult SubExpr;
10462 EnterExpressionEvaluationContext Unevaluated(
10463 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10464 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
10465 if (SubExpr.isInvalid())
10466 return ExprError();
10468 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
10472 return getDerived().RebuildExpressionTrait(
10473 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
10476 template <typename Derived>
10477 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
10478 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
10479 TypeSourceInfo **RecoveryTSI) {
10480 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
10481 DRE, AddrTaken, RecoveryTSI);
10483 // Propagate both errors and recovered types, which return ExprEmpty.
10484 if (!NewDRE.isUsable())
10487 // We got an expr, wrap it up in parens.
10488 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
10490 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
10494 template <typename Derived>
10495 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10496 DependentScopeDeclRefExpr *E) {
10497 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
10501 template<typename Derived>
10503 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10504 DependentScopeDeclRefExpr *E,
10505 bool IsAddressOfOperand,
10506 TypeSourceInfo **RecoveryTSI) {
10507 assert(E->getQualifierLoc());
10508 NestedNameSpecifierLoc QualifierLoc
10509 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10511 return ExprError();
10512 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10514 // TODO: If this is a conversion-function-id, verify that the
10515 // destination type name (if present) resolves the same way after
10516 // instantiation as it did in the local scope.
10518 DeclarationNameInfo NameInfo
10519 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
10520 if (!NameInfo.getName())
10521 return ExprError();
10523 if (!E->hasExplicitTemplateArgs()) {
10524 if (!getDerived().AlwaysRebuild() &&
10525 QualifierLoc == E->getQualifierLoc() &&
10526 // Note: it is sufficient to compare the Name component of NameInfo:
10527 // if name has not changed, DNLoc has not changed either.
10528 NameInfo.getName() == E->getDeclName())
10531 return getDerived().RebuildDependentScopeDeclRefExpr(
10532 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
10533 IsAddressOfOperand, RecoveryTSI);
10536 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
10537 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10538 E->getNumTemplateArgs(),
10540 return ExprError();
10542 return getDerived().RebuildDependentScopeDeclRefExpr(
10543 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
10547 template<typename Derived>
10549 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
10550 // CXXConstructExprs other than for list-initialization and
10551 // CXXTemporaryObjectExpr are always implicit, so when we have
10552 // a 1-argument construction we just transform that argument.
10553 if ((E->getNumArgs() == 1 ||
10554 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
10555 (!getDerived().DropCallArgument(E->getArg(0))) &&
10556 !E->isListInitialization())
10557 return getDerived().TransformExpr(E->getArg(0));
10559 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
10561 QualType T = getDerived().TransformType(E->getType());
10563 return ExprError();
10565 CXXConstructorDecl *Constructor
10566 = cast_or_null<CXXConstructorDecl>(
10567 getDerived().TransformDecl(E->getLocStart(),
10568 E->getConstructor()));
10570 return ExprError();
10572 bool ArgumentChanged = false;
10573 SmallVector<Expr*, 8> Args;
10574 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10576 return ExprError();
10578 if (!getDerived().AlwaysRebuild() &&
10579 T == E->getType() &&
10580 Constructor == E->getConstructor() &&
10581 !ArgumentChanged) {
10582 // Mark the constructor as referenced.
10583 // FIXME: Instantiation-specific
10584 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10588 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
10590 E->isElidable(), Args,
10591 E->hadMultipleCandidates(),
10592 E->isListInitialization(),
10593 E->isStdInitListInitialization(),
10594 E->requiresZeroInitialization(),
10595 E->getConstructionKind(),
10596 E->getParenOrBraceRange());
10599 template<typename Derived>
10600 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
10601 CXXInheritedCtorInitExpr *E) {
10602 QualType T = getDerived().TransformType(E->getType());
10604 return ExprError();
10606 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
10607 getDerived().TransformDecl(E->getLocStart(), E->getConstructor()));
10609 return ExprError();
10611 if (!getDerived().AlwaysRebuild() &&
10612 T == E->getType() &&
10613 Constructor == E->getConstructor()) {
10614 // Mark the constructor as referenced.
10615 // FIXME: Instantiation-specific
10616 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10620 return getDerived().RebuildCXXInheritedCtorInitExpr(
10621 T, E->getLocation(), Constructor,
10622 E->constructsVBase(), E->inheritedFromVBase());
10625 /// \brief Transform a C++ temporary-binding expression.
10627 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
10628 /// transform the subexpression and return that.
10629 template<typename Derived>
10631 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10632 return getDerived().TransformExpr(E->getSubExpr());
10635 /// \brief Transform a C++ expression that contains cleanups that should
10636 /// be run after the expression is evaluated.
10638 /// Since ExprWithCleanups nodes are implicitly generated, we
10639 /// just transform the subexpression and return that.
10640 template<typename Derived>
10642 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
10643 return getDerived().TransformExpr(E->getSubExpr());
10646 template<typename Derived>
10648 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
10649 CXXTemporaryObjectExpr *E) {
10650 TypeSourceInfo *T =
10651 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
10653 return ExprError();
10655 CXXConstructorDecl *Constructor
10656 = cast_or_null<CXXConstructorDecl>(
10657 getDerived().TransformDecl(E->getLocStart(),
10658 E->getConstructor()));
10660 return ExprError();
10662 bool ArgumentChanged = false;
10663 SmallVector<Expr*, 8> Args;
10664 Args.reserve(E->getNumArgs());
10665 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10667 return ExprError();
10669 if (!getDerived().AlwaysRebuild() &&
10670 T == E->getTypeSourceInfo() &&
10671 Constructor == E->getConstructor() &&
10672 !ArgumentChanged) {
10673 // FIXME: Instantiation-specific
10674 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10675 return SemaRef.MaybeBindToTemporary(E);
10678 // FIXME: Pass in E->isListInitialization().
10679 return getDerived().RebuildCXXTemporaryObjectExpr(T,
10680 /*FIXME:*/T->getTypeLoc().getEndLoc(),
10685 template<typename Derived>
10687 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
10688 // Transform any init-capture expressions before entering the scope of the
10689 // lambda body, because they are not semantically within that scope.
10690 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
10691 SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
10692 InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
10693 E->explicit_capture_begin());
10694 for (LambdaExpr::capture_iterator C = E->capture_begin(),
10695 CEnd = E->capture_end();
10697 if (!E->isInitCapture(C))
10699 EnterExpressionEvaluationContext EEEC(
10700 getSema(), Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
10701 ExprResult NewExprInitResult = getDerived().TransformInitializer(
10702 C->getCapturedVar()->getInit(),
10703 C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
10705 if (NewExprInitResult.isInvalid())
10706 return ExprError();
10707 Expr *NewExprInit = NewExprInitResult.get();
10709 VarDecl *OldVD = C->getCapturedVar();
10710 QualType NewInitCaptureType =
10711 getSema().buildLambdaInitCaptureInitialization(
10712 C->getLocation(), OldVD->getType()->isReferenceType(),
10713 OldVD->getIdentifier(),
10714 C->getCapturedVar()->getInitStyle() != VarDecl::CInit, NewExprInit);
10715 NewExprInitResult = NewExprInit;
10716 InitCaptureExprsAndTypes[C - E->capture_begin()] =
10717 std::make_pair(NewExprInitResult, NewInitCaptureType);
10720 // Transform the template parameters, and add them to the current
10721 // instantiation scope. The null case is handled correctly.
10722 auto TPL = getDerived().TransformTemplateParameterList(
10723 E->getTemplateParameterList());
10725 // Transform the type of the original lambda's call operator.
10726 // The transformation MUST be done in the CurrentInstantiationScope since
10727 // it introduces a mapping of the original to the newly created
10728 // transformed parameters.
10729 TypeSourceInfo *NewCallOpTSI = nullptr;
10731 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
10732 FunctionProtoTypeLoc OldCallOpFPTL =
10733 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
10735 TypeLocBuilder NewCallOpTLBuilder;
10736 SmallVector<QualType, 4> ExceptionStorage;
10737 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
10738 QualType NewCallOpType = TransformFunctionProtoType(
10739 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
10740 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
10741 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
10742 ExceptionStorage, Changed);
10744 if (NewCallOpType.isNull())
10745 return ExprError();
10746 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
10750 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
10751 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
10752 LSI->GLTemplateParameterList = TPL;
10754 // Create the local class that will describe the lambda.
10755 CXXRecordDecl *Class
10756 = getSema().createLambdaClosureType(E->getIntroducerRange(),
10758 /*KnownDependent=*/false,
10759 E->getCaptureDefault());
10760 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
10762 // Build the call operator.
10763 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
10764 Class, E->getIntroducerRange(), NewCallOpTSI,
10765 E->getCallOperator()->getLocEnd(),
10766 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
10767 E->getCallOperator()->isConstexpr());
10769 LSI->CallOperator = NewCallOperator;
10771 for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
10772 I != NumParams; ++I) {
10773 auto *P = NewCallOperator->getParamDecl(I);
10774 if (P->hasUninstantiatedDefaultArg()) {
10775 EnterExpressionEvaluationContext Eval(
10777 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
10778 ExprResult R = getDerived().TransformExpr(
10779 E->getCallOperator()->getParamDecl(I)->getDefaultArg());
10780 P->setDefaultArg(R.get());
10784 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
10785 getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
10787 // Introduce the context of the call operator.
10788 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
10789 /*NewThisContext*/false);
10791 // Enter the scope of the lambda.
10792 getSema().buildLambdaScope(LSI, NewCallOperator,
10793 E->getIntroducerRange(),
10794 E->getCaptureDefault(),
10795 E->getCaptureDefaultLoc(),
10796 E->hasExplicitParameters(),
10797 E->hasExplicitResultType(),
10800 bool Invalid = false;
10802 // Transform captures.
10803 bool FinishedExplicitCaptures = false;
10804 for (LambdaExpr::capture_iterator C = E->capture_begin(),
10805 CEnd = E->capture_end();
10807 // When we hit the first implicit capture, tell Sema that we've finished
10808 // the list of explicit captures.
10809 if (!FinishedExplicitCaptures && C->isImplicit()) {
10810 getSema().finishLambdaExplicitCaptures(LSI);
10811 FinishedExplicitCaptures = true;
10814 // Capturing 'this' is trivial.
10815 if (C->capturesThis()) {
10816 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
10817 /*BuildAndDiagnose*/ true, nullptr,
10818 C->getCaptureKind() == LCK_StarThis);
10821 // Captured expression will be recaptured during captured variables
10823 if (C->capturesVLAType())
10826 // Rebuild init-captures, including the implied field declaration.
10827 if (E->isInitCapture(C)) {
10828 InitCaptureInfoTy InitExprTypePair =
10829 InitCaptureExprsAndTypes[C - E->capture_begin()];
10830 ExprResult Init = InitExprTypePair.first;
10831 QualType InitQualType = InitExprTypePair.second;
10832 if (Init.isInvalid() || InitQualType.isNull()) {
10836 VarDecl *OldVD = C->getCapturedVar();
10837 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
10838 OldVD->getLocation(), InitExprTypePair.second, OldVD->getIdentifier(),
10839 OldVD->getInitStyle(), Init.get());
10843 getDerived().transformedLocalDecl(OldVD, NewVD);
10845 getSema().buildInitCaptureField(LSI, NewVD);
10849 assert(C->capturesVariable() && "unexpected kind of lambda capture");
10851 // Determine the capture kind for Sema.
10852 Sema::TryCaptureKind Kind
10853 = C->isImplicit()? Sema::TryCapture_Implicit
10854 : C->getCaptureKind() == LCK_ByCopy
10855 ? Sema::TryCapture_ExplicitByVal
10856 : Sema::TryCapture_ExplicitByRef;
10857 SourceLocation EllipsisLoc;
10858 if (C->isPackExpansion()) {
10859 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
10860 bool ShouldExpand = false;
10861 bool RetainExpansion = false;
10862 Optional<unsigned> NumExpansions;
10863 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
10866 ShouldExpand, RetainExpansion,
10872 if (ShouldExpand) {
10873 // The transform has determined that we should perform an expansion;
10874 // transform and capture each of the arguments.
10875 // expansion of the pattern. Do so.
10876 VarDecl *Pack = C->getCapturedVar();
10877 for (unsigned I = 0; I != *NumExpansions; ++I) {
10878 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
10879 VarDecl *CapturedVar
10880 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
10882 if (!CapturedVar) {
10887 // Capture the transformed variable.
10888 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
10891 // FIXME: Retain a pack expansion if RetainExpansion is true.
10896 EllipsisLoc = C->getEllipsisLoc();
10899 // Transform the captured variable.
10900 VarDecl *CapturedVar
10901 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
10902 C->getCapturedVar()));
10903 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
10908 // Capture the transformed variable.
10909 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
10912 if (!FinishedExplicitCaptures)
10913 getSema().finishLambdaExplicitCaptures(LSI);
10915 // Enter a new evaluation context to insulate the lambda from any
10916 // cleanups from the enclosing full-expression.
10917 getSema().PushExpressionEvaluationContext(
10918 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
10920 // Instantiate the body of the lambda expression.
10922 Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
10924 // ActOnLambda* will pop the function scope for us.
10925 FuncScopeCleanup.disable();
10927 if (Body.isInvalid()) {
10928 SavedContext.pop();
10929 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
10930 /*IsInstantiation=*/true);
10931 return ExprError();
10934 // Copy the LSI before ActOnFinishFunctionBody removes it.
10935 // FIXME: This is dumb. Store the lambda information somewhere that outlives
10936 // the call operator.
10937 auto LSICopy = *LSI;
10938 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
10939 /*IsInstantiation*/ true);
10940 SavedContext.pop();
10942 return getSema().BuildLambdaExpr(E->getLocStart(), Body.get()->getLocEnd(),
10946 template<typename Derived>
10948 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
10949 CXXUnresolvedConstructExpr *E) {
10950 TypeSourceInfo *T =
10951 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
10953 return ExprError();
10955 bool ArgumentChanged = false;
10956 SmallVector<Expr*, 8> Args;
10957 Args.reserve(E->arg_size());
10958 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
10960 return ExprError();
10962 if (!getDerived().AlwaysRebuild() &&
10963 T == E->getTypeSourceInfo() &&
10967 // FIXME: we're faking the locations of the commas
10968 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
10971 E->getRParenLoc());
10974 template<typename Derived>
10976 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
10977 CXXDependentScopeMemberExpr *E) {
10978 // Transform the base of the expression.
10979 ExprResult Base((Expr*) nullptr);
10982 QualType ObjectType;
10983 if (!E->isImplicitAccess()) {
10984 OldBase = E->getBase();
10985 Base = getDerived().TransformExpr(OldBase);
10986 if (Base.isInvalid())
10987 return ExprError();
10989 // Start the member reference and compute the object's type.
10990 ParsedType ObjectTy;
10991 bool MayBePseudoDestructor = false;
10992 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10993 E->getOperatorLoc(),
10994 E->isArrow()? tok::arrow : tok::period,
10996 MayBePseudoDestructor);
10997 if (Base.isInvalid())
10998 return ExprError();
11000 ObjectType = ObjectTy.get();
11001 BaseType = ((Expr*) Base.get())->getType();
11004 BaseType = getDerived().TransformType(E->getBaseType());
11005 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
11008 // Transform the first part of the nested-name-specifier that qualifies
11009 // the member name.
11010 NamedDecl *FirstQualifierInScope
11011 = getDerived().TransformFirstQualifierInScope(
11012 E->getFirstQualifierFoundInScope(),
11013 E->getQualifierLoc().getBeginLoc());
11015 NestedNameSpecifierLoc QualifierLoc;
11016 if (E->getQualifier()) {
11018 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11020 FirstQualifierInScope);
11022 return ExprError();
11025 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11027 // TODO: If this is a conversion-function-id, verify that the
11028 // destination type name (if present) resolves the same way after
11029 // instantiation as it did in the local scope.
11031 DeclarationNameInfo NameInfo
11032 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11033 if (!NameInfo.getName())
11034 return ExprError();
11036 if (!E->hasExplicitTemplateArgs()) {
11037 // This is a reference to a member without an explicitly-specified
11038 // template argument list. Optimize for this common case.
11039 if (!getDerived().AlwaysRebuild() &&
11040 Base.get() == OldBase &&
11041 BaseType == E->getBaseType() &&
11042 QualifierLoc == E->getQualifierLoc() &&
11043 NameInfo.getName() == E->getMember() &&
11044 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11047 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11050 E->getOperatorLoc(),
11053 FirstQualifierInScope,
11055 /*TemplateArgs*/nullptr);
11058 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11059 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11060 E->getNumTemplateArgs(),
11062 return ExprError();
11064 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11067 E->getOperatorLoc(),
11070 FirstQualifierInScope,
11075 template<typename Derived>
11077 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11078 // Transform the base of the expression.
11079 ExprResult Base((Expr*) nullptr);
11081 if (!Old->isImplicitAccess()) {
11082 Base = getDerived().TransformExpr(Old->getBase());
11083 if (Base.isInvalid())
11084 return ExprError();
11085 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11087 if (Base.isInvalid())
11088 return ExprError();
11089 BaseType = Base.get()->getType();
11091 BaseType = getDerived().TransformType(Old->getBaseType());
11094 NestedNameSpecifierLoc QualifierLoc;
11095 if (Old->getQualifierLoc()) {
11097 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11099 return ExprError();
11102 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11104 LookupResult R(SemaRef, Old->getMemberNameInfo(),
11105 Sema::LookupOrdinaryName);
11107 // Transform the declaration set.
11108 if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11109 return ExprError();
11111 // Determine the naming class.
11112 if (Old->getNamingClass()) {
11113 CXXRecordDecl *NamingClass
11114 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11115 Old->getMemberLoc(),
11116 Old->getNamingClass()));
11118 return ExprError();
11120 R.setNamingClass(NamingClass);
11123 TemplateArgumentListInfo TransArgs;
11124 if (Old->hasExplicitTemplateArgs()) {
11125 TransArgs.setLAngleLoc(Old->getLAngleLoc());
11126 TransArgs.setRAngleLoc(Old->getRAngleLoc());
11127 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11128 Old->getNumTemplateArgs(),
11130 return ExprError();
11133 // FIXME: to do this check properly, we will need to preserve the
11134 // first-qualifier-in-scope here, just in case we had a dependent
11135 // base (and therefore couldn't do the check) and a
11136 // nested-name-qualifier (and therefore could do the lookup).
11137 NamedDecl *FirstQualifierInScope = nullptr;
11139 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11141 Old->getOperatorLoc(),
11145 FirstQualifierInScope,
11147 (Old->hasExplicitTemplateArgs()
11148 ? &TransArgs : nullptr));
11151 template<typename Derived>
11153 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11154 EnterExpressionEvaluationContext Unevaluated(
11155 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11156 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11157 if (SubExpr.isInvalid())
11158 return ExprError();
11160 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11163 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11166 template<typename Derived>
11168 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11169 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11170 if (Pattern.isInvalid())
11171 return ExprError();
11173 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11176 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11177 E->getNumExpansions());
11180 template<typename Derived>
11182 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11183 // If E is not value-dependent, then nothing will change when we transform it.
11184 // Note: This is an instantiation-centric view.
11185 if (!E->isValueDependent())
11188 EnterExpressionEvaluationContext Unevaluated(
11189 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11191 ArrayRef<TemplateArgument> PackArgs;
11192 TemplateArgument ArgStorage;
11194 // Find the argument list to transform.
11195 if (E->isPartiallySubstituted()) {
11196 PackArgs = E->getPartialArguments();
11197 } else if (E->isValueDependent()) {
11198 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
11199 bool ShouldExpand = false;
11200 bool RetainExpansion = false;
11201 Optional<unsigned> NumExpansions;
11202 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
11204 ShouldExpand, RetainExpansion,
11206 return ExprError();
11208 // If we need to expand the pack, build a template argument from it and
11210 if (ShouldExpand) {
11211 auto *Pack = E->getPack();
11212 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
11213 ArgStorage = getSema().Context.getPackExpansionType(
11214 getSema().Context.getTypeDeclType(TTPD), None);
11215 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
11216 ArgStorage = TemplateArgument(TemplateName(TTPD), None);
11218 auto *VD = cast<ValueDecl>(Pack);
11219 ExprResult DRE = getSema().BuildDeclRefExpr(VD, VD->getType(),
11220 VK_RValue, E->getPackLoc());
11221 if (DRE.isInvalid())
11222 return ExprError();
11223 ArgStorage = new (getSema().Context) PackExpansionExpr(
11224 getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
11226 PackArgs = ArgStorage;
11230 // If we're not expanding the pack, just transform the decl.
11231 if (!PackArgs.size()) {
11232 auto *Pack = cast_or_null<NamedDecl>(
11233 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
11235 return ExprError();
11236 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
11238 E->getRParenLoc(), None, None);
11241 // Try to compute the result without performing a partial substitution.
11242 Optional<unsigned> Result = 0;
11243 for (const TemplateArgument &Arg : PackArgs) {
11244 if (!Arg.isPackExpansion()) {
11245 Result = *Result + 1;
11249 TemplateArgumentLoc ArgLoc;
11250 InventTemplateArgumentLoc(Arg, ArgLoc);
11252 // Find the pattern of the pack expansion.
11253 SourceLocation Ellipsis;
11254 Optional<unsigned> OrigNumExpansions;
11255 TemplateArgumentLoc Pattern =
11256 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
11257 OrigNumExpansions);
11259 // Substitute under the pack expansion. Do not expand the pack (yet).
11260 TemplateArgumentLoc OutPattern;
11261 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11262 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
11266 // See if we can determine the number of arguments from the result.
11267 Optional<unsigned> NumExpansions =
11268 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
11269 if (!NumExpansions) {
11270 // No: we must be in an alias template expansion, and we're going to need
11271 // to actually expand the packs.
11276 Result = *Result + *NumExpansions;
11279 // Common case: we could determine the number of expansions without
11282 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11284 E->getRParenLoc(), *Result, None);
11286 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
11289 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
11290 typedef TemplateArgumentLocInventIterator<
11291 Derived, const TemplateArgument*> PackLocIterator;
11292 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
11293 PackLocIterator(*this, PackArgs.end()),
11294 TransformedPackArgs, /*Uneval*/true))
11295 return ExprError();
11298 // Check whether we managed to fully-expand the pack.
11299 // FIXME: Is it possible for us to do so and not hit the early exit path?
11300 SmallVector<TemplateArgument, 8> Args;
11301 bool PartialSubstitution = false;
11302 for (auto &Loc : TransformedPackArgs.arguments()) {
11303 Args.push_back(Loc.getArgument());
11304 if (Loc.getArgument().isPackExpansion())
11305 PartialSubstitution = true;
11308 if (PartialSubstitution)
11309 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11311 E->getRParenLoc(), None, Args);
11313 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11314 E->getPackLoc(), E->getRParenLoc(),
11315 Args.size(), None);
11318 template<typename Derived>
11320 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
11321 SubstNonTypeTemplateParmPackExpr *E) {
11322 // Default behavior is to do nothing with this transformation.
11326 template<typename Derived>
11328 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
11329 SubstNonTypeTemplateParmExpr *E) {
11330 // Default behavior is to do nothing with this transformation.
11334 template<typename Derived>
11336 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
11337 // Default behavior is to do nothing with this transformation.
11341 template<typename Derived>
11343 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
11344 MaterializeTemporaryExpr *E) {
11345 return getDerived().TransformExpr(E->GetTemporaryExpr());
11348 template<typename Derived>
11350 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
11351 Expr *Pattern = E->getPattern();
11353 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11354 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
11355 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11357 // Determine whether the set of unexpanded parameter packs can and should
11359 bool Expand = true;
11360 bool RetainExpansion = false;
11361 Optional<unsigned> NumExpansions;
11362 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
11363 Pattern->getSourceRange(),
11365 Expand, RetainExpansion,
11370 // Do not expand any packs here, just transform and rebuild a fold
11372 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11375 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
11376 if (LHS.isInvalid())
11380 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
11381 if (RHS.isInvalid())
11384 if (!getDerived().AlwaysRebuild() &&
11385 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
11388 return getDerived().RebuildCXXFoldExpr(
11389 E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
11390 RHS.get(), E->getLocEnd());
11393 // The transform has determined that we should perform an elementwise
11394 // expansion of the pattern. Do so.
11395 ExprResult Result = getDerived().TransformExpr(E->getInit());
11396 if (Result.isInvalid())
11398 bool LeftFold = E->isLeftFold();
11400 // If we're retaining an expansion for a right fold, it is the innermost
11401 // component and takes the init (if any).
11402 if (!LeftFold && RetainExpansion) {
11403 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11405 ExprResult Out = getDerived().TransformExpr(Pattern);
11406 if (Out.isInvalid())
11409 Result = getDerived().RebuildCXXFoldExpr(
11410 E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
11411 Result.get(), E->getLocEnd());
11412 if (Result.isInvalid())
11416 for (unsigned I = 0; I != *NumExpansions; ++I) {
11417 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
11418 getSema(), LeftFold ? I : *NumExpansions - I - 1);
11419 ExprResult Out = getDerived().TransformExpr(Pattern);
11420 if (Out.isInvalid())
11423 if (Out.get()->containsUnexpandedParameterPack()) {
11424 // We still have a pack; retain a pack expansion for this slice.
11425 Result = getDerived().RebuildCXXFoldExpr(
11427 LeftFold ? Result.get() : Out.get(),
11428 E->getOperator(), E->getEllipsisLoc(),
11429 LeftFold ? Out.get() : Result.get(),
11431 } else if (Result.isUsable()) {
11432 // We've got down to a single element; build a binary operator.
11433 Result = getDerived().RebuildBinaryOperator(
11434 E->getEllipsisLoc(), E->getOperator(),
11435 LeftFold ? Result.get() : Out.get(),
11436 LeftFold ? Out.get() : Result.get());
11440 if (Result.isInvalid())
11444 // If we're retaining an expansion for a left fold, it is the outermost
11445 // component and takes the complete expansion so far as its init (if any).
11446 if (LeftFold && RetainExpansion) {
11447 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11449 ExprResult Out = getDerived().TransformExpr(Pattern);
11450 if (Out.isInvalid())
11453 Result = getDerived().RebuildCXXFoldExpr(
11454 E->getLocStart(), Result.get(),
11455 E->getOperator(), E->getEllipsisLoc(),
11456 Out.get(), E->getLocEnd());
11457 if (Result.isInvalid())
11461 // If we had no init and an empty pack, and we're not retaining an expansion,
11462 // then produce a fallback value or error.
11463 if (Result.isUnset())
11464 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
11470 template<typename Derived>
11472 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
11473 CXXStdInitializerListExpr *E) {
11474 return getDerived().TransformExpr(E->getSubExpr());
11477 template<typename Derived>
11479 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
11480 return SemaRef.MaybeBindToTemporary(E);
11483 template<typename Derived>
11485 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
11489 template<typename Derived>
11491 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
11492 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11493 if (SubExpr.isInvalid())
11494 return ExprError();
11496 if (!getDerived().AlwaysRebuild() &&
11497 SubExpr.get() == E->getSubExpr())
11500 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
11503 template<typename Derived>
11505 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
11506 // Transform each of the elements.
11507 SmallVector<Expr *, 8> Elements;
11508 bool ArgChanged = false;
11509 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
11510 /*IsCall=*/false, Elements, &ArgChanged))
11511 return ExprError();
11513 if (!getDerived().AlwaysRebuild() && !ArgChanged)
11514 return SemaRef.MaybeBindToTemporary(E);
11516 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
11521 template<typename Derived>
11523 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
11524 ObjCDictionaryLiteral *E) {
11525 // Transform each of the elements.
11526 SmallVector<ObjCDictionaryElement, 8> Elements;
11527 bool ArgChanged = false;
11528 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
11529 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
11531 if (OrigElement.isPackExpansion()) {
11532 // This key/value element is a pack expansion.
11533 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11534 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
11535 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
11536 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11538 // Determine whether the set of unexpanded parameter packs can
11539 // and should be expanded.
11540 bool Expand = true;
11541 bool RetainExpansion = false;
11542 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
11543 Optional<unsigned> NumExpansions = OrigNumExpansions;
11544 SourceRange PatternRange(OrigElement.Key->getLocStart(),
11545 OrigElement.Value->getLocEnd());
11546 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
11549 Expand, RetainExpansion,
11551 return ExprError();
11554 // The transform has determined that we should perform a simple
11555 // transformation on the pack expansion, producing another pack
11557 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11558 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11559 if (Key.isInvalid())
11560 return ExprError();
11562 if (Key.get() != OrigElement.Key)
11565 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11566 if (Value.isInvalid())
11567 return ExprError();
11569 if (Value.get() != OrigElement.Value)
11572 ObjCDictionaryElement Expansion = {
11573 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
11575 Elements.push_back(Expansion);
11579 // Record right away that the argument was changed. This needs
11580 // to happen even if the array expands to nothing.
11583 // The transform has determined that we should perform an elementwise
11584 // expansion of the pattern. Do so.
11585 for (unsigned I = 0; I != *NumExpansions; ++I) {
11586 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11587 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11588 if (Key.isInvalid())
11589 return ExprError();
11591 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11592 if (Value.isInvalid())
11593 return ExprError();
11595 ObjCDictionaryElement Element = {
11596 Key.get(), Value.get(), SourceLocation(), NumExpansions
11599 // If any unexpanded parameter packs remain, we still have a
11601 // FIXME: Can this really happen?
11602 if (Key.get()->containsUnexpandedParameterPack() ||
11603 Value.get()->containsUnexpandedParameterPack())
11604 Element.EllipsisLoc = OrigElement.EllipsisLoc;
11606 Elements.push_back(Element);
11609 // FIXME: Retain a pack expansion if RetainExpansion is true.
11611 // We've finished with this pack expansion.
11615 // Transform and check key.
11616 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11617 if (Key.isInvalid())
11618 return ExprError();
11620 if (Key.get() != OrigElement.Key)
11623 // Transform and check value.
11625 = getDerived().TransformExpr(OrigElement.Value);
11626 if (Value.isInvalid())
11627 return ExprError();
11629 if (Value.get() != OrigElement.Value)
11632 ObjCDictionaryElement Element = {
11633 Key.get(), Value.get(), SourceLocation(), None
11635 Elements.push_back(Element);
11638 if (!getDerived().AlwaysRebuild() && !ArgChanged)
11639 return SemaRef.MaybeBindToTemporary(E);
11641 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
11645 template<typename Derived>
11647 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
11648 TypeSourceInfo *EncodedTypeInfo
11649 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
11650 if (!EncodedTypeInfo)
11651 return ExprError();
11653 if (!getDerived().AlwaysRebuild() &&
11654 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
11657 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
11659 E->getRParenLoc());
11662 template<typename Derived>
11663 ExprResult TreeTransform<Derived>::
11664 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
11665 // This is a kind of implicit conversion, and it needs to get dropped
11666 // and recomputed for the same general reasons that ImplicitCastExprs
11667 // do, as well a more specific one: this expression is only valid when
11668 // it appears *immediately* as an argument expression.
11669 return getDerived().TransformExpr(E->getSubExpr());
11672 template<typename Derived>
11673 ExprResult TreeTransform<Derived>::
11674 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
11675 TypeSourceInfo *TSInfo
11676 = getDerived().TransformType(E->getTypeInfoAsWritten());
11678 return ExprError();
11680 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
11681 if (Result.isInvalid())
11682 return ExprError();
11684 if (!getDerived().AlwaysRebuild() &&
11685 TSInfo == E->getTypeInfoAsWritten() &&
11686 Result.get() == E->getSubExpr())
11689 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
11690 E->getBridgeKeywordLoc(), TSInfo,
11694 template <typename Derived>
11695 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
11696 ObjCAvailabilityCheckExpr *E) {
11700 template<typename Derived>
11702 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
11703 // Transform arguments.
11704 bool ArgChanged = false;
11705 SmallVector<Expr*, 8> Args;
11706 Args.reserve(E->getNumArgs());
11707 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
11709 return ExprError();
11711 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
11712 // Class message: transform the receiver type.
11713 TypeSourceInfo *ReceiverTypeInfo
11714 = getDerived().TransformType(E->getClassReceiverTypeInfo());
11715 if (!ReceiverTypeInfo)
11716 return ExprError();
11718 // If nothing changed, just retain the existing message send.
11719 if (!getDerived().AlwaysRebuild() &&
11720 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
11721 return SemaRef.MaybeBindToTemporary(E);
11723 // Build a new class message send.
11724 SmallVector<SourceLocation, 16> SelLocs;
11725 E->getSelectorLocs(SelLocs);
11726 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
11729 E->getMethodDecl(),
11734 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
11735 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11736 if (!E->getMethodDecl())
11737 return ExprError();
11739 // Build a new class message send to 'super'.
11740 SmallVector<SourceLocation, 16> SelLocs;
11741 E->getSelectorLocs(SelLocs);
11742 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
11745 E->getReceiverType(),
11746 E->getMethodDecl(),
11752 // Instance message: transform the receiver
11753 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
11754 "Only class and instance messages may be instantiated");
11755 ExprResult Receiver
11756 = getDerived().TransformExpr(E->getInstanceReceiver());
11757 if (Receiver.isInvalid())
11758 return ExprError();
11760 // If nothing changed, just retain the existing message send.
11761 if (!getDerived().AlwaysRebuild() &&
11762 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
11763 return SemaRef.MaybeBindToTemporary(E);
11765 // Build a new instance message send.
11766 SmallVector<SourceLocation, 16> SelLocs;
11767 E->getSelectorLocs(SelLocs);
11768 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
11771 E->getMethodDecl(),
11777 template<typename Derived>
11779 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
11783 template<typename Derived>
11785 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
11789 template<typename Derived>
11791 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
11792 // Transform the base expression.
11793 ExprResult Base = getDerived().TransformExpr(E->getBase());
11794 if (Base.isInvalid())
11795 return ExprError();
11797 // We don't need to transform the ivar; it will never change.
11799 // If nothing changed, just retain the existing expression.
11800 if (!getDerived().AlwaysRebuild() &&
11801 Base.get() == E->getBase())
11804 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
11806 E->isArrow(), E->isFreeIvar());
11809 template<typename Derived>
11811 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
11812 // 'super' and types never change. Property never changes. Just
11813 // retain the existing expression.
11814 if (!E->isObjectReceiver())
11817 // Transform the base expression.
11818 ExprResult Base = getDerived().TransformExpr(E->getBase());
11819 if (Base.isInvalid())
11820 return ExprError();
11822 // We don't need to transform the property; it will never change.
11824 // If nothing changed, just retain the existing expression.
11825 if (!getDerived().AlwaysRebuild() &&
11826 Base.get() == E->getBase())
11829 if (E->isExplicitProperty())
11830 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
11831 E->getExplicitProperty(),
11834 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
11835 SemaRef.Context.PseudoObjectTy,
11836 E->getImplicitPropertyGetter(),
11837 E->getImplicitPropertySetter(),
11841 template<typename Derived>
11843 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
11844 // Transform the base expression.
11845 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
11846 if (Base.isInvalid())
11847 return ExprError();
11849 // Transform the key expression.
11850 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
11851 if (Key.isInvalid())
11852 return ExprError();
11854 // If nothing changed, just retain the existing expression.
11855 if (!getDerived().AlwaysRebuild() &&
11856 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
11859 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
11860 Base.get(), Key.get(),
11861 E->getAtIndexMethodDecl(),
11862 E->setAtIndexMethodDecl());
11865 template<typename Derived>
11867 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
11868 // Transform the base expression.
11869 ExprResult Base = getDerived().TransformExpr(E->getBase());
11870 if (Base.isInvalid())
11871 return ExprError();
11873 // If nothing changed, just retain the existing expression.
11874 if (!getDerived().AlwaysRebuild() &&
11875 Base.get() == E->getBase())
11878 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
11883 template<typename Derived>
11885 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
11886 bool ArgumentChanged = false;
11887 SmallVector<Expr*, 8> SubExprs;
11888 SubExprs.reserve(E->getNumSubExprs());
11889 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
11890 SubExprs, &ArgumentChanged))
11891 return ExprError();
11893 if (!getDerived().AlwaysRebuild() &&
11897 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
11899 E->getRParenLoc());
11902 template<typename Derived>
11904 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
11905 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
11906 if (SrcExpr.isInvalid())
11907 return ExprError();
11909 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
11911 return ExprError();
11913 if (!getDerived().AlwaysRebuild() &&
11914 Type == E->getTypeSourceInfo() &&
11915 SrcExpr.get() == E->getSrcExpr())
11918 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
11919 SrcExpr.get(), Type,
11920 E->getRParenLoc());
11923 template<typename Derived>
11925 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
11926 BlockDecl *oldBlock = E->getBlockDecl();
11928 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
11929 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
11931 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
11932 blockScope->TheDecl->setBlockMissingReturnType(
11933 oldBlock->blockMissingReturnType());
11935 SmallVector<ParmVarDecl*, 4> params;
11936 SmallVector<QualType, 4> paramTypes;
11938 const FunctionProtoType *exprFunctionType = E->getFunctionType();
11940 // Parameter substitution.
11941 Sema::ExtParameterInfoBuilder extParamInfos;
11942 if (getDerived().TransformFunctionTypeParams(
11943 E->getCaretLocation(), oldBlock->parameters(), nullptr,
11944 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, ¶ms,
11946 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
11947 return ExprError();
11950 QualType exprResultType =
11951 getDerived().TransformType(exprFunctionType->getReturnType());
11953 auto epi = exprFunctionType->getExtProtoInfo();
11954 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
11956 QualType functionType =
11957 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
11958 blockScope->FunctionType = functionType;
11960 // Set the parameters on the block decl.
11961 if (!params.empty())
11962 blockScope->TheDecl->setParams(params);
11964 if (!oldBlock->blockMissingReturnType()) {
11965 blockScope->HasImplicitReturnType = false;
11966 blockScope->ReturnType = exprResultType;
11969 // Transform the body
11970 StmtResult body = getDerived().TransformStmt(E->getBody());
11971 if (body.isInvalid()) {
11972 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
11973 return ExprError();
11977 // In builds with assertions, make sure that we captured everything we
11978 // captured before.
11979 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
11980 for (const auto &I : oldBlock->captures()) {
11981 VarDecl *oldCapture = I.getVariable();
11983 // Ignore parameter packs.
11984 if (isa<ParmVarDecl>(oldCapture) &&
11985 cast<ParmVarDecl>(oldCapture)->isParameterPack())
11988 VarDecl *newCapture =
11989 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
11991 assert(blockScope->CaptureMap.count(newCapture));
11993 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
11997 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
11998 /*Scope=*/nullptr);
12001 template<typename Derived>
12003 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12004 llvm_unreachable("Cannot transform asType expressions yet");
12007 template<typename Derived>
12009 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12010 QualType RetTy = getDerived().TransformType(E->getType());
12011 bool ArgumentChanged = false;
12012 SmallVector<Expr*, 8> SubExprs;
12013 SubExprs.reserve(E->getNumSubExprs());
12014 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12015 SubExprs, &ArgumentChanged))
12016 return ExprError();
12018 if (!getDerived().AlwaysRebuild() &&
12022 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12023 RetTy, E->getOp(), E->getRParenLoc());
12026 //===----------------------------------------------------------------------===//
12027 // Type reconstruction
12028 //===----------------------------------------------------------------------===//
12030 template<typename Derived>
12031 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12032 SourceLocation Star) {
12033 return SemaRef.BuildPointerType(PointeeType, Star,
12034 getDerived().getBaseEntity());
12037 template<typename Derived>
12038 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12039 SourceLocation Star) {
12040 return SemaRef.BuildBlockPointerType(PointeeType, Star,
12041 getDerived().getBaseEntity());
12044 template<typename Derived>
12046 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12047 bool WrittenAsLValue,
12048 SourceLocation Sigil) {
12049 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12050 Sigil, getDerived().getBaseEntity());
12053 template<typename Derived>
12055 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12056 QualType ClassType,
12057 SourceLocation Sigil) {
12058 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12059 getDerived().getBaseEntity());
12062 template<typename Derived>
12063 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12064 const ObjCTypeParamDecl *Decl,
12065 SourceLocation ProtocolLAngleLoc,
12066 ArrayRef<ObjCProtocolDecl *> Protocols,
12067 ArrayRef<SourceLocation> ProtocolLocs,
12068 SourceLocation ProtocolRAngleLoc) {
12069 return SemaRef.BuildObjCTypeParamType(Decl,
12070 ProtocolLAngleLoc, Protocols,
12071 ProtocolLocs, ProtocolRAngleLoc,
12072 /*FailOnError=*/true);
12075 template<typename Derived>
12076 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12078 SourceLocation Loc,
12079 SourceLocation TypeArgsLAngleLoc,
12080 ArrayRef<TypeSourceInfo *> TypeArgs,
12081 SourceLocation TypeArgsRAngleLoc,
12082 SourceLocation ProtocolLAngleLoc,
12083 ArrayRef<ObjCProtocolDecl *> Protocols,
12084 ArrayRef<SourceLocation> ProtocolLocs,
12085 SourceLocation ProtocolRAngleLoc) {
12086 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12087 TypeArgs, TypeArgsRAngleLoc,
12088 ProtocolLAngleLoc, Protocols, ProtocolLocs,
12090 /*FailOnError=*/true);
12093 template<typename Derived>
12094 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12095 QualType PointeeType,
12096 SourceLocation Star) {
12097 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12100 template<typename Derived>
12102 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12103 ArrayType::ArraySizeModifier SizeMod,
12104 const llvm::APInt *Size,
12106 unsigned IndexTypeQuals,
12107 SourceRange BracketsRange) {
12108 if (SizeExpr || !Size)
12109 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12110 IndexTypeQuals, BracketsRange,
12111 getDerived().getBaseEntity());
12113 QualType Types[] = {
12114 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12115 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12116 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12118 const unsigned NumTypes = llvm::array_lengthof(Types);
12120 for (unsigned I = 0; I != NumTypes; ++I)
12121 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12122 SizeType = Types[I];
12126 // Note that we can return a VariableArrayType here in the case where
12127 // the element type was a dependent VariableArrayType.
12128 IntegerLiteral *ArraySize
12129 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12130 /*FIXME*/BracketsRange.getBegin());
12131 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12132 IndexTypeQuals, BracketsRange,
12133 getDerived().getBaseEntity());
12136 template<typename Derived>
12138 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12139 ArrayType::ArraySizeModifier SizeMod,
12140 const llvm::APInt &Size,
12141 unsigned IndexTypeQuals,
12142 SourceRange BracketsRange) {
12143 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
12144 IndexTypeQuals, BracketsRange);
12147 template<typename Derived>
12149 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12150 ArrayType::ArraySizeModifier SizeMod,
12151 unsigned IndexTypeQuals,
12152 SourceRange BracketsRange) {
12153 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12154 IndexTypeQuals, BracketsRange);
12157 template<typename Derived>
12159 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12160 ArrayType::ArraySizeModifier SizeMod,
12162 unsigned IndexTypeQuals,
12163 SourceRange BracketsRange) {
12164 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12166 IndexTypeQuals, BracketsRange);
12169 template<typename Derived>
12171 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12172 ArrayType::ArraySizeModifier SizeMod,
12174 unsigned IndexTypeQuals,
12175 SourceRange BracketsRange) {
12176 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12178 IndexTypeQuals, BracketsRange);
12181 template<typename Derived>
12182 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12183 unsigned NumElements,
12184 VectorType::VectorKind VecKind) {
12185 // FIXME: semantic checking!
12186 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12189 template<typename Derived>
12190 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
12191 unsigned NumElements,
12192 SourceLocation AttributeLoc) {
12193 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
12194 NumElements, true);
12195 IntegerLiteral *VectorSize
12196 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
12198 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
12201 template<typename Derived>
12203 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
12205 SourceLocation AttributeLoc) {
12206 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
12209 template<typename Derived>
12210 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
12212 MutableArrayRef<QualType> ParamTypes,
12213 const FunctionProtoType::ExtProtoInfo &EPI) {
12214 return SemaRef.BuildFunctionType(T, ParamTypes,
12215 getDerived().getBaseLocation(),
12216 getDerived().getBaseEntity(),
12220 template<typename Derived>
12221 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
12222 return SemaRef.Context.getFunctionNoProtoType(T);
12225 template<typename Derived>
12226 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
12228 assert(D && "no decl found");
12229 if (D->isInvalidDecl()) return QualType();
12231 // FIXME: Doesn't account for ObjCInterfaceDecl!
12233 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
12234 // A valid resolved using typename pack expansion decl can have multiple
12235 // UsingDecls, but they must each have exactly one type, and it must be
12236 // the same type in every case. But we must have at least one expansion!
12237 if (UPD->expansions().empty()) {
12238 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
12239 << UPD->isCXXClassMember() << UPD;
12243 // We might still have some unresolved types. Try to pick a resolved type
12244 // if we can. The final instantiation will check that the remaining
12245 // unresolved types instantiate to the type we pick.
12246 QualType FallbackT;
12248 for (auto *E : UPD->expansions()) {
12249 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
12250 if (ThisT.isNull())
12252 else if (ThisT->getAs<UnresolvedUsingType>())
12254 else if (T.isNull())
12257 assert(getSema().Context.hasSameType(ThisT, T) &&
12258 "mismatched resolved types in using pack expansion");
12260 return T.isNull() ? FallbackT : T;
12261 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
12262 assert(Using->hasTypename() &&
12263 "UnresolvedUsingTypenameDecl transformed to non-typename using");
12265 // A valid resolved using typename decl points to exactly one type decl.
12266 assert(++Using->shadow_begin() == Using->shadow_end());
12267 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
12269 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
12270 "UnresolvedUsingTypenameDecl transformed to non-using decl");
12271 Ty = cast<UnresolvedUsingTypenameDecl>(D);
12274 return SemaRef.Context.getTypeDeclType(Ty);
12277 template<typename Derived>
12278 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
12279 SourceLocation Loc) {
12280 return SemaRef.BuildTypeofExprType(E, Loc);
12283 template<typename Derived>
12284 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
12285 return SemaRef.Context.getTypeOfType(Underlying);
12288 template<typename Derived>
12289 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
12290 SourceLocation Loc) {
12291 return SemaRef.BuildDecltypeType(E, Loc);
12294 template<typename Derived>
12295 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
12296 UnaryTransformType::UTTKind UKind,
12297 SourceLocation Loc) {
12298 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
12301 template<typename Derived>
12302 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
12303 TemplateName Template,
12304 SourceLocation TemplateNameLoc,
12305 TemplateArgumentListInfo &TemplateArgs) {
12306 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
12309 template<typename Derived>
12310 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
12311 SourceLocation KWLoc) {
12312 return SemaRef.BuildAtomicType(ValueType, KWLoc);
12315 template<typename Derived>
12316 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
12317 SourceLocation KWLoc,
12319 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
12320 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
12323 template<typename Derived>
12325 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12327 TemplateDecl *Template) {
12328 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
12332 template<typename Derived>
12334 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12335 const IdentifierInfo &Name,
12336 SourceLocation NameLoc,
12337 QualType ObjectType,
12338 NamedDecl *FirstQualifierInScope,
12339 bool AllowInjectedClassName) {
12340 UnqualifiedId TemplateName;
12341 TemplateName.setIdentifier(&Name, NameLoc);
12342 Sema::TemplateTy Template;
12343 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12344 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12345 SS, TemplateKWLoc, TemplateName,
12346 ParsedType::make(ObjectType),
12347 /*EnteringContext=*/false,
12348 Template, AllowInjectedClassName);
12349 return Template.get();
12352 template<typename Derived>
12354 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12355 OverloadedOperatorKind Operator,
12356 SourceLocation NameLoc,
12357 QualType ObjectType,
12358 bool AllowInjectedClassName) {
12359 UnqualifiedId Name;
12360 // FIXME: Bogus location information.
12361 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
12362 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
12363 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12364 Sema::TemplateTy Template;
12365 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12366 SS, TemplateKWLoc, Name,
12367 ParsedType::make(ObjectType),
12368 /*EnteringContext=*/false,
12369 Template, AllowInjectedClassName);
12370 return Template.get();
12373 template<typename Derived>
12375 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
12376 SourceLocation OpLoc,
12380 Expr *Callee = OrigCallee->IgnoreParenCasts();
12381 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
12383 if (First->getObjectKind() == OK_ObjCProperty) {
12384 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12385 if (BinaryOperator::isAssignmentOp(Opc))
12386 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
12388 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
12389 if (Result.isInvalid())
12390 return ExprError();
12391 First = Result.get();
12394 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
12395 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
12396 if (Result.isInvalid())
12397 return ExprError();
12398 Second = Result.get();
12401 // Determine whether this should be a builtin operation.
12402 if (Op == OO_Subscript) {
12403 if (!First->getType()->isOverloadableType() &&
12404 !Second->getType()->isOverloadableType())
12405 return getSema().CreateBuiltinArraySubscriptExpr(First,
12406 Callee->getLocStart(),
12408 } else if (Op == OO_Arrow) {
12409 // -> is never a builtin operation.
12410 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
12411 } else if (Second == nullptr || isPostIncDec) {
12412 if (!First->getType()->isOverloadableType()) {
12413 // The argument is not of overloadable type, so try to create a
12414 // built-in unary operation.
12415 UnaryOperatorKind Opc
12416 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12418 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
12421 if (!First->getType()->isOverloadableType() &&
12422 !Second->getType()->isOverloadableType()) {
12423 // Neither of the arguments is an overloadable type, so try to
12424 // create a built-in binary operation.
12425 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12427 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
12428 if (Result.isInvalid())
12429 return ExprError();
12435 // Compute the transformed set of functions (and function templates) to be
12436 // used during overload resolution.
12437 UnresolvedSet<16> Functions;
12439 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
12440 assert(ULE->requiresADL());
12441 Functions.append(ULE->decls_begin(), ULE->decls_end());
12443 // If we've resolved this to a particular non-member function, just call
12444 // that function. If we resolved it to a member function,
12445 // CreateOverloaded* will find that function for us.
12446 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
12447 if (!isa<CXXMethodDecl>(ND))
12448 Functions.addDecl(ND);
12451 // Add any functions found via argument-dependent lookup.
12452 Expr *Args[2] = { First, Second };
12453 unsigned NumArgs = 1 + (Second != nullptr);
12455 // Create the overloaded operator invocation for unary operators.
12456 if (NumArgs == 1 || isPostIncDec) {
12457 UnaryOperatorKind Opc
12458 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12459 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
12462 if (Op == OO_Subscript) {
12463 SourceLocation LBrace;
12464 SourceLocation RBrace;
12466 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
12467 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
12468 LBrace = SourceLocation::getFromRawEncoding(
12469 NameLoc.CXXOperatorName.BeginOpNameLoc);
12470 RBrace = SourceLocation::getFromRawEncoding(
12471 NameLoc.CXXOperatorName.EndOpNameLoc);
12473 LBrace = Callee->getLocStart();
12477 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
12481 // Create the overloaded operator invocation for binary operators.
12482 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12484 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
12485 if (Result.isInvalid())
12486 return ExprError();
12491 template<typename Derived>
12493 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
12494 SourceLocation OperatorLoc,
12497 TypeSourceInfo *ScopeType,
12498 SourceLocation CCLoc,
12499 SourceLocation TildeLoc,
12500 PseudoDestructorTypeStorage Destroyed) {
12501 QualType BaseType = Base->getType();
12502 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
12503 (!isArrow && !BaseType->getAs<RecordType>()) ||
12504 (isArrow && BaseType->getAs<PointerType>() &&
12505 !BaseType->getAs<PointerType>()->getPointeeType()
12506 ->template getAs<RecordType>())){
12507 // This pseudo-destructor expression is still a pseudo-destructor.
12508 return SemaRef.BuildPseudoDestructorExpr(
12509 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
12510 CCLoc, TildeLoc, Destroyed);
12513 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
12514 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
12515 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
12516 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
12517 NameInfo.setNamedTypeInfo(DestroyedType);
12519 // The scope type is now known to be a valid nested name specifier
12520 // component. Tack it on to the end of the nested name specifier.
12522 if (!ScopeType->getType()->getAs<TagType>()) {
12523 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
12524 diag::err_expected_class_or_namespace)
12525 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
12526 return ExprError();
12528 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
12532 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12533 return getSema().BuildMemberReferenceExpr(Base, BaseType,
12534 OperatorLoc, isArrow,
12536 /*FIXME: FirstQualifier*/ nullptr,
12538 /*TemplateArgs*/ nullptr,
12542 template<typename Derived>
12544 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
12545 SourceLocation Loc = S->getLocStart();
12546 CapturedDecl *CD = S->getCapturedDecl();
12547 unsigned NumParams = CD->getNumParams();
12548 unsigned ContextParamPos = CD->getContextParamPosition();
12549 SmallVector<Sema::CapturedParamNameType, 4> Params;
12550 for (unsigned I = 0; I < NumParams; ++I) {
12551 if (I != ContextParamPos) {
12554 CD->getParam(I)->getName(),
12555 getDerived().TransformType(CD->getParam(I)->getType())));
12557 Params.push_back(std::make_pair(StringRef(), QualType()));
12560 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
12561 S->getCapturedRegionKind(), Params);
12564 Sema::CompoundScopeRAII CompoundScope(getSema());
12565 Body = getDerived().TransformStmt(S->getCapturedStmt());
12568 if (Body.isInvalid()) {
12569 getSema().ActOnCapturedRegionError();
12570 return StmtError();
12573 return getSema().ActOnCapturedRegionEnd(Body.get());
12576 } // end namespace clang
12578 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H