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();
6949 assert(S->getResultDecl() && "ResultDecl must already be built");
6950 StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
6951 if (ResultDecl.isInvalid())
6953 Builder.ResultDecl = ResultDecl.get();
6955 if (auto *ReturnStmt = S->getReturnStmt()) {
6956 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
6957 if (Res.isInvalid())
6959 Builder.ReturnStmt = Res.get();
6963 return getDerived().RebuildCoroutineBodyStmt(Builder);
6966 template<typename Derived>
6968 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
6969 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
6970 /*NotCopyInit*/false);
6971 if (Result.isInvalid())
6974 // Always rebuild; we don't know if this needs to be injected into a new
6975 // context or if the promise type has changed.
6976 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
6980 template<typename Derived>
6982 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
6983 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
6984 /*NotCopyInit*/false);
6985 if (Result.isInvalid())
6988 // Always rebuild; we don't know if this needs to be injected into a new
6989 // context or if the promise type has changed.
6990 return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
6994 template <typename Derived>
6996 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
6997 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
6998 /*NotCopyInit*/ false);
6999 if (OperandResult.isInvalid())
7002 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7003 E->getOperatorCoawaitLookup());
7005 if (LookupResult.isInvalid())
7008 // Always rebuild; we don't know if this needs to be injected into a new
7009 // context or if the promise type has changed.
7010 return getDerived().RebuildDependentCoawaitExpr(
7011 E->getKeywordLoc(), OperandResult.get(),
7012 cast<UnresolvedLookupExpr>(LookupResult.get()));
7015 template<typename Derived>
7017 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7018 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7019 /*NotCopyInit*/false);
7020 if (Result.isInvalid())
7023 // Always rebuild; we don't know if this needs to be injected into a new
7024 // context or if the promise type has changed.
7025 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7028 // Objective-C Statements.
7030 template<typename Derived>
7032 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7033 // Transform the body of the @try.
7034 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7035 if (TryBody.isInvalid())
7038 // Transform the @catch statements (if present).
7039 bool AnyCatchChanged = false;
7040 SmallVector<Stmt*, 8> CatchStmts;
7041 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7042 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7043 if (Catch.isInvalid())
7045 if (Catch.get() != S->getCatchStmt(I))
7046 AnyCatchChanged = true;
7047 CatchStmts.push_back(Catch.get());
7050 // Transform the @finally statement (if present).
7052 if (S->getFinallyStmt()) {
7053 Finally = getDerived().TransformStmt(S->getFinallyStmt());
7054 if (Finally.isInvalid())
7058 // If nothing changed, just retain this statement.
7059 if (!getDerived().AlwaysRebuild() &&
7060 TryBody.get() == S->getTryBody() &&
7062 Finally.get() == S->getFinallyStmt())
7065 // Build a new statement.
7066 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7067 CatchStmts, Finally.get());
7070 template<typename Derived>
7072 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7073 // Transform the @catch parameter, if there is one.
7074 VarDecl *Var = nullptr;
7075 if (VarDecl *FromVar = S->getCatchParamDecl()) {
7076 TypeSourceInfo *TSInfo = nullptr;
7077 if (FromVar->getTypeSourceInfo()) {
7078 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7085 T = TSInfo->getType();
7087 T = getDerived().TransformType(FromVar->getType());
7092 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7097 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7098 if (Body.isInvalid())
7101 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7106 template<typename Derived>
7108 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7109 // Transform the body.
7110 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7111 if (Body.isInvalid())
7114 // If nothing changed, just retain this statement.
7115 if (!getDerived().AlwaysRebuild() &&
7116 Body.get() == S->getFinallyBody())
7119 // Build a new statement.
7120 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7124 template<typename Derived>
7126 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7128 if (S->getThrowExpr()) {
7129 Operand = getDerived().TransformExpr(S->getThrowExpr());
7130 if (Operand.isInvalid())
7134 if (!getDerived().AlwaysRebuild() &&
7135 Operand.get() == S->getThrowExpr())
7138 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7141 template<typename Derived>
7143 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7144 ObjCAtSynchronizedStmt *S) {
7145 // Transform the object we are locking.
7146 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7147 if (Object.isInvalid())
7150 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7152 if (Object.isInvalid())
7155 // Transform the body.
7156 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7157 if (Body.isInvalid())
7160 // If nothing change, just retain the current statement.
7161 if (!getDerived().AlwaysRebuild() &&
7162 Object.get() == S->getSynchExpr() &&
7163 Body.get() == S->getSynchBody())
7166 // Build a new statement.
7167 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7168 Object.get(), Body.get());
7171 template<typename Derived>
7173 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7174 ObjCAutoreleasePoolStmt *S) {
7175 // Transform the body.
7176 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7177 if (Body.isInvalid())
7180 // If nothing changed, just retain this statement.
7181 if (!getDerived().AlwaysRebuild() &&
7182 Body.get() == S->getSubStmt())
7185 // Build a new statement.
7186 return getDerived().RebuildObjCAutoreleasePoolStmt(
7187 S->getAtLoc(), Body.get());
7190 template<typename Derived>
7192 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7193 ObjCForCollectionStmt *S) {
7194 // Transform the element statement.
7195 StmtResult Element = getDerived().TransformStmt(S->getElement());
7196 if (Element.isInvalid())
7199 // Transform the collection expression.
7200 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7201 if (Collection.isInvalid())
7204 // Transform the body.
7205 StmtResult Body = getDerived().TransformStmt(S->getBody());
7206 if (Body.isInvalid())
7209 // If nothing changed, just retain this statement.
7210 if (!getDerived().AlwaysRebuild() &&
7211 Element.get() == S->getElement() &&
7212 Collection.get() == S->getCollection() &&
7213 Body.get() == S->getBody())
7216 // Build a new statement.
7217 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7224 template <typename Derived>
7225 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7226 // Transform the exception declaration, if any.
7227 VarDecl *Var = nullptr;
7228 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7230 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7234 Var = getDerived().RebuildExceptionDecl(
7235 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7236 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7237 if (!Var || Var->isInvalidDecl())
7241 // Transform the actual exception handler.
7242 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7243 if (Handler.isInvalid())
7246 if (!getDerived().AlwaysRebuild() && !Var &&
7247 Handler.get() == S->getHandlerBlock())
7250 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7253 template <typename Derived>
7254 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7255 // Transform the try block itself.
7256 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7257 if (TryBlock.isInvalid())
7260 // Transform the handlers.
7261 bool HandlerChanged = false;
7262 SmallVector<Stmt *, 8> Handlers;
7263 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7264 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7265 if (Handler.isInvalid())
7268 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7269 Handlers.push_back(Handler.getAs<Stmt>());
7272 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7276 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7280 template<typename Derived>
7282 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7283 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7284 if (Range.isInvalid())
7287 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7288 if (Begin.isInvalid())
7290 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7291 if (End.isInvalid())
7294 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7295 if (Cond.isInvalid())
7298 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7299 if (Cond.isInvalid())
7302 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7304 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7305 if (Inc.isInvalid())
7308 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7310 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7311 if (LoopVar.isInvalid())
7314 StmtResult NewStmt = S;
7315 if (getDerived().AlwaysRebuild() ||
7316 Range.get() != S->getRangeStmt() ||
7317 Begin.get() != S->getBeginStmt() ||
7318 End.get() != S->getEndStmt() ||
7319 Cond.get() != S->getCond() ||
7320 Inc.get() != S->getInc() ||
7321 LoopVar.get() != S->getLoopVarStmt()) {
7322 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7324 S->getColonLoc(), Range.get(),
7325 Begin.get(), End.get(),
7327 Inc.get(), LoopVar.get(),
7329 if (NewStmt.isInvalid())
7333 StmtResult Body = getDerived().TransformStmt(S->getBody());
7334 if (Body.isInvalid())
7337 // Body has changed but we didn't rebuild the for-range statement. Rebuild
7338 // it now so we have a new statement to attach the body to.
7339 if (Body.get() != S->getBody() && NewStmt.get() == S) {
7340 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7342 S->getColonLoc(), Range.get(),
7343 Begin.get(), End.get(),
7345 Inc.get(), LoopVar.get(),
7347 if (NewStmt.isInvalid())
7351 if (NewStmt.get() == S)
7354 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7357 template<typename Derived>
7359 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7360 MSDependentExistsStmt *S) {
7361 // Transform the nested-name-specifier, if any.
7362 NestedNameSpecifierLoc QualifierLoc;
7363 if (S->getQualifierLoc()) {
7365 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7370 // Transform the declaration name.
7371 DeclarationNameInfo NameInfo = S->getNameInfo();
7372 if (NameInfo.getName()) {
7373 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7374 if (!NameInfo.getName())
7378 // Check whether anything changed.
7379 if (!getDerived().AlwaysRebuild() &&
7380 QualifierLoc == S->getQualifierLoc() &&
7381 NameInfo.getName() == S->getNameInfo().getName())
7384 // Determine whether this name exists, if we can.
7386 SS.Adopt(QualifierLoc);
7387 bool Dependent = false;
7388 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7389 case Sema::IER_Exists:
7390 if (S->isIfExists())
7393 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7395 case Sema::IER_DoesNotExist:
7396 if (S->isIfNotExists())
7399 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7401 case Sema::IER_Dependent:
7405 case Sema::IER_Error:
7409 // We need to continue with the instantiation, so do so now.
7410 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7411 if (SubStmt.isInvalid())
7414 // If we have resolved the name, just transform to the substatement.
7418 // The name is still dependent, so build a dependent expression again.
7419 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7426 template<typename Derived>
7428 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7429 NestedNameSpecifierLoc QualifierLoc;
7430 if (E->getQualifierLoc()) {
7432 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7437 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7438 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7442 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7443 if (Base.isInvalid())
7446 return new (SemaRef.getASTContext())
7447 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7448 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7449 QualifierLoc, E->getMemberLoc());
7452 template <typename Derived>
7453 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7454 MSPropertySubscriptExpr *E) {
7455 auto BaseRes = getDerived().TransformExpr(E->getBase());
7456 if (BaseRes.isInvalid())
7458 auto IdxRes = getDerived().TransformExpr(E->getIdx());
7459 if (IdxRes.isInvalid())
7462 if (!getDerived().AlwaysRebuild() &&
7463 BaseRes.get() == E->getBase() &&
7464 IdxRes.get() == E->getIdx())
7467 return getDerived().RebuildArraySubscriptExpr(
7468 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7471 template <typename Derived>
7472 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7473 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7474 if (TryBlock.isInvalid())
7477 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7478 if (Handler.isInvalid())
7481 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7482 Handler.get() == S->getHandler())
7485 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7486 TryBlock.get(), Handler.get());
7489 template <typename Derived>
7490 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7491 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7492 if (Block.isInvalid())
7495 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7498 template <typename Derived>
7499 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7500 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7501 if (FilterExpr.isInvalid())
7504 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7505 if (Block.isInvalid())
7508 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7512 template <typename Derived>
7513 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7514 if (isa<SEHFinallyStmt>(Handler))
7515 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7517 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7520 template<typename Derived>
7522 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7526 //===----------------------------------------------------------------------===//
7527 // OpenMP directive transformation
7528 //===----------------------------------------------------------------------===//
7529 template <typename Derived>
7530 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7531 OMPExecutableDirective *D) {
7533 // Transform the clauses
7534 llvm::SmallVector<OMPClause *, 16> TClauses;
7535 ArrayRef<OMPClause *> Clauses = D->clauses();
7536 TClauses.reserve(Clauses.size());
7537 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7540 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7541 OMPClause *Clause = getDerived().TransformOMPClause(*I);
7542 getDerived().getSema().EndOpenMPClause();
7544 TClauses.push_back(Clause);
7546 TClauses.push_back(nullptr);
7549 StmtResult AssociatedStmt;
7550 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7551 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7552 /*CurScope=*/nullptr);
7555 Sema::CompoundScopeRAII CompoundScope(getSema());
7556 int ThisCaptureLevel =
7557 Sema::getOpenMPCaptureLevels(D->getDirectiveKind());
7558 Stmt *CS = D->getAssociatedStmt();
7559 while (--ThisCaptureLevel >= 0)
7560 CS = cast<CapturedStmt>(CS)->getCapturedStmt();
7561 Body = getDerived().TransformStmt(CS);
7564 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7565 if (AssociatedStmt.isInvalid()) {
7569 if (TClauses.size() != Clauses.size()) {
7573 // Transform directive name for 'omp critical' directive.
7574 DeclarationNameInfo DirName;
7575 if (D->getDirectiveKind() == OMPD_critical) {
7576 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7577 DirName = getDerived().TransformDeclarationNameInfo(DirName);
7579 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7580 if (D->getDirectiveKind() == OMPD_cancellation_point) {
7581 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7582 } else if (D->getDirectiveKind() == OMPD_cancel) {
7583 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7586 return getDerived().RebuildOMPExecutableDirective(
7587 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7588 AssociatedStmt.get(), D->getLocStart(), D->getLocEnd());
7591 template <typename Derived>
7593 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7594 DeclarationNameInfo DirName;
7595 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7597 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7598 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7602 template <typename Derived>
7604 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7605 DeclarationNameInfo DirName;
7606 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7608 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7609 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7613 template <typename Derived>
7615 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7616 DeclarationNameInfo DirName;
7617 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7619 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7620 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7624 template <typename Derived>
7626 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7627 DeclarationNameInfo DirName;
7628 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7630 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7631 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7635 template <typename Derived>
7637 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7638 DeclarationNameInfo DirName;
7639 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7641 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7642 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7646 template <typename Derived>
7648 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7649 DeclarationNameInfo DirName;
7650 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7652 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7653 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7657 template <typename Derived>
7659 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7660 DeclarationNameInfo DirName;
7661 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7663 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7664 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7668 template <typename Derived>
7670 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
7671 DeclarationNameInfo DirName;
7672 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
7674 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7675 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7679 template <typename Derived>
7681 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
7682 getDerived().getSema().StartOpenMPDSABlock(
7683 OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
7684 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7685 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7689 template <typename Derived>
7690 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
7691 OMPParallelForDirective *D) {
7692 DeclarationNameInfo DirName;
7693 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
7694 nullptr, D->getLocStart());
7695 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7696 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7700 template <typename Derived>
7701 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
7702 OMPParallelForSimdDirective *D) {
7703 DeclarationNameInfo DirName;
7704 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
7705 nullptr, D->getLocStart());
7706 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7707 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7711 template <typename Derived>
7712 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
7713 OMPParallelSectionsDirective *D) {
7714 DeclarationNameInfo DirName;
7715 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
7716 nullptr, D->getLocStart());
7717 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7718 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7722 template <typename Derived>
7724 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
7725 DeclarationNameInfo DirName;
7726 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
7728 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7729 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7733 template <typename Derived>
7734 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
7735 OMPTaskyieldDirective *D) {
7736 DeclarationNameInfo DirName;
7737 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
7739 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7740 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7744 template <typename Derived>
7746 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
7747 DeclarationNameInfo DirName;
7748 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
7750 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7751 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7755 template <typename Derived>
7757 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
7758 DeclarationNameInfo DirName;
7759 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
7761 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7762 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7766 template <typename Derived>
7767 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
7768 OMPTaskgroupDirective *D) {
7769 DeclarationNameInfo DirName;
7770 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
7772 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7773 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7777 template <typename Derived>
7779 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
7780 DeclarationNameInfo DirName;
7781 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
7783 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7784 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7788 template <typename Derived>
7790 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
7791 DeclarationNameInfo DirName;
7792 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
7794 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7795 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7799 template <typename Derived>
7801 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
7802 DeclarationNameInfo DirName;
7803 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
7805 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7806 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7810 template <typename Derived>
7812 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
7813 DeclarationNameInfo DirName;
7814 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
7816 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7817 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7821 template <typename Derived>
7822 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
7823 OMPTargetDataDirective *D) {
7824 DeclarationNameInfo DirName;
7825 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
7827 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7828 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7832 template <typename Derived>
7833 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
7834 OMPTargetEnterDataDirective *D) {
7835 DeclarationNameInfo DirName;
7836 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
7837 nullptr, D->getLocStart());
7838 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7839 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7843 template <typename Derived>
7844 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
7845 OMPTargetExitDataDirective *D) {
7846 DeclarationNameInfo DirName;
7847 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
7848 nullptr, D->getLocStart());
7849 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7850 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7854 template <typename Derived>
7855 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
7856 OMPTargetParallelDirective *D) {
7857 DeclarationNameInfo DirName;
7858 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
7859 nullptr, D->getLocStart());
7860 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7861 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7865 template <typename Derived>
7866 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
7867 OMPTargetParallelForDirective *D) {
7868 DeclarationNameInfo DirName;
7869 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
7870 nullptr, D->getLocStart());
7871 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7872 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7876 template <typename Derived>
7877 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
7878 OMPTargetUpdateDirective *D) {
7879 DeclarationNameInfo DirName;
7880 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
7881 nullptr, D->getLocStart());
7882 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7883 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7887 template <typename Derived>
7889 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
7890 DeclarationNameInfo DirName;
7891 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
7893 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7894 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7898 template <typename Derived>
7899 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
7900 OMPCancellationPointDirective *D) {
7901 DeclarationNameInfo DirName;
7902 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
7903 nullptr, D->getLocStart());
7904 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7905 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7909 template <typename Derived>
7911 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
7912 DeclarationNameInfo DirName;
7913 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
7915 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7916 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7920 template <typename Derived>
7922 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
7923 DeclarationNameInfo DirName;
7924 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
7926 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7927 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7931 template <typename Derived>
7932 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
7933 OMPTaskLoopSimdDirective *D) {
7934 DeclarationNameInfo DirName;
7935 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
7936 nullptr, D->getLocStart());
7937 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7938 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7942 template <typename Derived>
7943 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
7944 OMPDistributeDirective *D) {
7945 DeclarationNameInfo DirName;
7946 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
7948 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7949 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7953 template <typename Derived>
7954 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
7955 OMPDistributeParallelForDirective *D) {
7956 DeclarationNameInfo DirName;
7957 getDerived().getSema().StartOpenMPDSABlock(
7958 OMPD_distribute_parallel_for, DirName, nullptr, D->getLocStart());
7959 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7960 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7964 template <typename Derived>
7966 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
7967 OMPDistributeParallelForSimdDirective *D) {
7968 DeclarationNameInfo DirName;
7969 getDerived().getSema().StartOpenMPDSABlock(
7970 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getLocStart());
7971 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7972 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7976 template <typename Derived>
7977 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
7978 OMPDistributeSimdDirective *D) {
7979 DeclarationNameInfo DirName;
7980 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
7981 nullptr, D->getLocStart());
7982 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7983 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7987 template <typename Derived>
7988 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
7989 OMPTargetParallelForSimdDirective *D) {
7990 DeclarationNameInfo DirName;
7991 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for_simd,
7994 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7995 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7999 template <typename Derived>
8000 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8001 OMPTargetSimdDirective *D) {
8002 DeclarationNameInfo DirName;
8003 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8005 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8006 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8010 template <typename Derived>
8011 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8012 OMPTeamsDistributeDirective *D) {
8013 DeclarationNameInfo DirName;
8014 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8015 nullptr, D->getLocStart());
8016 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8017 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8021 template <typename Derived>
8022 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8023 OMPTeamsDistributeSimdDirective *D) {
8024 DeclarationNameInfo DirName;
8025 getDerived().getSema().StartOpenMPDSABlock(
8026 OMPD_teams_distribute_simd, DirName, nullptr, D->getLocStart());
8027 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8028 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8032 template <typename Derived>
8033 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8034 OMPTeamsDistributeParallelForSimdDirective *D) {
8035 DeclarationNameInfo DirName;
8036 getDerived().getSema().StartOpenMPDSABlock(
8037 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr, D->getLocStart());
8038 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8039 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8043 template <typename Derived>
8044 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8045 OMPTeamsDistributeParallelForDirective *D) {
8046 DeclarationNameInfo DirName;
8047 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute_parallel_for,
8048 DirName, nullptr, D->getLocStart());
8049 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8050 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8054 template <typename Derived>
8055 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8056 OMPTargetTeamsDirective *D) {
8057 DeclarationNameInfo DirName;
8058 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8059 nullptr, D->getLocStart());
8060 auto Res = getDerived().TransformOMPExecutableDirective(D);
8061 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8065 template <typename Derived>
8066 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8067 OMPTargetTeamsDistributeDirective *D) {
8068 DeclarationNameInfo DirName;
8069 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_distribute,
8070 DirName, nullptr, D->getLocStart());
8071 auto Res = getDerived().TransformOMPExecutableDirective(D);
8072 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8076 template <typename Derived>
8078 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8079 OMPTargetTeamsDistributeParallelForDirective *D) {
8080 DeclarationNameInfo DirName;
8081 getDerived().getSema().StartOpenMPDSABlock(
8082 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8084 auto Res = getDerived().TransformOMPExecutableDirective(D);
8085 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8089 template <typename Derived>
8090 StmtResult TreeTransform<Derived>::
8091 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8092 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8093 DeclarationNameInfo DirName;
8094 getDerived().getSema().StartOpenMPDSABlock(
8095 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8097 auto Res = getDerived().TransformOMPExecutableDirective(D);
8098 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8102 template <typename Derived>
8104 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8105 OMPTargetTeamsDistributeSimdDirective *D) {
8106 DeclarationNameInfo DirName;
8107 getDerived().getSema().StartOpenMPDSABlock(
8108 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getLocStart());
8109 auto Res = getDerived().TransformOMPExecutableDirective(D);
8110 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8115 //===----------------------------------------------------------------------===//
8116 // OpenMP clause transformation
8117 //===----------------------------------------------------------------------===//
8118 template <typename Derived>
8119 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8120 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8121 if (Cond.isInvalid())
8123 return getDerived().RebuildOMPIfClause(
8124 C->getNameModifier(), Cond.get(), C->getLocStart(), C->getLParenLoc(),
8125 C->getNameModifierLoc(), C->getColonLoc(), C->getLocEnd());
8128 template <typename Derived>
8129 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8130 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8131 if (Cond.isInvalid())
8133 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
8134 C->getLParenLoc(), C->getLocEnd());
8137 template <typename Derived>
8139 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8140 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8141 if (NumThreads.isInvalid())
8143 return getDerived().RebuildOMPNumThreadsClause(
8144 NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8147 template <typename Derived>
8149 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8150 ExprResult E = getDerived().TransformExpr(C->getSafelen());
8153 return getDerived().RebuildOMPSafelenClause(
8154 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8157 template <typename Derived>
8159 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8160 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8163 return getDerived().RebuildOMPSimdlenClause(
8164 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8167 template <typename Derived>
8169 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8170 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8173 return getDerived().RebuildOMPCollapseClause(
8174 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8177 template <typename Derived>
8179 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8180 return getDerived().RebuildOMPDefaultClause(
8181 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
8182 C->getLParenLoc(), C->getLocEnd());
8185 template <typename Derived>
8187 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8188 return getDerived().RebuildOMPProcBindClause(
8189 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
8190 C->getLParenLoc(), C->getLocEnd());
8193 template <typename Derived>
8195 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8196 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8199 return getDerived().RebuildOMPScheduleClause(
8200 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8201 C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
8202 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8203 C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
8206 template <typename Derived>
8208 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8210 if (auto *Num = C->getNumForLoops()) {
8211 E = getDerived().TransformExpr(Num);
8215 return getDerived().RebuildOMPOrderedClause(C->getLocStart(), C->getLocEnd(),
8216 C->getLParenLoc(), E.get());
8219 template <typename Derived>
8221 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8222 // No need to rebuild this clause, no template-dependent parameters.
8226 template <typename Derived>
8228 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8229 // No need to rebuild this clause, no template-dependent parameters.
8233 template <typename Derived>
8235 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8236 // No need to rebuild this clause, no template-dependent parameters.
8240 template <typename Derived>
8241 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8242 // No need to rebuild this clause, no template-dependent parameters.
8246 template <typename Derived>
8247 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8248 // No need to rebuild this clause, no template-dependent parameters.
8252 template <typename Derived>
8254 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8255 // No need to rebuild this clause, no template-dependent parameters.
8259 template <typename Derived>
8261 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8262 // No need to rebuild this clause, no template-dependent parameters.
8266 template <typename Derived>
8268 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8269 // No need to rebuild this clause, no template-dependent parameters.
8273 template <typename Derived>
8275 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8276 // No need to rebuild this clause, no template-dependent parameters.
8280 template <typename Derived>
8281 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8282 // No need to rebuild this clause, no template-dependent parameters.
8286 template <typename Derived>
8288 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8289 // No need to rebuild this clause, no template-dependent parameters.
8293 template <typename Derived>
8295 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8296 llvm::SmallVector<Expr *, 16> Vars;
8297 Vars.reserve(C->varlist_size());
8298 for (auto *VE : C->varlists()) {
8299 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8300 if (EVar.isInvalid())
8302 Vars.push_back(EVar.get());
8304 return getDerived().RebuildOMPPrivateClause(
8305 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8308 template <typename Derived>
8309 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8310 OMPFirstprivateClause *C) {
8311 llvm::SmallVector<Expr *, 16> Vars;
8312 Vars.reserve(C->varlist_size());
8313 for (auto *VE : C->varlists()) {
8314 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8315 if (EVar.isInvalid())
8317 Vars.push_back(EVar.get());
8319 return getDerived().RebuildOMPFirstprivateClause(
8320 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8323 template <typename Derived>
8325 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8326 llvm::SmallVector<Expr *, 16> Vars;
8327 Vars.reserve(C->varlist_size());
8328 for (auto *VE : C->varlists()) {
8329 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8330 if (EVar.isInvalid())
8332 Vars.push_back(EVar.get());
8334 return getDerived().RebuildOMPLastprivateClause(
8335 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8338 template <typename Derived>
8340 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8341 llvm::SmallVector<Expr *, 16> Vars;
8342 Vars.reserve(C->varlist_size());
8343 for (auto *VE : C->varlists()) {
8344 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8345 if (EVar.isInvalid())
8347 Vars.push_back(EVar.get());
8349 return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
8350 C->getLParenLoc(), C->getLocEnd());
8353 template <typename Derived>
8355 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8356 llvm::SmallVector<Expr *, 16> Vars;
8357 Vars.reserve(C->varlist_size());
8358 for (auto *VE : C->varlists()) {
8359 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8360 if (EVar.isInvalid())
8362 Vars.push_back(EVar.get());
8364 CXXScopeSpec ReductionIdScopeSpec;
8365 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8367 DeclarationNameInfo NameInfo = C->getNameInfo();
8368 if (NameInfo.getName()) {
8369 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8370 if (!NameInfo.getName())
8373 // Build a list of all UDR decls with the same names ranged by the Scopes.
8374 // The Scope boundary is a duplication of the previous decl.
8375 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8376 for (auto *E : C->reduction_ops()) {
8377 // Transform all the decls.
8379 auto *ULE = cast<UnresolvedLookupExpr>(E);
8380 UnresolvedSet<8> Decls;
8381 for (auto *D : ULE->decls()) {
8383 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8384 Decls.addDecl(InstD, InstD->getAccess());
8386 UnresolvedReductions.push_back(
8387 UnresolvedLookupExpr::Create(
8388 SemaRef.Context, /*NamingClass=*/nullptr,
8389 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8390 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8391 Decls.begin(), Decls.end()));
8393 UnresolvedReductions.push_back(nullptr);
8395 return getDerived().RebuildOMPReductionClause(
8396 Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
8397 C->getLocEnd(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8400 template <typename Derived>
8402 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8403 llvm::SmallVector<Expr *, 16> Vars;
8404 Vars.reserve(C->varlist_size());
8405 for (auto *VE : C->varlists()) {
8406 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8407 if (EVar.isInvalid())
8409 Vars.push_back(EVar.get());
8411 ExprResult Step = getDerived().TransformExpr(C->getStep());
8412 if (Step.isInvalid())
8414 return getDerived().RebuildOMPLinearClause(
8415 Vars, Step.get(), C->getLocStart(), C->getLParenLoc(), C->getModifier(),
8416 C->getModifierLoc(), C->getColonLoc(), C->getLocEnd());
8419 template <typename Derived>
8421 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8422 llvm::SmallVector<Expr *, 16> Vars;
8423 Vars.reserve(C->varlist_size());
8424 for (auto *VE : C->varlists()) {
8425 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8426 if (EVar.isInvalid())
8428 Vars.push_back(EVar.get());
8430 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8431 if (Alignment.isInvalid())
8433 return getDerived().RebuildOMPAlignedClause(
8434 Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
8435 C->getColonLoc(), C->getLocEnd());
8438 template <typename Derived>
8440 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8441 llvm::SmallVector<Expr *, 16> Vars;
8442 Vars.reserve(C->varlist_size());
8443 for (auto *VE : C->varlists()) {
8444 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8445 if (EVar.isInvalid())
8447 Vars.push_back(EVar.get());
8449 return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
8450 C->getLParenLoc(), C->getLocEnd());
8453 template <typename Derived>
8455 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8456 llvm::SmallVector<Expr *, 16> Vars;
8457 Vars.reserve(C->varlist_size());
8458 for (auto *VE : C->varlists()) {
8459 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8460 if (EVar.isInvalid())
8462 Vars.push_back(EVar.get());
8464 return getDerived().RebuildOMPCopyprivateClause(
8465 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8468 template <typename Derived>
8469 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8470 llvm::SmallVector<Expr *, 16> Vars;
8471 Vars.reserve(C->varlist_size());
8472 for (auto *VE : C->varlists()) {
8473 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8474 if (EVar.isInvalid())
8476 Vars.push_back(EVar.get());
8478 return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
8479 C->getLParenLoc(), C->getLocEnd());
8482 template <typename Derived>
8484 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8485 llvm::SmallVector<Expr *, 16> Vars;
8486 Vars.reserve(C->varlist_size());
8487 for (auto *VE : C->varlists()) {
8488 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8489 if (EVar.isInvalid())
8491 Vars.push_back(EVar.get());
8493 return getDerived().RebuildOMPDependClause(
8494 C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8495 C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8498 template <typename Derived>
8500 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
8501 ExprResult E = getDerived().TransformExpr(C->getDevice());
8504 return getDerived().RebuildOMPDeviceClause(
8505 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8508 template <typename Derived>
8509 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
8510 llvm::SmallVector<Expr *, 16> Vars;
8511 Vars.reserve(C->varlist_size());
8512 for (auto *VE : C->varlists()) {
8513 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8514 if (EVar.isInvalid())
8516 Vars.push_back(EVar.get());
8518 return getDerived().RebuildOMPMapClause(
8519 C->getMapTypeModifier(), C->getMapType(), C->isImplicitMapType(),
8520 C->getMapLoc(), C->getColonLoc(), Vars, C->getLocStart(),
8521 C->getLParenLoc(), C->getLocEnd());
8524 template <typename Derived>
8526 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
8527 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
8530 return getDerived().RebuildOMPNumTeamsClause(
8531 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8534 template <typename Derived>
8536 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
8537 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
8540 return getDerived().RebuildOMPThreadLimitClause(
8541 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8544 template <typename Derived>
8546 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
8547 ExprResult E = getDerived().TransformExpr(C->getPriority());
8550 return getDerived().RebuildOMPPriorityClause(
8551 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8554 template <typename Derived>
8556 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
8557 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
8560 return getDerived().RebuildOMPGrainsizeClause(
8561 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8564 template <typename Derived>
8566 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
8567 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
8570 return getDerived().RebuildOMPNumTasksClause(
8571 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8574 template <typename Derived>
8575 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
8576 ExprResult E = getDerived().TransformExpr(C->getHint());
8579 return getDerived().RebuildOMPHintClause(E.get(), C->getLocStart(),
8580 C->getLParenLoc(), C->getLocEnd());
8583 template <typename Derived>
8584 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
8585 OMPDistScheduleClause *C) {
8586 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8589 return getDerived().RebuildOMPDistScheduleClause(
8590 C->getDistScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
8591 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
8594 template <typename Derived>
8596 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
8600 template <typename Derived>
8601 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
8602 llvm::SmallVector<Expr *, 16> Vars;
8603 Vars.reserve(C->varlist_size());
8604 for (auto *VE : C->varlists()) {
8605 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8606 if (EVar.isInvalid())
8608 Vars.push_back(EVar.get());
8610 return getDerived().RebuildOMPToClause(Vars, C->getLocStart(),
8611 C->getLParenLoc(), C->getLocEnd());
8614 template <typename Derived>
8615 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
8616 llvm::SmallVector<Expr *, 16> Vars;
8617 Vars.reserve(C->varlist_size());
8618 for (auto *VE : C->varlists()) {
8619 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8620 if (EVar.isInvalid())
8622 Vars.push_back(EVar.get());
8624 return getDerived().RebuildOMPFromClause(Vars, C->getLocStart(),
8625 C->getLParenLoc(), C->getLocEnd());
8628 template <typename Derived>
8629 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
8630 OMPUseDevicePtrClause *C) {
8631 llvm::SmallVector<Expr *, 16> Vars;
8632 Vars.reserve(C->varlist_size());
8633 for (auto *VE : C->varlists()) {
8634 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8635 if (EVar.isInvalid())
8637 Vars.push_back(EVar.get());
8639 return getDerived().RebuildOMPUseDevicePtrClause(
8640 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8643 template <typename Derived>
8645 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
8646 llvm::SmallVector<Expr *, 16> Vars;
8647 Vars.reserve(C->varlist_size());
8648 for (auto *VE : C->varlists()) {
8649 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8650 if (EVar.isInvalid())
8652 Vars.push_back(EVar.get());
8654 return getDerived().RebuildOMPIsDevicePtrClause(
8655 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8658 //===----------------------------------------------------------------------===//
8659 // Expression transformation
8660 //===----------------------------------------------------------------------===//
8661 template<typename Derived>
8663 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
8664 if (!E->isTypeDependent())
8667 return getDerived().RebuildPredefinedExpr(E->getLocation(),
8671 template<typename Derived>
8673 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
8674 NestedNameSpecifierLoc QualifierLoc;
8675 if (E->getQualifierLoc()) {
8677 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8683 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
8688 DeclarationNameInfo NameInfo = E->getNameInfo();
8689 if (NameInfo.getName()) {
8690 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8691 if (!NameInfo.getName())
8695 if (!getDerived().AlwaysRebuild() &&
8696 QualifierLoc == E->getQualifierLoc() &&
8697 ND == E->getDecl() &&
8698 NameInfo.getName() == E->getDecl()->getDeclName() &&
8699 !E->hasExplicitTemplateArgs()) {
8701 // Mark it referenced in the new context regardless.
8702 // FIXME: this is a bit instantiation-specific.
8703 SemaRef.MarkDeclRefReferenced(E);
8708 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
8709 if (E->hasExplicitTemplateArgs()) {
8710 TemplateArgs = &TransArgs;
8711 TransArgs.setLAngleLoc(E->getLAngleLoc());
8712 TransArgs.setRAngleLoc(E->getRAngleLoc());
8713 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
8714 E->getNumTemplateArgs(),
8719 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
8723 template<typename Derived>
8725 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
8729 template<typename Derived>
8731 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
8735 template<typename Derived>
8737 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
8741 template<typename Derived>
8743 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
8747 template<typename Derived>
8749 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
8753 template<typename Derived>
8755 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
8756 if (FunctionDecl *FD = E->getDirectCallee())
8757 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
8758 return SemaRef.MaybeBindToTemporary(E);
8761 template<typename Derived>
8763 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
8764 ExprResult ControllingExpr =
8765 getDerived().TransformExpr(E->getControllingExpr());
8766 if (ControllingExpr.isInvalid())
8769 SmallVector<Expr *, 4> AssocExprs;
8770 SmallVector<TypeSourceInfo *, 4> AssocTypes;
8771 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
8772 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
8774 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
8777 AssocTypes.push_back(AssocType);
8779 AssocTypes.push_back(nullptr);
8782 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
8783 if (AssocExpr.isInvalid())
8785 AssocExprs.push_back(AssocExpr.get());
8788 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
8791 ControllingExpr.get(),
8796 template<typename Derived>
8798 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
8799 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8800 if (SubExpr.isInvalid())
8803 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
8806 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
8810 /// \brief The operand of a unary address-of operator has special rules: it's
8811 /// allowed to refer to a non-static member of a class even if there's no 'this'
8812 /// object available.
8813 template<typename Derived>
8815 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
8816 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
8817 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
8819 return getDerived().TransformExpr(E);
8822 template<typename Derived>
8824 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
8826 if (E->getOpcode() == UO_AddrOf)
8827 SubExpr = TransformAddressOfOperand(E->getSubExpr());
8829 SubExpr = TransformExpr(E->getSubExpr());
8830 if (SubExpr.isInvalid())
8833 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
8836 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
8841 template<typename Derived>
8843 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
8844 // Transform the type.
8845 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
8849 // Transform all of the components into components similar to what the
8851 // FIXME: It would be slightly more efficient in the non-dependent case to
8852 // just map FieldDecls, rather than requiring the rebuilder to look for
8853 // the fields again. However, __builtin_offsetof is rare enough in
8854 // template code that we don't care.
8855 bool ExprChanged = false;
8856 typedef Sema::OffsetOfComponent Component;
8857 SmallVector<Component, 4> Components;
8858 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
8859 const OffsetOfNode &ON = E->getComponent(I);
8861 Comp.isBrackets = true;
8862 Comp.LocStart = ON.getSourceRange().getBegin();
8863 Comp.LocEnd = ON.getSourceRange().getEnd();
8864 switch (ON.getKind()) {
8865 case OffsetOfNode::Array: {
8866 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
8867 ExprResult Index = getDerived().TransformExpr(FromIndex);
8868 if (Index.isInvalid())
8871 ExprChanged = ExprChanged || Index.get() != FromIndex;
8872 Comp.isBrackets = true;
8873 Comp.U.E = Index.get();
8877 case OffsetOfNode::Field:
8878 case OffsetOfNode::Identifier:
8879 Comp.isBrackets = false;
8880 Comp.U.IdentInfo = ON.getFieldName();
8881 if (!Comp.U.IdentInfo)
8886 case OffsetOfNode::Base:
8887 // Will be recomputed during the rebuild.
8891 Components.push_back(Comp);
8894 // If nothing changed, retain the existing expression.
8895 if (!getDerived().AlwaysRebuild() &&
8896 Type == E->getTypeSourceInfo() &&
8900 // Build a new offsetof expression.
8901 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
8902 Components, E->getRParenLoc());
8905 template<typename Derived>
8907 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
8908 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
8909 "opaque value expression requires transformation");
8913 template<typename Derived>
8915 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
8919 template<typename Derived>
8921 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
8922 // Rebuild the syntactic form. The original syntactic form has
8923 // opaque-value expressions in it, so strip those away and rebuild
8924 // the result. This is a really awful way of doing this, but the
8925 // better solution (rebuilding the semantic expressions and
8926 // rebinding OVEs as necessary) doesn't work; we'd need
8927 // TreeTransform to not strip away implicit conversions.
8928 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
8929 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
8930 if (result.isInvalid()) return ExprError();
8932 // If that gives us a pseudo-object result back, the pseudo-object
8933 // expression must have been an lvalue-to-rvalue conversion which we
8935 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
8936 result = SemaRef.checkPseudoObjectRValue(result.get());
8941 template<typename Derived>
8943 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
8944 UnaryExprOrTypeTraitExpr *E) {
8945 if (E->isArgumentType()) {
8946 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
8948 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
8952 if (!getDerived().AlwaysRebuild() && OldT == NewT)
8955 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
8957 E->getSourceRange());
8960 // C++0x [expr.sizeof]p1:
8961 // The operand is either an expression, which is an unevaluated operand
8963 EnterExpressionEvaluationContext Unevaluated(
8964 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
8965 Sema::ReuseLambdaContextDecl);
8967 // Try to recover if we have something like sizeof(T::X) where X is a type.
8968 // Notably, there must be *exactly* one set of parens if X is a type.
8969 TypeSourceInfo *RecoveryTSI = nullptr;
8971 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
8973 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
8974 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
8975 PE, DRE, false, &RecoveryTSI);
8977 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
8980 return getDerived().RebuildUnaryExprOrTypeTrait(
8981 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
8982 } else if (SubExpr.isInvalid())
8985 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
8988 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
8989 E->getOperatorLoc(),
8991 E->getSourceRange());
8994 template<typename Derived>
8996 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
8997 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8998 if (LHS.isInvalid())
9001 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9002 if (RHS.isInvalid())
9006 if (!getDerived().AlwaysRebuild() &&
9007 LHS.get() == E->getLHS() &&
9008 RHS.get() == E->getRHS())
9011 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
9012 /*FIXME:*/E->getLHS()->getLocStart(),
9014 E->getRBracketLoc());
9017 template <typename Derived>
9019 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9020 ExprResult Base = getDerived().TransformExpr(E->getBase());
9021 if (Base.isInvalid())
9024 ExprResult LowerBound;
9025 if (E->getLowerBound()) {
9026 LowerBound = getDerived().TransformExpr(E->getLowerBound());
9027 if (LowerBound.isInvalid())
9032 if (E->getLength()) {
9033 Length = getDerived().TransformExpr(E->getLength());
9034 if (Length.isInvalid())
9038 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9039 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9042 return getDerived().RebuildOMPArraySectionExpr(
9043 Base.get(), E->getBase()->getLocEnd(), LowerBound.get(), E->getColonLoc(),
9044 Length.get(), E->getRBracketLoc());
9047 template<typename Derived>
9049 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9050 // Transform the callee.
9051 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9052 if (Callee.isInvalid())
9055 // Transform arguments.
9056 bool ArgChanged = false;
9057 SmallVector<Expr*, 8> Args;
9058 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9062 if (!getDerived().AlwaysRebuild() &&
9063 Callee.get() == E->getCallee() &&
9065 return SemaRef.MaybeBindToTemporary(E);
9067 // FIXME: Wrong source location information for the '('.
9068 SourceLocation FakeLParenLoc
9069 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9070 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9075 template<typename Derived>
9077 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9078 ExprResult Base = getDerived().TransformExpr(E->getBase());
9079 if (Base.isInvalid())
9082 NestedNameSpecifierLoc QualifierLoc;
9083 if (E->hasQualifier()) {
9085 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9090 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9093 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9094 E->getMemberDecl()));
9098 NamedDecl *FoundDecl = E->getFoundDecl();
9099 if (FoundDecl == E->getMemberDecl()) {
9102 FoundDecl = cast_or_null<NamedDecl>(
9103 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9108 if (!getDerived().AlwaysRebuild() &&
9109 Base.get() == E->getBase() &&
9110 QualifierLoc == E->getQualifierLoc() &&
9111 Member == E->getMemberDecl() &&
9112 FoundDecl == E->getFoundDecl() &&
9113 !E->hasExplicitTemplateArgs()) {
9115 // Mark it referenced in the new context regardless.
9116 // FIXME: this is a bit instantiation-specific.
9117 SemaRef.MarkMemberReferenced(E);
9122 TemplateArgumentListInfo TransArgs;
9123 if (E->hasExplicitTemplateArgs()) {
9124 TransArgs.setLAngleLoc(E->getLAngleLoc());
9125 TransArgs.setRAngleLoc(E->getRAngleLoc());
9126 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9127 E->getNumTemplateArgs(),
9132 // FIXME: Bogus source location for the operator
9133 SourceLocation FakeOperatorLoc =
9134 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9136 // FIXME: to do this check properly, we will need to preserve the
9137 // first-qualifier-in-scope here, just in case we had a dependent
9138 // base (and therefore couldn't do the check) and a
9139 // nested-name-qualifier (and therefore could do the lookup).
9140 NamedDecl *FirstQualifierInScope = nullptr;
9141 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9142 if (MemberNameInfo.getName()) {
9143 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9144 if (!MemberNameInfo.getName())
9148 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9155 (E->hasExplicitTemplateArgs()
9156 ? &TransArgs : nullptr),
9157 FirstQualifierInScope);
9160 template<typename Derived>
9162 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9163 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9164 if (LHS.isInvalid())
9167 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9168 if (RHS.isInvalid())
9171 if (!getDerived().AlwaysRebuild() &&
9172 LHS.get() == E->getLHS() &&
9173 RHS.get() == E->getRHS())
9176 Sema::FPContractStateRAII FPContractState(getSema());
9177 getSema().FPFeatures = E->getFPFeatures();
9179 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9180 LHS.get(), RHS.get());
9183 template<typename Derived>
9185 TreeTransform<Derived>::TransformCompoundAssignOperator(
9186 CompoundAssignOperator *E) {
9187 return getDerived().TransformBinaryOperator(E);
9190 template<typename Derived>
9191 ExprResult TreeTransform<Derived>::
9192 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9193 // Just rebuild the common and RHS expressions and see whether we
9196 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9197 if (commonExpr.isInvalid())
9200 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9201 if (rhs.isInvalid())
9204 if (!getDerived().AlwaysRebuild() &&
9205 commonExpr.get() == e->getCommon() &&
9206 rhs.get() == e->getFalseExpr())
9209 return getDerived().RebuildConditionalOperator(commonExpr.get(),
9210 e->getQuestionLoc(),
9216 template<typename Derived>
9218 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9219 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9220 if (Cond.isInvalid())
9223 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9224 if (LHS.isInvalid())
9227 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9228 if (RHS.isInvalid())
9231 if (!getDerived().AlwaysRebuild() &&
9232 Cond.get() == E->getCond() &&
9233 LHS.get() == E->getLHS() &&
9234 RHS.get() == E->getRHS())
9237 return getDerived().RebuildConditionalOperator(Cond.get(),
9238 E->getQuestionLoc(),
9244 template<typename Derived>
9246 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9247 // Implicit casts are eliminated during transformation, since they
9248 // will be recomputed by semantic analysis after transformation.
9249 return getDerived().TransformExpr(E->getSubExprAsWritten());
9252 template<typename Derived>
9254 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9255 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9260 = getDerived().TransformExpr(E->getSubExprAsWritten());
9261 if (SubExpr.isInvalid())
9264 if (!getDerived().AlwaysRebuild() &&
9265 Type == E->getTypeInfoAsWritten() &&
9266 SubExpr.get() == E->getSubExpr())
9269 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9275 template<typename Derived>
9277 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9278 TypeSourceInfo *OldT = E->getTypeSourceInfo();
9279 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9283 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9284 if (Init.isInvalid())
9287 if (!getDerived().AlwaysRebuild() &&
9289 Init.get() == E->getInitializer())
9290 return SemaRef.MaybeBindToTemporary(E);
9292 // Note: the expression type doesn't necessarily match the
9293 // type-as-written, but that's okay, because it should always be
9294 // derivable from the initializer.
9296 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
9297 /*FIXME:*/E->getInitializer()->getLocEnd(),
9301 template<typename Derived>
9303 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9304 ExprResult Base = getDerived().TransformExpr(E->getBase());
9305 if (Base.isInvalid())
9308 if (!getDerived().AlwaysRebuild() &&
9309 Base.get() == E->getBase())
9312 // FIXME: Bad source location
9313 SourceLocation FakeOperatorLoc =
9314 SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
9315 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9316 E->getAccessorLoc(),
9320 template<typename Derived>
9322 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9323 if (InitListExpr *Syntactic = E->getSyntacticForm())
9326 bool InitChanged = false;
9328 SmallVector<Expr*, 4> Inits;
9329 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9330 Inits, &InitChanged))
9333 if (!getDerived().AlwaysRebuild() && !InitChanged) {
9334 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9335 // in some cases. We can't reuse it in general, because the syntactic and
9336 // semantic forms are linked, and we can't know that semantic form will
9337 // match even if the syntactic form does.
9340 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9341 E->getRBraceLoc(), E->getType());
9344 template<typename Derived>
9346 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9349 // transform the initializer value
9350 ExprResult Init = getDerived().TransformExpr(E->getInit());
9351 if (Init.isInvalid())
9354 // transform the designators.
9355 SmallVector<Expr*, 4> ArrayExprs;
9356 bool ExprChanged = false;
9357 for (const DesignatedInitExpr::Designator &D : E->designators()) {
9358 if (D.isFieldDesignator()) {
9359 Desig.AddDesignator(Designator::getField(D.getFieldName(),
9363 FieldDecl *Field = cast_or_null<FieldDecl>(
9364 getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
9365 if (Field != D.getField())
9366 // Rebuild the expression when the transformed FieldDecl is
9367 // different to the already assigned FieldDecl.
9370 // Ensure that the designator expression is rebuilt when there isn't
9371 // a resolved FieldDecl in the designator as we don't want to assign
9372 // a FieldDecl to a pattern designator that will be instantiated again.
9378 if (D.isArrayDesignator()) {
9379 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
9380 if (Index.isInvalid())
9383 Desig.AddDesignator(
9384 Designator::getArray(Index.get(), D.getLBracketLoc()));
9386 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
9387 ArrayExprs.push_back(Index.get());
9391 assert(D.isArrayRangeDesignator() && "New kind of designator?");
9393 = getDerived().TransformExpr(E->getArrayRangeStart(D));
9394 if (Start.isInvalid())
9397 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
9398 if (End.isInvalid())
9401 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
9404 D.getEllipsisLoc()));
9406 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
9407 End.get() != E->getArrayRangeEnd(D);
9409 ArrayExprs.push_back(Start.get());
9410 ArrayExprs.push_back(End.get());
9413 if (!getDerived().AlwaysRebuild() &&
9414 Init.get() == E->getInit() &&
9418 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
9419 E->getEqualOrColonLoc(),
9420 E->usesGNUSyntax(), Init.get());
9423 // Seems that if TransformInitListExpr() only works on the syntactic form of an
9424 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
9425 template<typename Derived>
9427 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
9428 DesignatedInitUpdateExpr *E) {
9429 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
9434 template<typename Derived>
9436 TreeTransform<Derived>::TransformNoInitExpr(
9438 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
9442 template<typename Derived>
9444 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
9445 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
9449 template<typename Derived>
9451 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
9452 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
9456 template<typename Derived>
9458 TreeTransform<Derived>::TransformImplicitValueInitExpr(
9459 ImplicitValueInitExpr *E) {
9460 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
9462 // FIXME: Will we ever have proper type location here? Will we actually
9463 // need to transform the type?
9464 QualType T = getDerived().TransformType(E->getType());
9468 if (!getDerived().AlwaysRebuild() &&
9472 return getDerived().RebuildImplicitValueInitExpr(T);
9475 template<typename Derived>
9477 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
9478 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
9482 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9483 if (SubExpr.isInvalid())
9486 if (!getDerived().AlwaysRebuild() &&
9487 TInfo == E->getWrittenTypeInfo() &&
9488 SubExpr.get() == E->getSubExpr())
9491 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
9492 TInfo, E->getRParenLoc());
9495 template<typename Derived>
9497 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
9498 bool ArgumentChanged = false;
9499 SmallVector<Expr*, 4> Inits;
9500 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
9504 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
9509 /// \brief Transform an address-of-label expression.
9511 /// By default, the transformation of an address-of-label expression always
9512 /// rebuilds the expression, so that the label identifier can be resolved to
9513 /// the corresponding label statement by semantic analysis.
9514 template<typename Derived>
9516 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
9517 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
9522 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
9523 cast<LabelDecl>(LD));
9526 template<typename Derived>
9528 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
9529 SemaRef.ActOnStartStmtExpr();
9531 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
9532 if (SubStmt.isInvalid()) {
9533 SemaRef.ActOnStmtExprError();
9537 if (!getDerived().AlwaysRebuild() &&
9538 SubStmt.get() == E->getSubStmt()) {
9539 // Calling this an 'error' is unintuitive, but it does the right thing.
9540 SemaRef.ActOnStmtExprError();
9541 return SemaRef.MaybeBindToTemporary(E);
9544 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
9549 template<typename Derived>
9551 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
9552 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9553 if (Cond.isInvalid())
9556 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9557 if (LHS.isInvalid())
9560 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9561 if (RHS.isInvalid())
9564 if (!getDerived().AlwaysRebuild() &&
9565 Cond.get() == E->getCond() &&
9566 LHS.get() == E->getLHS() &&
9567 RHS.get() == E->getRHS())
9570 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
9571 Cond.get(), LHS.get(), RHS.get(),
9575 template<typename Derived>
9577 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
9581 template<typename Derived>
9583 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9584 switch (E->getOperator()) {
9588 case OO_Array_Delete:
9589 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
9592 // This is a call to an object's operator().
9593 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
9595 // Transform the object itself.
9596 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
9597 if (Object.isInvalid())
9600 // FIXME: Poor location information
9601 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
9602 static_cast<Expr *>(Object.get())->getLocEnd());
9604 // Transform the call arguments.
9605 SmallVector<Expr*, 8> Args;
9606 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
9610 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
9615 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9617 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
9618 #include "clang/Basic/OperatorKinds.def"
9623 case OO_Conditional:
9624 llvm_unreachable("conditional operator is not actually overloadable");
9627 case NUM_OVERLOADED_OPERATORS:
9628 llvm_unreachable("not an overloaded operator?");
9631 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9632 if (Callee.isInvalid())
9636 if (E->getOperator() == OO_Amp)
9637 First = getDerived().TransformAddressOfOperand(E->getArg(0));
9639 First = getDerived().TransformExpr(E->getArg(0));
9640 if (First.isInvalid())
9644 if (E->getNumArgs() == 2) {
9645 Second = getDerived().TransformExpr(E->getArg(1));
9646 if (Second.isInvalid())
9650 if (!getDerived().AlwaysRebuild() &&
9651 Callee.get() == E->getCallee() &&
9652 First.get() == E->getArg(0) &&
9653 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
9654 return SemaRef.MaybeBindToTemporary(E);
9656 Sema::FPContractStateRAII FPContractState(getSema());
9657 getSema().FPFeatures = E->getFPFeatures();
9659 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
9660 E->getOperatorLoc(),
9666 template<typename Derived>
9668 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
9669 return getDerived().TransformCallExpr(E);
9672 template<typename Derived>
9674 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
9675 // Transform the callee.
9676 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9677 if (Callee.isInvalid())
9680 // Transform exec config.
9681 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
9685 // Transform arguments.
9686 bool ArgChanged = false;
9687 SmallVector<Expr*, 8> Args;
9688 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9692 if (!getDerived().AlwaysRebuild() &&
9693 Callee.get() == E->getCallee() &&
9695 return SemaRef.MaybeBindToTemporary(E);
9697 // FIXME: Wrong source location information for the '('.
9698 SourceLocation FakeLParenLoc
9699 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9700 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9702 E->getRParenLoc(), EC.get());
9705 template<typename Derived>
9707 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
9708 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9713 = getDerived().TransformExpr(E->getSubExprAsWritten());
9714 if (SubExpr.isInvalid())
9717 if (!getDerived().AlwaysRebuild() &&
9718 Type == E->getTypeInfoAsWritten() &&
9719 SubExpr.get() == E->getSubExpr())
9721 return getDerived().RebuildCXXNamedCastExpr(
9722 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
9723 Type, E->getAngleBrackets().getEnd(),
9724 // FIXME. this should be '(' location
9725 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
9728 template<typename Derived>
9730 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
9731 return getDerived().TransformCXXNamedCastExpr(E);
9734 template<typename Derived>
9736 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
9737 return getDerived().TransformCXXNamedCastExpr(E);
9740 template<typename Derived>
9742 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
9743 CXXReinterpretCastExpr *E) {
9744 return getDerived().TransformCXXNamedCastExpr(E);
9747 template<typename Derived>
9749 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
9750 return getDerived().TransformCXXNamedCastExpr(E);
9753 template<typename Derived>
9755 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
9756 CXXFunctionalCastExpr *E) {
9757 TypeSourceInfo *Type =
9758 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
9763 = getDerived().TransformExpr(E->getSubExprAsWritten());
9764 if (SubExpr.isInvalid())
9767 if (!getDerived().AlwaysRebuild() &&
9768 Type == E->getTypeInfoAsWritten() &&
9769 SubExpr.get() == E->getSubExpr())
9772 return getDerived().RebuildCXXFunctionalCastExpr(Type,
9778 template<typename Derived>
9780 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
9781 if (E->isTypeOperand()) {
9782 TypeSourceInfo *TInfo
9783 = getDerived().TransformType(E->getTypeOperandSourceInfo());
9787 if (!getDerived().AlwaysRebuild() &&
9788 TInfo == E->getTypeOperandSourceInfo())
9791 return getDerived().RebuildCXXTypeidExpr(E->getType(),
9797 // We don't know whether the subexpression is potentially evaluated until
9798 // after we perform semantic analysis. We speculatively assume it is
9799 // unevaluated; it will get fixed later if the subexpression is in fact
9800 // potentially evaluated.
9801 EnterExpressionEvaluationContext Unevaluated(
9802 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9803 Sema::ReuseLambdaContextDecl);
9805 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
9806 if (SubExpr.isInvalid())
9809 if (!getDerived().AlwaysRebuild() &&
9810 SubExpr.get() == E->getExprOperand())
9813 return getDerived().RebuildCXXTypeidExpr(E->getType(),
9819 template<typename Derived>
9821 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
9822 if (E->isTypeOperand()) {
9823 TypeSourceInfo *TInfo
9824 = getDerived().TransformType(E->getTypeOperandSourceInfo());
9828 if (!getDerived().AlwaysRebuild() &&
9829 TInfo == E->getTypeOperandSourceInfo())
9832 return getDerived().RebuildCXXUuidofExpr(E->getType(),
9838 EnterExpressionEvaluationContext Unevaluated(
9839 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
9841 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
9842 if (SubExpr.isInvalid())
9845 if (!getDerived().AlwaysRebuild() &&
9846 SubExpr.get() == E->getExprOperand())
9849 return getDerived().RebuildCXXUuidofExpr(E->getType(),
9855 template<typename Derived>
9857 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
9861 template<typename Derived>
9863 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
9864 CXXNullPtrLiteralExpr *E) {
9868 template<typename Derived>
9870 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
9871 QualType T = getSema().getCurrentThisType();
9873 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
9874 // Make sure that we capture 'this'.
9875 getSema().CheckCXXThisCapture(E->getLocStart());
9879 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
9882 template<typename Derived>
9884 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
9885 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9886 if (SubExpr.isInvalid())
9889 if (!getDerived().AlwaysRebuild() &&
9890 SubExpr.get() == E->getSubExpr())
9893 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
9894 E->isThrownVariableInScope());
9897 template<typename Derived>
9899 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9901 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
9906 if (!getDerived().AlwaysRebuild() &&
9907 Param == E->getParam())
9910 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
9913 template<typename Derived>
9915 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
9917 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
9922 if (!getDerived().AlwaysRebuild() && Field == E->getField())
9925 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
9928 template<typename Derived>
9930 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
9931 CXXScalarValueInitExpr *E) {
9932 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9936 if (!getDerived().AlwaysRebuild() &&
9937 T == E->getTypeSourceInfo())
9940 return getDerived().RebuildCXXScalarValueInitExpr(T,
9941 /*FIXME:*/T->getTypeLoc().getEndLoc(),
9945 template<typename Derived>
9947 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
9948 // Transform the type that we're allocating
9949 TypeSourceInfo *AllocTypeInfo =
9950 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
9954 // Transform the size of the array we're allocating (if any).
9955 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
9956 if (ArraySize.isInvalid())
9959 // Transform the placement arguments (if any).
9960 bool ArgumentChanged = false;
9961 SmallVector<Expr*, 8> PlacementArgs;
9962 if (getDerived().TransformExprs(E->getPlacementArgs(),
9963 E->getNumPlacementArgs(), true,
9964 PlacementArgs, &ArgumentChanged))
9967 // Transform the initializer (if any).
9968 Expr *OldInit = E->getInitializer();
9971 NewInit = getDerived().TransformInitializer(OldInit, true);
9972 if (NewInit.isInvalid())
9975 // Transform new operator and delete operator.
9976 FunctionDecl *OperatorNew = nullptr;
9977 if (E->getOperatorNew()) {
9978 OperatorNew = cast_or_null<FunctionDecl>(
9979 getDerived().TransformDecl(E->getLocStart(),
9980 E->getOperatorNew()));
9985 FunctionDecl *OperatorDelete = nullptr;
9986 if (E->getOperatorDelete()) {
9987 OperatorDelete = cast_or_null<FunctionDecl>(
9988 getDerived().TransformDecl(E->getLocStart(),
9989 E->getOperatorDelete()));
9990 if (!OperatorDelete)
9994 if (!getDerived().AlwaysRebuild() &&
9995 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
9996 ArraySize.get() == E->getArraySize() &&
9997 NewInit.get() == OldInit &&
9998 OperatorNew == E->getOperatorNew() &&
9999 OperatorDelete == E->getOperatorDelete() &&
10000 !ArgumentChanged) {
10001 // Mark any declarations we need as referenced.
10002 // FIXME: instantiation-specific.
10004 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
10005 if (OperatorDelete)
10006 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
10008 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10009 QualType ElementType
10010 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10011 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10012 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10013 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10014 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
10022 QualType AllocType = AllocTypeInfo->getType();
10023 if (!ArraySize.get()) {
10024 // If no array size was specified, but the new expression was
10025 // instantiated with an array type (e.g., "new T" where T is
10026 // instantiated with "int[4]"), extract the outer bound from the
10027 // array type as our array size. We do this with constant and
10028 // dependently-sized array types.
10029 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10032 } else if (const ConstantArrayType *ConsArrayT
10033 = dyn_cast<ConstantArrayType>(ArrayT)) {
10034 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10035 SemaRef.Context.getSizeType(),
10036 /*FIXME:*/ E->getLocStart());
10037 AllocType = ConsArrayT->getElementType();
10038 } else if (const DependentSizedArrayType *DepArrayT
10039 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10040 if (DepArrayT->getSizeExpr()) {
10041 ArraySize = DepArrayT->getSizeExpr();
10042 AllocType = DepArrayT->getElementType();
10047 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
10049 /*FIXME:*/E->getLocStart(),
10051 /*FIXME:*/E->getLocStart(),
10052 E->getTypeIdParens(),
10056 E->getDirectInitRange(),
10060 template<typename Derived>
10062 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10063 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10064 if (Operand.isInvalid())
10065 return ExprError();
10067 // Transform the delete operator, if known.
10068 FunctionDecl *OperatorDelete = nullptr;
10069 if (E->getOperatorDelete()) {
10070 OperatorDelete = cast_or_null<FunctionDecl>(
10071 getDerived().TransformDecl(E->getLocStart(),
10072 E->getOperatorDelete()));
10073 if (!OperatorDelete)
10074 return ExprError();
10077 if (!getDerived().AlwaysRebuild() &&
10078 Operand.get() == E->getArgument() &&
10079 OperatorDelete == E->getOperatorDelete()) {
10080 // Mark any declarations we need as referenced.
10081 // FIXME: instantiation-specific.
10082 if (OperatorDelete)
10083 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
10085 if (!E->getArgument()->isTypeDependent()) {
10086 QualType Destroyed = SemaRef.Context.getBaseElementType(
10087 E->getDestroyedType());
10088 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10089 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10090 SemaRef.MarkFunctionReferenced(E->getLocStart(),
10091 SemaRef.LookupDestructor(Record));
10098 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
10099 E->isGlobalDelete(),
10104 template<typename Derived>
10106 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10107 CXXPseudoDestructorExpr *E) {
10108 ExprResult Base = getDerived().TransformExpr(E->getBase());
10109 if (Base.isInvalid())
10110 return ExprError();
10112 ParsedType ObjectTypePtr;
10113 bool MayBePseudoDestructor = false;
10114 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10115 E->getOperatorLoc(),
10116 E->isArrow()? tok::arrow : tok::period,
10118 MayBePseudoDestructor);
10119 if (Base.isInvalid())
10120 return ExprError();
10122 QualType ObjectType = ObjectTypePtr.get();
10123 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10124 if (QualifierLoc) {
10126 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10128 return ExprError();
10131 SS.Adopt(QualifierLoc);
10133 PseudoDestructorTypeStorage Destroyed;
10134 if (E->getDestroyedTypeInfo()) {
10135 TypeSourceInfo *DestroyedTypeInfo
10136 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10137 ObjectType, nullptr, SS);
10138 if (!DestroyedTypeInfo)
10139 return ExprError();
10140 Destroyed = DestroyedTypeInfo;
10141 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10142 // We aren't likely to be able to resolve the identifier down to a type
10143 // now anyway, so just retain the identifier.
10144 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10145 E->getDestroyedTypeLoc());
10147 // Look for a destructor known with the given name.
10148 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10149 *E->getDestroyedTypeIdentifier(),
10150 E->getDestroyedTypeLoc(),
10155 return ExprError();
10158 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10159 E->getDestroyedTypeLoc());
10162 TypeSourceInfo *ScopeTypeInfo = nullptr;
10163 if (E->getScopeTypeInfo()) {
10164 CXXScopeSpec EmptySS;
10165 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10166 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10167 if (!ScopeTypeInfo)
10168 return ExprError();
10171 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10172 E->getOperatorLoc(),
10176 E->getColonColonLoc(),
10181 template <typename Derived>
10182 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10185 // Transform all the decls.
10186 bool AllEmptyPacks = true;
10187 for (auto *OldD : Old->decls()) {
10188 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10190 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10191 // This can happen because of dependent hiding.
10192 if (isa<UsingShadowDecl>(OldD))
10200 // Expand using pack declarations.
10201 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10202 ArrayRef<NamedDecl*> Decls = SingleDecl;
10203 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10204 Decls = UPD->expansions();
10206 // Expand using declarations.
10207 for (auto *D : Decls) {
10208 if (auto *UD = dyn_cast<UsingDecl>(D)) {
10209 for (auto *SD : UD->shadows())
10216 AllEmptyPacks &= Decls.empty();
10219 // C++ [temp.res]/8.4.2:
10220 // The program is ill-formed, no diagnostic required, if [...] lookup for
10221 // a name in the template definition found a using-declaration, but the
10222 // lookup in the corresponding scope in the instantiation odoes not find
10223 // any declarations because the using-declaration was a pack expansion and
10224 // the corresponding pack is empty
10225 if (AllEmptyPacks && !RequiresADL) {
10226 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10227 << isa<UnresolvedMemberExpr>(Old) << Old->getNameInfo().getName();
10231 // Resolve a kind, but don't do any further analysis. If it's
10232 // ambiguous, the callee needs to deal with it.
10237 template<typename Derived>
10239 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10240 UnresolvedLookupExpr *Old) {
10241 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10242 Sema::LookupOrdinaryName);
10244 // Transform the declaration set.
10245 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10246 return ExprError();
10248 // Rebuild the nested-name qualifier, if present.
10250 if (Old->getQualifierLoc()) {
10251 NestedNameSpecifierLoc QualifierLoc
10252 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10254 return ExprError();
10256 SS.Adopt(QualifierLoc);
10259 if (Old->getNamingClass()) {
10260 CXXRecordDecl *NamingClass
10261 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10263 Old->getNamingClass()));
10264 if (!NamingClass) {
10266 return ExprError();
10269 R.setNamingClass(NamingClass);
10272 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10274 // If we have neither explicit template arguments, nor the template keyword,
10275 // it's a normal declaration name or member reference.
10276 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10277 NamedDecl *D = R.getAsSingle<NamedDecl>();
10278 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10279 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10280 // give a good diagnostic.
10281 if (D && D->isCXXInstanceMember()) {
10282 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10283 /*TemplateArgs=*/nullptr,
10284 /*Scope=*/nullptr);
10287 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10290 // If we have template arguments, rebuild them, then rebuild the
10291 // templateid expression.
10292 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10293 if (Old->hasExplicitTemplateArgs() &&
10294 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10295 Old->getNumTemplateArgs(),
10298 return ExprError();
10301 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10302 Old->requiresADL(), &TransArgs);
10305 template<typename Derived>
10307 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10308 bool ArgChanged = false;
10309 SmallVector<TypeSourceInfo *, 4> Args;
10310 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10311 TypeSourceInfo *From = E->getArg(I);
10312 TypeLoc FromTL = From->getTypeLoc();
10313 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10314 TypeLocBuilder TLB;
10315 TLB.reserve(FromTL.getFullDataSize());
10316 QualType To = getDerived().TransformType(TLB, FromTL);
10318 return ExprError();
10320 if (To == From->getType())
10321 Args.push_back(From);
10323 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10331 // We have a pack expansion. Instantiate it.
10332 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10333 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10334 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10335 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
10337 // Determine whether the set of unexpanded parameter packs can and should
10339 bool Expand = true;
10340 bool RetainExpansion = false;
10341 Optional<unsigned> OrigNumExpansions =
10342 ExpansionTL.getTypePtr()->getNumExpansions();
10343 Optional<unsigned> NumExpansions = OrigNumExpansions;
10344 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
10345 PatternTL.getSourceRange(),
10347 Expand, RetainExpansion,
10349 return ExprError();
10352 // The transform has determined that we should perform a simple
10353 // transformation on the pack expansion, producing another pack
10355 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10357 TypeLocBuilder TLB;
10358 TLB.reserve(From->getTypeLoc().getFullDataSize());
10360 QualType To = getDerived().TransformType(TLB, PatternTL);
10362 return ExprError();
10364 To = getDerived().RebuildPackExpansionType(To,
10365 PatternTL.getSourceRange(),
10366 ExpansionTL.getEllipsisLoc(),
10369 return ExprError();
10371 PackExpansionTypeLoc ToExpansionTL
10372 = TLB.push<PackExpansionTypeLoc>(To);
10373 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10374 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10378 // Expand the pack expansion by substituting for each argument in the
10380 for (unsigned I = 0; I != *NumExpansions; ++I) {
10381 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
10382 TypeLocBuilder TLB;
10383 TLB.reserve(PatternTL.getFullDataSize());
10384 QualType To = getDerived().TransformType(TLB, PatternTL);
10386 return ExprError();
10388 if (To->containsUnexpandedParameterPack()) {
10389 To = getDerived().RebuildPackExpansionType(To,
10390 PatternTL.getSourceRange(),
10391 ExpansionTL.getEllipsisLoc(),
10394 return ExprError();
10396 PackExpansionTypeLoc ToExpansionTL
10397 = TLB.push<PackExpansionTypeLoc>(To);
10398 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10401 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10404 if (!RetainExpansion)
10407 // If we're supposed to retain a pack expansion, do so by temporarily
10408 // forgetting the partially-substituted parameter pack.
10409 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10411 TypeLocBuilder TLB;
10412 TLB.reserve(From->getTypeLoc().getFullDataSize());
10414 QualType To = getDerived().TransformType(TLB, PatternTL);
10416 return ExprError();
10418 To = getDerived().RebuildPackExpansionType(To,
10419 PatternTL.getSourceRange(),
10420 ExpansionTL.getEllipsisLoc(),
10423 return ExprError();
10425 PackExpansionTypeLoc ToExpansionTL
10426 = TLB.push<PackExpansionTypeLoc>(To);
10427 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10428 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10431 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10434 return getDerived().RebuildTypeTrait(E->getTrait(),
10440 template<typename Derived>
10442 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
10443 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
10445 return ExprError();
10447 if (!getDerived().AlwaysRebuild() &&
10448 T == E->getQueriedTypeSourceInfo())
10451 ExprResult SubExpr;
10453 EnterExpressionEvaluationContext Unevaluated(
10454 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10455 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
10456 if (SubExpr.isInvalid())
10457 return ExprError();
10459 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
10463 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
10470 template<typename Derived>
10472 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
10473 ExprResult SubExpr;
10475 EnterExpressionEvaluationContext Unevaluated(
10476 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10477 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
10478 if (SubExpr.isInvalid())
10479 return ExprError();
10481 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
10485 return getDerived().RebuildExpressionTrait(
10486 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
10489 template <typename Derived>
10490 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
10491 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
10492 TypeSourceInfo **RecoveryTSI) {
10493 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
10494 DRE, AddrTaken, RecoveryTSI);
10496 // Propagate both errors and recovered types, which return ExprEmpty.
10497 if (!NewDRE.isUsable())
10500 // We got an expr, wrap it up in parens.
10501 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
10503 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
10507 template <typename Derived>
10508 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10509 DependentScopeDeclRefExpr *E) {
10510 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
10514 template<typename Derived>
10516 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10517 DependentScopeDeclRefExpr *E,
10518 bool IsAddressOfOperand,
10519 TypeSourceInfo **RecoveryTSI) {
10520 assert(E->getQualifierLoc());
10521 NestedNameSpecifierLoc QualifierLoc
10522 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10524 return ExprError();
10525 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10527 // TODO: If this is a conversion-function-id, verify that the
10528 // destination type name (if present) resolves the same way after
10529 // instantiation as it did in the local scope.
10531 DeclarationNameInfo NameInfo
10532 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
10533 if (!NameInfo.getName())
10534 return ExprError();
10536 if (!E->hasExplicitTemplateArgs()) {
10537 if (!getDerived().AlwaysRebuild() &&
10538 QualifierLoc == E->getQualifierLoc() &&
10539 // Note: it is sufficient to compare the Name component of NameInfo:
10540 // if name has not changed, DNLoc has not changed either.
10541 NameInfo.getName() == E->getDeclName())
10544 return getDerived().RebuildDependentScopeDeclRefExpr(
10545 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
10546 IsAddressOfOperand, RecoveryTSI);
10549 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
10550 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10551 E->getNumTemplateArgs(),
10553 return ExprError();
10555 return getDerived().RebuildDependentScopeDeclRefExpr(
10556 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
10560 template<typename Derived>
10562 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
10563 // CXXConstructExprs other than for list-initialization and
10564 // CXXTemporaryObjectExpr are always implicit, so when we have
10565 // a 1-argument construction we just transform that argument.
10566 if ((E->getNumArgs() == 1 ||
10567 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
10568 (!getDerived().DropCallArgument(E->getArg(0))) &&
10569 !E->isListInitialization())
10570 return getDerived().TransformExpr(E->getArg(0));
10572 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
10574 QualType T = getDerived().TransformType(E->getType());
10576 return ExprError();
10578 CXXConstructorDecl *Constructor
10579 = cast_or_null<CXXConstructorDecl>(
10580 getDerived().TransformDecl(E->getLocStart(),
10581 E->getConstructor()));
10583 return ExprError();
10585 bool ArgumentChanged = false;
10586 SmallVector<Expr*, 8> Args;
10587 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10589 return ExprError();
10591 if (!getDerived().AlwaysRebuild() &&
10592 T == E->getType() &&
10593 Constructor == E->getConstructor() &&
10594 !ArgumentChanged) {
10595 // Mark the constructor as referenced.
10596 // FIXME: Instantiation-specific
10597 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10601 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
10603 E->isElidable(), Args,
10604 E->hadMultipleCandidates(),
10605 E->isListInitialization(),
10606 E->isStdInitListInitialization(),
10607 E->requiresZeroInitialization(),
10608 E->getConstructionKind(),
10609 E->getParenOrBraceRange());
10612 template<typename Derived>
10613 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
10614 CXXInheritedCtorInitExpr *E) {
10615 QualType T = getDerived().TransformType(E->getType());
10617 return ExprError();
10619 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
10620 getDerived().TransformDecl(E->getLocStart(), E->getConstructor()));
10622 return ExprError();
10624 if (!getDerived().AlwaysRebuild() &&
10625 T == E->getType() &&
10626 Constructor == E->getConstructor()) {
10627 // Mark the constructor as referenced.
10628 // FIXME: Instantiation-specific
10629 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10633 return getDerived().RebuildCXXInheritedCtorInitExpr(
10634 T, E->getLocation(), Constructor,
10635 E->constructsVBase(), E->inheritedFromVBase());
10638 /// \brief Transform a C++ temporary-binding expression.
10640 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
10641 /// transform the subexpression and return that.
10642 template<typename Derived>
10644 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10645 return getDerived().TransformExpr(E->getSubExpr());
10648 /// \brief Transform a C++ expression that contains cleanups that should
10649 /// be run after the expression is evaluated.
10651 /// Since ExprWithCleanups nodes are implicitly generated, we
10652 /// just transform the subexpression and return that.
10653 template<typename Derived>
10655 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
10656 return getDerived().TransformExpr(E->getSubExpr());
10659 template<typename Derived>
10661 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
10662 CXXTemporaryObjectExpr *E) {
10663 TypeSourceInfo *T =
10664 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
10666 return ExprError();
10668 CXXConstructorDecl *Constructor
10669 = cast_or_null<CXXConstructorDecl>(
10670 getDerived().TransformDecl(E->getLocStart(),
10671 E->getConstructor()));
10673 return ExprError();
10675 bool ArgumentChanged = false;
10676 SmallVector<Expr*, 8> Args;
10677 Args.reserve(E->getNumArgs());
10678 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10680 return ExprError();
10682 if (!getDerived().AlwaysRebuild() &&
10683 T == E->getTypeSourceInfo() &&
10684 Constructor == E->getConstructor() &&
10685 !ArgumentChanged) {
10686 // FIXME: Instantiation-specific
10687 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10688 return SemaRef.MaybeBindToTemporary(E);
10691 // FIXME: Pass in E->isListInitialization().
10692 return getDerived().RebuildCXXTemporaryObjectExpr(T,
10693 /*FIXME:*/T->getTypeLoc().getEndLoc(),
10698 template<typename Derived>
10700 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
10701 // Transform any init-capture expressions before entering the scope of the
10702 // lambda body, because they are not semantically within that scope.
10703 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
10704 SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
10705 InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
10706 E->explicit_capture_begin());
10707 for (LambdaExpr::capture_iterator C = E->capture_begin(),
10708 CEnd = E->capture_end();
10710 if (!E->isInitCapture(C))
10712 EnterExpressionEvaluationContext EEEC(
10713 getSema(), Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
10714 ExprResult NewExprInitResult = getDerived().TransformInitializer(
10715 C->getCapturedVar()->getInit(),
10716 C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
10718 if (NewExprInitResult.isInvalid())
10719 return ExprError();
10720 Expr *NewExprInit = NewExprInitResult.get();
10722 VarDecl *OldVD = C->getCapturedVar();
10723 QualType NewInitCaptureType =
10724 getSema().buildLambdaInitCaptureInitialization(
10725 C->getLocation(), OldVD->getType()->isReferenceType(),
10726 OldVD->getIdentifier(),
10727 C->getCapturedVar()->getInitStyle() != VarDecl::CInit, NewExprInit);
10728 NewExprInitResult = NewExprInit;
10729 InitCaptureExprsAndTypes[C - E->capture_begin()] =
10730 std::make_pair(NewExprInitResult, NewInitCaptureType);
10733 // Transform the template parameters, and add them to the current
10734 // instantiation scope. The null case is handled correctly.
10735 auto TPL = getDerived().TransformTemplateParameterList(
10736 E->getTemplateParameterList());
10738 // Transform the type of the original lambda's call operator.
10739 // The transformation MUST be done in the CurrentInstantiationScope since
10740 // it introduces a mapping of the original to the newly created
10741 // transformed parameters.
10742 TypeSourceInfo *NewCallOpTSI = nullptr;
10744 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
10745 FunctionProtoTypeLoc OldCallOpFPTL =
10746 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
10748 TypeLocBuilder NewCallOpTLBuilder;
10749 SmallVector<QualType, 4> ExceptionStorage;
10750 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
10751 QualType NewCallOpType = TransformFunctionProtoType(
10752 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
10753 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
10754 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
10755 ExceptionStorage, Changed);
10757 if (NewCallOpType.isNull())
10758 return ExprError();
10759 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
10763 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
10764 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
10765 LSI->GLTemplateParameterList = TPL;
10767 // Create the local class that will describe the lambda.
10768 CXXRecordDecl *Class
10769 = getSema().createLambdaClosureType(E->getIntroducerRange(),
10771 /*KnownDependent=*/false,
10772 E->getCaptureDefault());
10773 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
10775 // Build the call operator.
10776 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
10777 Class, E->getIntroducerRange(), NewCallOpTSI,
10778 E->getCallOperator()->getLocEnd(),
10779 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
10780 E->getCallOperator()->isConstexpr());
10782 LSI->CallOperator = NewCallOperator;
10784 for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
10785 I != NumParams; ++I) {
10786 auto *P = NewCallOperator->getParamDecl(I);
10787 if (P->hasUninstantiatedDefaultArg()) {
10788 EnterExpressionEvaluationContext Eval(
10790 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
10791 ExprResult R = getDerived().TransformExpr(
10792 E->getCallOperator()->getParamDecl(I)->getDefaultArg());
10793 P->setDefaultArg(R.get());
10797 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
10798 getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
10800 // Introduce the context of the call operator.
10801 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
10802 /*NewThisContext*/false);
10804 // Enter the scope of the lambda.
10805 getSema().buildLambdaScope(LSI, NewCallOperator,
10806 E->getIntroducerRange(),
10807 E->getCaptureDefault(),
10808 E->getCaptureDefaultLoc(),
10809 E->hasExplicitParameters(),
10810 E->hasExplicitResultType(),
10813 bool Invalid = false;
10815 // Transform captures.
10816 bool FinishedExplicitCaptures = false;
10817 for (LambdaExpr::capture_iterator C = E->capture_begin(),
10818 CEnd = E->capture_end();
10820 // When we hit the first implicit capture, tell Sema that we've finished
10821 // the list of explicit captures.
10822 if (!FinishedExplicitCaptures && C->isImplicit()) {
10823 getSema().finishLambdaExplicitCaptures(LSI);
10824 FinishedExplicitCaptures = true;
10827 // Capturing 'this' is trivial.
10828 if (C->capturesThis()) {
10829 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
10830 /*BuildAndDiagnose*/ true, nullptr,
10831 C->getCaptureKind() == LCK_StarThis);
10834 // Captured expression will be recaptured during captured variables
10836 if (C->capturesVLAType())
10839 // Rebuild init-captures, including the implied field declaration.
10840 if (E->isInitCapture(C)) {
10841 InitCaptureInfoTy InitExprTypePair =
10842 InitCaptureExprsAndTypes[C - E->capture_begin()];
10843 ExprResult Init = InitExprTypePair.first;
10844 QualType InitQualType = InitExprTypePair.second;
10845 if (Init.isInvalid() || InitQualType.isNull()) {
10849 VarDecl *OldVD = C->getCapturedVar();
10850 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
10851 OldVD->getLocation(), InitExprTypePair.second, OldVD->getIdentifier(),
10852 OldVD->getInitStyle(), Init.get());
10856 getDerived().transformedLocalDecl(OldVD, NewVD);
10858 getSema().buildInitCaptureField(LSI, NewVD);
10862 assert(C->capturesVariable() && "unexpected kind of lambda capture");
10864 // Determine the capture kind for Sema.
10865 Sema::TryCaptureKind Kind
10866 = C->isImplicit()? Sema::TryCapture_Implicit
10867 : C->getCaptureKind() == LCK_ByCopy
10868 ? Sema::TryCapture_ExplicitByVal
10869 : Sema::TryCapture_ExplicitByRef;
10870 SourceLocation EllipsisLoc;
10871 if (C->isPackExpansion()) {
10872 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
10873 bool ShouldExpand = false;
10874 bool RetainExpansion = false;
10875 Optional<unsigned> NumExpansions;
10876 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
10879 ShouldExpand, RetainExpansion,
10885 if (ShouldExpand) {
10886 // The transform has determined that we should perform an expansion;
10887 // transform and capture each of the arguments.
10888 // expansion of the pattern. Do so.
10889 VarDecl *Pack = C->getCapturedVar();
10890 for (unsigned I = 0; I != *NumExpansions; ++I) {
10891 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
10892 VarDecl *CapturedVar
10893 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
10895 if (!CapturedVar) {
10900 // Capture the transformed variable.
10901 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
10904 // FIXME: Retain a pack expansion if RetainExpansion is true.
10909 EllipsisLoc = C->getEllipsisLoc();
10912 // Transform the captured variable.
10913 VarDecl *CapturedVar
10914 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
10915 C->getCapturedVar()));
10916 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
10921 // Capture the transformed variable.
10922 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
10925 if (!FinishedExplicitCaptures)
10926 getSema().finishLambdaExplicitCaptures(LSI);
10928 // Enter a new evaluation context to insulate the lambda from any
10929 // cleanups from the enclosing full-expression.
10930 getSema().PushExpressionEvaluationContext(
10931 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
10933 // Instantiate the body of the lambda expression.
10935 Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
10937 // ActOnLambda* will pop the function scope for us.
10938 FuncScopeCleanup.disable();
10940 if (Body.isInvalid()) {
10941 SavedContext.pop();
10942 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
10943 /*IsInstantiation=*/true);
10944 return ExprError();
10947 // Copy the LSI before ActOnFinishFunctionBody removes it.
10948 // FIXME: This is dumb. Store the lambda information somewhere that outlives
10949 // the call operator.
10950 auto LSICopy = *LSI;
10951 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
10952 /*IsInstantiation*/ true);
10953 SavedContext.pop();
10955 return getSema().BuildLambdaExpr(E->getLocStart(), Body.get()->getLocEnd(),
10959 template<typename Derived>
10961 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
10962 CXXUnresolvedConstructExpr *E) {
10963 TypeSourceInfo *T =
10964 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
10966 return ExprError();
10968 bool ArgumentChanged = false;
10969 SmallVector<Expr*, 8> Args;
10970 Args.reserve(E->arg_size());
10971 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
10973 return ExprError();
10975 if (!getDerived().AlwaysRebuild() &&
10976 T == E->getTypeSourceInfo() &&
10980 // FIXME: we're faking the locations of the commas
10981 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
10984 E->getRParenLoc());
10987 template<typename Derived>
10989 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
10990 CXXDependentScopeMemberExpr *E) {
10991 // Transform the base of the expression.
10992 ExprResult Base((Expr*) nullptr);
10995 QualType ObjectType;
10996 if (!E->isImplicitAccess()) {
10997 OldBase = E->getBase();
10998 Base = getDerived().TransformExpr(OldBase);
10999 if (Base.isInvalid())
11000 return ExprError();
11002 // Start the member reference and compute the object's type.
11003 ParsedType ObjectTy;
11004 bool MayBePseudoDestructor = false;
11005 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11006 E->getOperatorLoc(),
11007 E->isArrow()? tok::arrow : tok::period,
11009 MayBePseudoDestructor);
11010 if (Base.isInvalid())
11011 return ExprError();
11013 ObjectType = ObjectTy.get();
11014 BaseType = ((Expr*) Base.get())->getType();
11017 BaseType = getDerived().TransformType(E->getBaseType());
11018 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
11021 // Transform the first part of the nested-name-specifier that qualifies
11022 // the member name.
11023 NamedDecl *FirstQualifierInScope
11024 = getDerived().TransformFirstQualifierInScope(
11025 E->getFirstQualifierFoundInScope(),
11026 E->getQualifierLoc().getBeginLoc());
11028 NestedNameSpecifierLoc QualifierLoc;
11029 if (E->getQualifier()) {
11031 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11033 FirstQualifierInScope);
11035 return ExprError();
11038 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11040 // TODO: If this is a conversion-function-id, verify that the
11041 // destination type name (if present) resolves the same way after
11042 // instantiation as it did in the local scope.
11044 DeclarationNameInfo NameInfo
11045 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11046 if (!NameInfo.getName())
11047 return ExprError();
11049 if (!E->hasExplicitTemplateArgs()) {
11050 // This is a reference to a member without an explicitly-specified
11051 // template argument list. Optimize for this common case.
11052 if (!getDerived().AlwaysRebuild() &&
11053 Base.get() == OldBase &&
11054 BaseType == E->getBaseType() &&
11055 QualifierLoc == E->getQualifierLoc() &&
11056 NameInfo.getName() == E->getMember() &&
11057 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11060 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11063 E->getOperatorLoc(),
11066 FirstQualifierInScope,
11068 /*TemplateArgs*/nullptr);
11071 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11072 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11073 E->getNumTemplateArgs(),
11075 return ExprError();
11077 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11080 E->getOperatorLoc(),
11083 FirstQualifierInScope,
11088 template<typename Derived>
11090 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11091 // Transform the base of the expression.
11092 ExprResult Base((Expr*) nullptr);
11094 if (!Old->isImplicitAccess()) {
11095 Base = getDerived().TransformExpr(Old->getBase());
11096 if (Base.isInvalid())
11097 return ExprError();
11098 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11100 if (Base.isInvalid())
11101 return ExprError();
11102 BaseType = Base.get()->getType();
11104 BaseType = getDerived().TransformType(Old->getBaseType());
11107 NestedNameSpecifierLoc QualifierLoc;
11108 if (Old->getQualifierLoc()) {
11110 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11112 return ExprError();
11115 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11117 LookupResult R(SemaRef, Old->getMemberNameInfo(),
11118 Sema::LookupOrdinaryName);
11120 // Transform the declaration set.
11121 if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11122 return ExprError();
11124 // Determine the naming class.
11125 if (Old->getNamingClass()) {
11126 CXXRecordDecl *NamingClass
11127 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11128 Old->getMemberLoc(),
11129 Old->getNamingClass()));
11131 return ExprError();
11133 R.setNamingClass(NamingClass);
11136 TemplateArgumentListInfo TransArgs;
11137 if (Old->hasExplicitTemplateArgs()) {
11138 TransArgs.setLAngleLoc(Old->getLAngleLoc());
11139 TransArgs.setRAngleLoc(Old->getRAngleLoc());
11140 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11141 Old->getNumTemplateArgs(),
11143 return ExprError();
11146 // FIXME: to do this check properly, we will need to preserve the
11147 // first-qualifier-in-scope here, just in case we had a dependent
11148 // base (and therefore couldn't do the check) and a
11149 // nested-name-qualifier (and therefore could do the lookup).
11150 NamedDecl *FirstQualifierInScope = nullptr;
11152 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11154 Old->getOperatorLoc(),
11158 FirstQualifierInScope,
11160 (Old->hasExplicitTemplateArgs()
11161 ? &TransArgs : nullptr));
11164 template<typename Derived>
11166 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11167 EnterExpressionEvaluationContext Unevaluated(
11168 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11169 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11170 if (SubExpr.isInvalid())
11171 return ExprError();
11173 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11176 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11179 template<typename Derived>
11181 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11182 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11183 if (Pattern.isInvalid())
11184 return ExprError();
11186 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11189 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11190 E->getNumExpansions());
11193 template<typename Derived>
11195 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11196 // If E is not value-dependent, then nothing will change when we transform it.
11197 // Note: This is an instantiation-centric view.
11198 if (!E->isValueDependent())
11201 EnterExpressionEvaluationContext Unevaluated(
11202 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11204 ArrayRef<TemplateArgument> PackArgs;
11205 TemplateArgument ArgStorage;
11207 // Find the argument list to transform.
11208 if (E->isPartiallySubstituted()) {
11209 PackArgs = E->getPartialArguments();
11210 } else if (E->isValueDependent()) {
11211 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
11212 bool ShouldExpand = false;
11213 bool RetainExpansion = false;
11214 Optional<unsigned> NumExpansions;
11215 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
11217 ShouldExpand, RetainExpansion,
11219 return ExprError();
11221 // If we need to expand the pack, build a template argument from it and
11223 if (ShouldExpand) {
11224 auto *Pack = E->getPack();
11225 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
11226 ArgStorage = getSema().Context.getPackExpansionType(
11227 getSema().Context.getTypeDeclType(TTPD), None);
11228 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
11229 ArgStorage = TemplateArgument(TemplateName(TTPD), None);
11231 auto *VD = cast<ValueDecl>(Pack);
11232 ExprResult DRE = getSema().BuildDeclRefExpr(VD, VD->getType(),
11233 VK_RValue, E->getPackLoc());
11234 if (DRE.isInvalid())
11235 return ExprError();
11236 ArgStorage = new (getSema().Context) PackExpansionExpr(
11237 getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
11239 PackArgs = ArgStorage;
11243 // If we're not expanding the pack, just transform the decl.
11244 if (!PackArgs.size()) {
11245 auto *Pack = cast_or_null<NamedDecl>(
11246 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
11248 return ExprError();
11249 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
11251 E->getRParenLoc(), None, None);
11254 // Try to compute the result without performing a partial substitution.
11255 Optional<unsigned> Result = 0;
11256 for (const TemplateArgument &Arg : PackArgs) {
11257 if (!Arg.isPackExpansion()) {
11258 Result = *Result + 1;
11262 TemplateArgumentLoc ArgLoc;
11263 InventTemplateArgumentLoc(Arg, ArgLoc);
11265 // Find the pattern of the pack expansion.
11266 SourceLocation Ellipsis;
11267 Optional<unsigned> OrigNumExpansions;
11268 TemplateArgumentLoc Pattern =
11269 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
11270 OrigNumExpansions);
11272 // Substitute under the pack expansion. Do not expand the pack (yet).
11273 TemplateArgumentLoc OutPattern;
11274 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11275 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
11279 // See if we can determine the number of arguments from the result.
11280 Optional<unsigned> NumExpansions =
11281 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
11282 if (!NumExpansions) {
11283 // No: we must be in an alias template expansion, and we're going to need
11284 // to actually expand the packs.
11289 Result = *Result + *NumExpansions;
11292 // Common case: we could determine the number of expansions without
11295 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11297 E->getRParenLoc(), *Result, None);
11299 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
11302 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
11303 typedef TemplateArgumentLocInventIterator<
11304 Derived, const TemplateArgument*> PackLocIterator;
11305 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
11306 PackLocIterator(*this, PackArgs.end()),
11307 TransformedPackArgs, /*Uneval*/true))
11308 return ExprError();
11311 // Check whether we managed to fully-expand the pack.
11312 // FIXME: Is it possible for us to do so and not hit the early exit path?
11313 SmallVector<TemplateArgument, 8> Args;
11314 bool PartialSubstitution = false;
11315 for (auto &Loc : TransformedPackArgs.arguments()) {
11316 Args.push_back(Loc.getArgument());
11317 if (Loc.getArgument().isPackExpansion())
11318 PartialSubstitution = true;
11321 if (PartialSubstitution)
11322 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11324 E->getRParenLoc(), None, Args);
11326 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11327 E->getPackLoc(), E->getRParenLoc(),
11328 Args.size(), None);
11331 template<typename Derived>
11333 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
11334 SubstNonTypeTemplateParmPackExpr *E) {
11335 // Default behavior is to do nothing with this transformation.
11339 template<typename Derived>
11341 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
11342 SubstNonTypeTemplateParmExpr *E) {
11343 // Default behavior is to do nothing with this transformation.
11347 template<typename Derived>
11349 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
11350 // Default behavior is to do nothing with this transformation.
11354 template<typename Derived>
11356 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
11357 MaterializeTemporaryExpr *E) {
11358 return getDerived().TransformExpr(E->GetTemporaryExpr());
11361 template<typename Derived>
11363 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
11364 Expr *Pattern = E->getPattern();
11366 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11367 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
11368 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11370 // Determine whether the set of unexpanded parameter packs can and should
11372 bool Expand = true;
11373 bool RetainExpansion = false;
11374 Optional<unsigned> NumExpansions;
11375 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
11376 Pattern->getSourceRange(),
11378 Expand, RetainExpansion,
11383 // Do not expand any packs here, just transform and rebuild a fold
11385 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11388 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
11389 if (LHS.isInvalid())
11393 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
11394 if (RHS.isInvalid())
11397 if (!getDerived().AlwaysRebuild() &&
11398 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
11401 return getDerived().RebuildCXXFoldExpr(
11402 E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
11403 RHS.get(), E->getLocEnd());
11406 // The transform has determined that we should perform an elementwise
11407 // expansion of the pattern. Do so.
11408 ExprResult Result = getDerived().TransformExpr(E->getInit());
11409 if (Result.isInvalid())
11411 bool LeftFold = E->isLeftFold();
11413 // If we're retaining an expansion for a right fold, it is the innermost
11414 // component and takes the init (if any).
11415 if (!LeftFold && RetainExpansion) {
11416 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11418 ExprResult Out = getDerived().TransformExpr(Pattern);
11419 if (Out.isInvalid())
11422 Result = getDerived().RebuildCXXFoldExpr(
11423 E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
11424 Result.get(), E->getLocEnd());
11425 if (Result.isInvalid())
11429 for (unsigned I = 0; I != *NumExpansions; ++I) {
11430 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
11431 getSema(), LeftFold ? I : *NumExpansions - I - 1);
11432 ExprResult Out = getDerived().TransformExpr(Pattern);
11433 if (Out.isInvalid())
11436 if (Out.get()->containsUnexpandedParameterPack()) {
11437 // We still have a pack; retain a pack expansion for this slice.
11438 Result = getDerived().RebuildCXXFoldExpr(
11440 LeftFold ? Result.get() : Out.get(),
11441 E->getOperator(), E->getEllipsisLoc(),
11442 LeftFold ? Out.get() : Result.get(),
11444 } else if (Result.isUsable()) {
11445 // We've got down to a single element; build a binary operator.
11446 Result = getDerived().RebuildBinaryOperator(
11447 E->getEllipsisLoc(), E->getOperator(),
11448 LeftFold ? Result.get() : Out.get(),
11449 LeftFold ? Out.get() : Result.get());
11453 if (Result.isInvalid())
11457 // If we're retaining an expansion for a left fold, it is the outermost
11458 // component and takes the complete expansion so far as its init (if any).
11459 if (LeftFold && RetainExpansion) {
11460 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11462 ExprResult Out = getDerived().TransformExpr(Pattern);
11463 if (Out.isInvalid())
11466 Result = getDerived().RebuildCXXFoldExpr(
11467 E->getLocStart(), Result.get(),
11468 E->getOperator(), E->getEllipsisLoc(),
11469 Out.get(), E->getLocEnd());
11470 if (Result.isInvalid())
11474 // If we had no init and an empty pack, and we're not retaining an expansion,
11475 // then produce a fallback value or error.
11476 if (Result.isUnset())
11477 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
11483 template<typename Derived>
11485 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
11486 CXXStdInitializerListExpr *E) {
11487 return getDerived().TransformExpr(E->getSubExpr());
11490 template<typename Derived>
11492 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
11493 return SemaRef.MaybeBindToTemporary(E);
11496 template<typename Derived>
11498 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
11502 template<typename Derived>
11504 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
11505 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11506 if (SubExpr.isInvalid())
11507 return ExprError();
11509 if (!getDerived().AlwaysRebuild() &&
11510 SubExpr.get() == E->getSubExpr())
11513 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
11516 template<typename Derived>
11518 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
11519 // Transform each of the elements.
11520 SmallVector<Expr *, 8> Elements;
11521 bool ArgChanged = false;
11522 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
11523 /*IsCall=*/false, Elements, &ArgChanged))
11524 return ExprError();
11526 if (!getDerived().AlwaysRebuild() && !ArgChanged)
11527 return SemaRef.MaybeBindToTemporary(E);
11529 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
11534 template<typename Derived>
11536 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
11537 ObjCDictionaryLiteral *E) {
11538 // Transform each of the elements.
11539 SmallVector<ObjCDictionaryElement, 8> Elements;
11540 bool ArgChanged = false;
11541 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
11542 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
11544 if (OrigElement.isPackExpansion()) {
11545 // This key/value element is a pack expansion.
11546 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11547 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
11548 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
11549 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11551 // Determine whether the set of unexpanded parameter packs can
11552 // and should be expanded.
11553 bool Expand = true;
11554 bool RetainExpansion = false;
11555 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
11556 Optional<unsigned> NumExpansions = OrigNumExpansions;
11557 SourceRange PatternRange(OrigElement.Key->getLocStart(),
11558 OrigElement.Value->getLocEnd());
11559 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
11562 Expand, RetainExpansion,
11564 return ExprError();
11567 // The transform has determined that we should perform a simple
11568 // transformation on the pack expansion, producing another pack
11570 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11571 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11572 if (Key.isInvalid())
11573 return ExprError();
11575 if (Key.get() != OrigElement.Key)
11578 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11579 if (Value.isInvalid())
11580 return ExprError();
11582 if (Value.get() != OrigElement.Value)
11585 ObjCDictionaryElement Expansion = {
11586 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
11588 Elements.push_back(Expansion);
11592 // Record right away that the argument was changed. This needs
11593 // to happen even if the array expands to nothing.
11596 // The transform has determined that we should perform an elementwise
11597 // expansion of the pattern. Do so.
11598 for (unsigned I = 0; I != *NumExpansions; ++I) {
11599 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11600 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11601 if (Key.isInvalid())
11602 return ExprError();
11604 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11605 if (Value.isInvalid())
11606 return ExprError();
11608 ObjCDictionaryElement Element = {
11609 Key.get(), Value.get(), SourceLocation(), NumExpansions
11612 // If any unexpanded parameter packs remain, we still have a
11614 // FIXME: Can this really happen?
11615 if (Key.get()->containsUnexpandedParameterPack() ||
11616 Value.get()->containsUnexpandedParameterPack())
11617 Element.EllipsisLoc = OrigElement.EllipsisLoc;
11619 Elements.push_back(Element);
11622 // FIXME: Retain a pack expansion if RetainExpansion is true.
11624 // We've finished with this pack expansion.
11628 // Transform and check key.
11629 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11630 if (Key.isInvalid())
11631 return ExprError();
11633 if (Key.get() != OrigElement.Key)
11636 // Transform and check value.
11638 = getDerived().TransformExpr(OrigElement.Value);
11639 if (Value.isInvalid())
11640 return ExprError();
11642 if (Value.get() != OrigElement.Value)
11645 ObjCDictionaryElement Element = {
11646 Key.get(), Value.get(), SourceLocation(), None
11648 Elements.push_back(Element);
11651 if (!getDerived().AlwaysRebuild() && !ArgChanged)
11652 return SemaRef.MaybeBindToTemporary(E);
11654 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
11658 template<typename Derived>
11660 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
11661 TypeSourceInfo *EncodedTypeInfo
11662 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
11663 if (!EncodedTypeInfo)
11664 return ExprError();
11666 if (!getDerived().AlwaysRebuild() &&
11667 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
11670 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
11672 E->getRParenLoc());
11675 template<typename Derived>
11676 ExprResult TreeTransform<Derived>::
11677 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
11678 // This is a kind of implicit conversion, and it needs to get dropped
11679 // and recomputed for the same general reasons that ImplicitCastExprs
11680 // do, as well a more specific one: this expression is only valid when
11681 // it appears *immediately* as an argument expression.
11682 return getDerived().TransformExpr(E->getSubExpr());
11685 template<typename Derived>
11686 ExprResult TreeTransform<Derived>::
11687 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
11688 TypeSourceInfo *TSInfo
11689 = getDerived().TransformType(E->getTypeInfoAsWritten());
11691 return ExprError();
11693 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
11694 if (Result.isInvalid())
11695 return ExprError();
11697 if (!getDerived().AlwaysRebuild() &&
11698 TSInfo == E->getTypeInfoAsWritten() &&
11699 Result.get() == E->getSubExpr())
11702 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
11703 E->getBridgeKeywordLoc(), TSInfo,
11707 template <typename Derived>
11708 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
11709 ObjCAvailabilityCheckExpr *E) {
11713 template<typename Derived>
11715 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
11716 // Transform arguments.
11717 bool ArgChanged = false;
11718 SmallVector<Expr*, 8> Args;
11719 Args.reserve(E->getNumArgs());
11720 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
11722 return ExprError();
11724 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
11725 // Class message: transform the receiver type.
11726 TypeSourceInfo *ReceiverTypeInfo
11727 = getDerived().TransformType(E->getClassReceiverTypeInfo());
11728 if (!ReceiverTypeInfo)
11729 return ExprError();
11731 // If nothing changed, just retain the existing message send.
11732 if (!getDerived().AlwaysRebuild() &&
11733 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
11734 return SemaRef.MaybeBindToTemporary(E);
11736 // Build a new class message send.
11737 SmallVector<SourceLocation, 16> SelLocs;
11738 E->getSelectorLocs(SelLocs);
11739 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
11742 E->getMethodDecl(),
11747 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
11748 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11749 if (!E->getMethodDecl())
11750 return ExprError();
11752 // Build a new class message send to 'super'.
11753 SmallVector<SourceLocation, 16> SelLocs;
11754 E->getSelectorLocs(SelLocs);
11755 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
11758 E->getReceiverType(),
11759 E->getMethodDecl(),
11765 // Instance message: transform the receiver
11766 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
11767 "Only class and instance messages may be instantiated");
11768 ExprResult Receiver
11769 = getDerived().TransformExpr(E->getInstanceReceiver());
11770 if (Receiver.isInvalid())
11771 return ExprError();
11773 // If nothing changed, just retain the existing message send.
11774 if (!getDerived().AlwaysRebuild() &&
11775 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
11776 return SemaRef.MaybeBindToTemporary(E);
11778 // Build a new instance message send.
11779 SmallVector<SourceLocation, 16> SelLocs;
11780 E->getSelectorLocs(SelLocs);
11781 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
11784 E->getMethodDecl(),
11790 template<typename Derived>
11792 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
11796 template<typename Derived>
11798 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
11802 template<typename Derived>
11804 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
11805 // Transform the base expression.
11806 ExprResult Base = getDerived().TransformExpr(E->getBase());
11807 if (Base.isInvalid())
11808 return ExprError();
11810 // We don't need to transform the ivar; it will never change.
11812 // If nothing changed, just retain the existing expression.
11813 if (!getDerived().AlwaysRebuild() &&
11814 Base.get() == E->getBase())
11817 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
11819 E->isArrow(), E->isFreeIvar());
11822 template<typename Derived>
11824 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
11825 // 'super' and types never change. Property never changes. Just
11826 // retain the existing expression.
11827 if (!E->isObjectReceiver())
11830 // Transform the base expression.
11831 ExprResult Base = getDerived().TransformExpr(E->getBase());
11832 if (Base.isInvalid())
11833 return ExprError();
11835 // We don't need to transform the property; it will never change.
11837 // If nothing changed, just retain the existing expression.
11838 if (!getDerived().AlwaysRebuild() &&
11839 Base.get() == E->getBase())
11842 if (E->isExplicitProperty())
11843 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
11844 E->getExplicitProperty(),
11847 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
11848 SemaRef.Context.PseudoObjectTy,
11849 E->getImplicitPropertyGetter(),
11850 E->getImplicitPropertySetter(),
11854 template<typename Derived>
11856 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
11857 // Transform the base expression.
11858 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
11859 if (Base.isInvalid())
11860 return ExprError();
11862 // Transform the key expression.
11863 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
11864 if (Key.isInvalid())
11865 return ExprError();
11867 // If nothing changed, just retain the existing expression.
11868 if (!getDerived().AlwaysRebuild() &&
11869 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
11872 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
11873 Base.get(), Key.get(),
11874 E->getAtIndexMethodDecl(),
11875 E->setAtIndexMethodDecl());
11878 template<typename Derived>
11880 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
11881 // Transform the base expression.
11882 ExprResult Base = getDerived().TransformExpr(E->getBase());
11883 if (Base.isInvalid())
11884 return ExprError();
11886 // If nothing changed, just retain the existing expression.
11887 if (!getDerived().AlwaysRebuild() &&
11888 Base.get() == E->getBase())
11891 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
11896 template<typename Derived>
11898 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
11899 bool ArgumentChanged = false;
11900 SmallVector<Expr*, 8> SubExprs;
11901 SubExprs.reserve(E->getNumSubExprs());
11902 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
11903 SubExprs, &ArgumentChanged))
11904 return ExprError();
11906 if (!getDerived().AlwaysRebuild() &&
11910 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
11912 E->getRParenLoc());
11915 template<typename Derived>
11917 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
11918 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
11919 if (SrcExpr.isInvalid())
11920 return ExprError();
11922 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
11924 return ExprError();
11926 if (!getDerived().AlwaysRebuild() &&
11927 Type == E->getTypeSourceInfo() &&
11928 SrcExpr.get() == E->getSrcExpr())
11931 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
11932 SrcExpr.get(), Type,
11933 E->getRParenLoc());
11936 template<typename Derived>
11938 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
11939 BlockDecl *oldBlock = E->getBlockDecl();
11941 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
11942 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
11944 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
11945 blockScope->TheDecl->setBlockMissingReturnType(
11946 oldBlock->blockMissingReturnType());
11948 SmallVector<ParmVarDecl*, 4> params;
11949 SmallVector<QualType, 4> paramTypes;
11951 const FunctionProtoType *exprFunctionType = E->getFunctionType();
11953 // Parameter substitution.
11954 Sema::ExtParameterInfoBuilder extParamInfos;
11955 if (getDerived().TransformFunctionTypeParams(
11956 E->getCaretLocation(), oldBlock->parameters(), nullptr,
11957 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, ¶ms,
11959 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
11960 return ExprError();
11963 QualType exprResultType =
11964 getDerived().TransformType(exprFunctionType->getReturnType());
11966 auto epi = exprFunctionType->getExtProtoInfo();
11967 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
11969 QualType functionType =
11970 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
11971 blockScope->FunctionType = functionType;
11973 // Set the parameters on the block decl.
11974 if (!params.empty())
11975 blockScope->TheDecl->setParams(params);
11977 if (!oldBlock->blockMissingReturnType()) {
11978 blockScope->HasImplicitReturnType = false;
11979 blockScope->ReturnType = exprResultType;
11982 // Transform the body
11983 StmtResult body = getDerived().TransformStmt(E->getBody());
11984 if (body.isInvalid()) {
11985 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
11986 return ExprError();
11990 // In builds with assertions, make sure that we captured everything we
11991 // captured before.
11992 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
11993 for (const auto &I : oldBlock->captures()) {
11994 VarDecl *oldCapture = I.getVariable();
11996 // Ignore parameter packs.
11997 if (isa<ParmVarDecl>(oldCapture) &&
11998 cast<ParmVarDecl>(oldCapture)->isParameterPack())
12001 VarDecl *newCapture =
12002 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12004 assert(blockScope->CaptureMap.count(newCapture));
12006 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12010 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12011 /*Scope=*/nullptr);
12014 template<typename Derived>
12016 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12017 llvm_unreachable("Cannot transform asType expressions yet");
12020 template<typename Derived>
12022 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12023 QualType RetTy = getDerived().TransformType(E->getType());
12024 bool ArgumentChanged = false;
12025 SmallVector<Expr*, 8> SubExprs;
12026 SubExprs.reserve(E->getNumSubExprs());
12027 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12028 SubExprs, &ArgumentChanged))
12029 return ExprError();
12031 if (!getDerived().AlwaysRebuild() &&
12035 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12036 RetTy, E->getOp(), E->getRParenLoc());
12039 //===----------------------------------------------------------------------===//
12040 // Type reconstruction
12041 //===----------------------------------------------------------------------===//
12043 template<typename Derived>
12044 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12045 SourceLocation Star) {
12046 return SemaRef.BuildPointerType(PointeeType, Star,
12047 getDerived().getBaseEntity());
12050 template<typename Derived>
12051 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12052 SourceLocation Star) {
12053 return SemaRef.BuildBlockPointerType(PointeeType, Star,
12054 getDerived().getBaseEntity());
12057 template<typename Derived>
12059 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12060 bool WrittenAsLValue,
12061 SourceLocation Sigil) {
12062 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12063 Sigil, getDerived().getBaseEntity());
12066 template<typename Derived>
12068 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12069 QualType ClassType,
12070 SourceLocation Sigil) {
12071 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12072 getDerived().getBaseEntity());
12075 template<typename Derived>
12076 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12077 const ObjCTypeParamDecl *Decl,
12078 SourceLocation ProtocolLAngleLoc,
12079 ArrayRef<ObjCProtocolDecl *> Protocols,
12080 ArrayRef<SourceLocation> ProtocolLocs,
12081 SourceLocation ProtocolRAngleLoc) {
12082 return SemaRef.BuildObjCTypeParamType(Decl,
12083 ProtocolLAngleLoc, Protocols,
12084 ProtocolLocs, ProtocolRAngleLoc,
12085 /*FailOnError=*/true);
12088 template<typename Derived>
12089 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12091 SourceLocation Loc,
12092 SourceLocation TypeArgsLAngleLoc,
12093 ArrayRef<TypeSourceInfo *> TypeArgs,
12094 SourceLocation TypeArgsRAngleLoc,
12095 SourceLocation ProtocolLAngleLoc,
12096 ArrayRef<ObjCProtocolDecl *> Protocols,
12097 ArrayRef<SourceLocation> ProtocolLocs,
12098 SourceLocation ProtocolRAngleLoc) {
12099 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12100 TypeArgs, TypeArgsRAngleLoc,
12101 ProtocolLAngleLoc, Protocols, ProtocolLocs,
12103 /*FailOnError=*/true);
12106 template<typename Derived>
12107 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12108 QualType PointeeType,
12109 SourceLocation Star) {
12110 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12113 template<typename Derived>
12115 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12116 ArrayType::ArraySizeModifier SizeMod,
12117 const llvm::APInt *Size,
12119 unsigned IndexTypeQuals,
12120 SourceRange BracketsRange) {
12121 if (SizeExpr || !Size)
12122 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12123 IndexTypeQuals, BracketsRange,
12124 getDerived().getBaseEntity());
12126 QualType Types[] = {
12127 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12128 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12129 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12131 const unsigned NumTypes = llvm::array_lengthof(Types);
12133 for (unsigned I = 0; I != NumTypes; ++I)
12134 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12135 SizeType = Types[I];
12139 // Note that we can return a VariableArrayType here in the case where
12140 // the element type was a dependent VariableArrayType.
12141 IntegerLiteral *ArraySize
12142 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12143 /*FIXME*/BracketsRange.getBegin());
12144 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12145 IndexTypeQuals, BracketsRange,
12146 getDerived().getBaseEntity());
12149 template<typename Derived>
12151 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12152 ArrayType::ArraySizeModifier SizeMod,
12153 const llvm::APInt &Size,
12154 unsigned IndexTypeQuals,
12155 SourceRange BracketsRange) {
12156 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
12157 IndexTypeQuals, BracketsRange);
12160 template<typename Derived>
12162 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12163 ArrayType::ArraySizeModifier SizeMod,
12164 unsigned IndexTypeQuals,
12165 SourceRange BracketsRange) {
12166 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12167 IndexTypeQuals, BracketsRange);
12170 template<typename Derived>
12172 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12173 ArrayType::ArraySizeModifier SizeMod,
12175 unsigned IndexTypeQuals,
12176 SourceRange BracketsRange) {
12177 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12179 IndexTypeQuals, BracketsRange);
12182 template<typename Derived>
12184 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12185 ArrayType::ArraySizeModifier SizeMod,
12187 unsigned IndexTypeQuals,
12188 SourceRange BracketsRange) {
12189 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12191 IndexTypeQuals, BracketsRange);
12194 template<typename Derived>
12195 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12196 unsigned NumElements,
12197 VectorType::VectorKind VecKind) {
12198 // FIXME: semantic checking!
12199 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12202 template<typename Derived>
12203 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
12204 unsigned NumElements,
12205 SourceLocation AttributeLoc) {
12206 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
12207 NumElements, true);
12208 IntegerLiteral *VectorSize
12209 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
12211 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
12214 template<typename Derived>
12216 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
12218 SourceLocation AttributeLoc) {
12219 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
12222 template<typename Derived>
12223 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
12225 MutableArrayRef<QualType> ParamTypes,
12226 const FunctionProtoType::ExtProtoInfo &EPI) {
12227 return SemaRef.BuildFunctionType(T, ParamTypes,
12228 getDerived().getBaseLocation(),
12229 getDerived().getBaseEntity(),
12233 template<typename Derived>
12234 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
12235 return SemaRef.Context.getFunctionNoProtoType(T);
12238 template<typename Derived>
12239 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
12241 assert(D && "no decl found");
12242 if (D->isInvalidDecl()) return QualType();
12244 // FIXME: Doesn't account for ObjCInterfaceDecl!
12246 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
12247 // A valid resolved using typename pack expansion decl can have multiple
12248 // UsingDecls, but they must each have exactly one type, and it must be
12249 // the same type in every case. But we must have at least one expansion!
12250 if (UPD->expansions().empty()) {
12251 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
12252 << UPD->isCXXClassMember() << UPD;
12256 // We might still have some unresolved types. Try to pick a resolved type
12257 // if we can. The final instantiation will check that the remaining
12258 // unresolved types instantiate to the type we pick.
12259 QualType FallbackT;
12261 for (auto *E : UPD->expansions()) {
12262 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
12263 if (ThisT.isNull())
12265 else if (ThisT->getAs<UnresolvedUsingType>())
12267 else if (T.isNull())
12270 assert(getSema().Context.hasSameType(ThisT, T) &&
12271 "mismatched resolved types in using pack expansion");
12273 return T.isNull() ? FallbackT : T;
12274 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
12275 assert(Using->hasTypename() &&
12276 "UnresolvedUsingTypenameDecl transformed to non-typename using");
12278 // A valid resolved using typename decl points to exactly one type decl.
12279 assert(++Using->shadow_begin() == Using->shadow_end());
12280 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
12282 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
12283 "UnresolvedUsingTypenameDecl transformed to non-using decl");
12284 Ty = cast<UnresolvedUsingTypenameDecl>(D);
12287 return SemaRef.Context.getTypeDeclType(Ty);
12290 template<typename Derived>
12291 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
12292 SourceLocation Loc) {
12293 return SemaRef.BuildTypeofExprType(E, Loc);
12296 template<typename Derived>
12297 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
12298 return SemaRef.Context.getTypeOfType(Underlying);
12301 template<typename Derived>
12302 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
12303 SourceLocation Loc) {
12304 return SemaRef.BuildDecltypeType(E, Loc);
12307 template<typename Derived>
12308 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
12309 UnaryTransformType::UTTKind UKind,
12310 SourceLocation Loc) {
12311 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
12314 template<typename Derived>
12315 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
12316 TemplateName Template,
12317 SourceLocation TemplateNameLoc,
12318 TemplateArgumentListInfo &TemplateArgs) {
12319 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
12322 template<typename Derived>
12323 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
12324 SourceLocation KWLoc) {
12325 return SemaRef.BuildAtomicType(ValueType, KWLoc);
12328 template<typename Derived>
12329 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
12330 SourceLocation KWLoc,
12332 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
12333 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
12336 template<typename Derived>
12338 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12340 TemplateDecl *Template) {
12341 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
12345 template<typename Derived>
12347 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12348 const IdentifierInfo &Name,
12349 SourceLocation NameLoc,
12350 QualType ObjectType,
12351 NamedDecl *FirstQualifierInScope,
12352 bool AllowInjectedClassName) {
12353 UnqualifiedId TemplateName;
12354 TemplateName.setIdentifier(&Name, NameLoc);
12355 Sema::TemplateTy Template;
12356 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12357 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12358 SS, TemplateKWLoc, TemplateName,
12359 ParsedType::make(ObjectType),
12360 /*EnteringContext=*/false,
12361 Template, AllowInjectedClassName);
12362 return Template.get();
12365 template<typename Derived>
12367 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12368 OverloadedOperatorKind Operator,
12369 SourceLocation NameLoc,
12370 QualType ObjectType,
12371 bool AllowInjectedClassName) {
12372 UnqualifiedId Name;
12373 // FIXME: Bogus location information.
12374 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
12375 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
12376 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12377 Sema::TemplateTy Template;
12378 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12379 SS, TemplateKWLoc, Name,
12380 ParsedType::make(ObjectType),
12381 /*EnteringContext=*/false,
12382 Template, AllowInjectedClassName);
12383 return Template.get();
12386 template<typename Derived>
12388 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
12389 SourceLocation OpLoc,
12393 Expr *Callee = OrigCallee->IgnoreParenCasts();
12394 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
12396 if (First->getObjectKind() == OK_ObjCProperty) {
12397 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12398 if (BinaryOperator::isAssignmentOp(Opc))
12399 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
12401 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
12402 if (Result.isInvalid())
12403 return ExprError();
12404 First = Result.get();
12407 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
12408 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
12409 if (Result.isInvalid())
12410 return ExprError();
12411 Second = Result.get();
12414 // Determine whether this should be a builtin operation.
12415 if (Op == OO_Subscript) {
12416 if (!First->getType()->isOverloadableType() &&
12417 !Second->getType()->isOverloadableType())
12418 return getSema().CreateBuiltinArraySubscriptExpr(First,
12419 Callee->getLocStart(),
12421 } else if (Op == OO_Arrow) {
12422 // -> is never a builtin operation.
12423 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
12424 } else if (Second == nullptr || isPostIncDec) {
12425 if (!First->getType()->isOverloadableType()) {
12426 // The argument is not of overloadable type, so try to create a
12427 // built-in unary operation.
12428 UnaryOperatorKind Opc
12429 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12431 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
12434 if (!First->getType()->isOverloadableType() &&
12435 !Second->getType()->isOverloadableType()) {
12436 // Neither of the arguments is an overloadable type, so try to
12437 // create a built-in binary operation.
12438 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12440 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
12441 if (Result.isInvalid())
12442 return ExprError();
12448 // Compute the transformed set of functions (and function templates) to be
12449 // used during overload resolution.
12450 UnresolvedSet<16> Functions;
12452 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
12453 assert(ULE->requiresADL());
12454 Functions.append(ULE->decls_begin(), ULE->decls_end());
12456 // If we've resolved this to a particular non-member function, just call
12457 // that function. If we resolved it to a member function,
12458 // CreateOverloaded* will find that function for us.
12459 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
12460 if (!isa<CXXMethodDecl>(ND))
12461 Functions.addDecl(ND);
12464 // Add any functions found via argument-dependent lookup.
12465 Expr *Args[2] = { First, Second };
12466 unsigned NumArgs = 1 + (Second != nullptr);
12468 // Create the overloaded operator invocation for unary operators.
12469 if (NumArgs == 1 || isPostIncDec) {
12470 UnaryOperatorKind Opc
12471 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12472 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
12475 if (Op == OO_Subscript) {
12476 SourceLocation LBrace;
12477 SourceLocation RBrace;
12479 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
12480 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
12481 LBrace = SourceLocation::getFromRawEncoding(
12482 NameLoc.CXXOperatorName.BeginOpNameLoc);
12483 RBrace = SourceLocation::getFromRawEncoding(
12484 NameLoc.CXXOperatorName.EndOpNameLoc);
12486 LBrace = Callee->getLocStart();
12490 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
12494 // Create the overloaded operator invocation for binary operators.
12495 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12497 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
12498 if (Result.isInvalid())
12499 return ExprError();
12504 template<typename Derived>
12506 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
12507 SourceLocation OperatorLoc,
12510 TypeSourceInfo *ScopeType,
12511 SourceLocation CCLoc,
12512 SourceLocation TildeLoc,
12513 PseudoDestructorTypeStorage Destroyed) {
12514 QualType BaseType = Base->getType();
12515 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
12516 (!isArrow && !BaseType->getAs<RecordType>()) ||
12517 (isArrow && BaseType->getAs<PointerType>() &&
12518 !BaseType->getAs<PointerType>()->getPointeeType()
12519 ->template getAs<RecordType>())){
12520 // This pseudo-destructor expression is still a pseudo-destructor.
12521 return SemaRef.BuildPseudoDestructorExpr(
12522 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
12523 CCLoc, TildeLoc, Destroyed);
12526 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
12527 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
12528 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
12529 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
12530 NameInfo.setNamedTypeInfo(DestroyedType);
12532 // The scope type is now known to be a valid nested name specifier
12533 // component. Tack it on to the end of the nested name specifier.
12535 if (!ScopeType->getType()->getAs<TagType>()) {
12536 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
12537 diag::err_expected_class_or_namespace)
12538 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
12539 return ExprError();
12541 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
12545 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12546 return getSema().BuildMemberReferenceExpr(Base, BaseType,
12547 OperatorLoc, isArrow,
12549 /*FIXME: FirstQualifier*/ nullptr,
12551 /*TemplateArgs*/ nullptr,
12555 template<typename Derived>
12557 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
12558 SourceLocation Loc = S->getLocStart();
12559 CapturedDecl *CD = S->getCapturedDecl();
12560 unsigned NumParams = CD->getNumParams();
12561 unsigned ContextParamPos = CD->getContextParamPosition();
12562 SmallVector<Sema::CapturedParamNameType, 4> Params;
12563 for (unsigned I = 0; I < NumParams; ++I) {
12564 if (I != ContextParamPos) {
12567 CD->getParam(I)->getName(),
12568 getDerived().TransformType(CD->getParam(I)->getType())));
12570 Params.push_back(std::make_pair(StringRef(), QualType()));
12573 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
12574 S->getCapturedRegionKind(), Params);
12577 Sema::CompoundScopeRAII CompoundScope(getSema());
12578 Body = getDerived().TransformStmt(S->getCapturedStmt());
12581 if (Body.isInvalid()) {
12582 getSema().ActOnCapturedRegionError();
12583 return StmtError();
12586 return getSema().ActOnCapturedRegionEnd(Body.get());
12589 } // end namespace clang
12591 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H