1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
8 // This file implements a semantic tree transformation that takes a given
9 // AST and rebuilds it, possibly transforming some nodes in the process.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
16 #include "CoroutineStmtBuilder.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExprOpenMP.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/AST/StmtOpenMP.h"
29 #include "clang/Sema/Designator.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Ownership.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaDiagnostic.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/Support/ErrorHandling.h"
43 /// A semantic tree transformation that allows one to transform one
44 /// abstract syntax tree into another.
46 /// A new tree transformation is defined by creating a new subclass \c X of
47 /// \c TreeTransform<X> and then overriding certain operations to provide
48 /// behavior specific to that transformation. For example, template
49 /// instantiation is implemented as a tree transformation where the
50 /// transformation of TemplateTypeParmType nodes involves substituting the
51 /// template arguments for their corresponding template parameters; a similar
52 /// transformation is performed for non-type template parameters and
53 /// template template parameters.
55 /// This tree-transformation template uses static polymorphism to allow
56 /// subclasses to customize any of its operations. Thus, a subclass can
57 /// override any of the transformation or rebuild operators by providing an
58 /// operation with the same signature as the default implementation. The
59 /// overriding function should not be virtual.
61 /// Semantic tree transformations are split into two stages, either of which
62 /// can be replaced by a subclass. The "transform" step transforms an AST node
63 /// or the parts of an AST node using the various transformation functions,
64 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
65 /// node of the appropriate kind from the pieces. The default transformation
66 /// routines recursively transform the operands to composite AST nodes (e.g.,
67 /// the pointee type of a PointerType node) and, if any of those operand nodes
68 /// were changed by the transformation, invokes the rebuild operation to create
71 /// Subclasses can customize the transformation at various levels. The
72 /// most coarse-grained transformations involve replacing TransformType(),
73 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
74 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
75 /// new implementations.
77 /// For more fine-grained transformations, subclasses can replace any of the
78 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
79 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
80 /// replacing TransformTemplateTypeParmType() allows template instantiation
81 /// to substitute template arguments for their corresponding template
82 /// parameters. Additionally, subclasses can override the \c RebuildXXX
83 /// functions to control how AST nodes are rebuilt when their operands change.
84 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
85 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
86 /// be able to use more efficient rebuild steps.
88 /// There are a handful of other functions that can be overridden, allowing one
89 /// to avoid traversing nodes that don't need any transformation
90 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
91 /// operands have not changed (\c AlwaysRebuild()), and customize the
92 /// default locations and entity names used for type-checking
93 /// (\c getBaseLocation(), \c getBaseEntity()).
94 template<typename Derived>
96 /// Private RAII object that helps us forget and then re-remember
97 /// the template argument corresponding to a partially-substituted parameter
99 class ForgetPartiallySubstitutedPackRAII {
101 TemplateArgument Old;
104 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
105 Old = Self.ForgetPartiallySubstitutedPack();
108 ~ForgetPartiallySubstitutedPackRAII() {
109 Self.RememberPartiallySubstitutedPack(Old);
116 /// The set of local declarations that have been transformed, for
117 /// cases where we are forced to build new declarations within the transformer
118 /// rather than in the subclass (e.g., lambda closure types).
119 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
122 /// Initializes a new tree transformer.
123 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
125 /// Retrieves a reference to the derived class.
126 Derived &getDerived() { return static_cast<Derived&>(*this); }
128 /// Retrieves a reference to the derived class.
129 const Derived &getDerived() const {
130 return static_cast<const Derived&>(*this);
133 static inline ExprResult Owned(Expr *E) { return E; }
134 static inline StmtResult Owned(Stmt *S) { return S; }
136 /// Retrieves a reference to the semantic analysis object used for
137 /// this tree transform.
138 Sema &getSema() const { return SemaRef; }
140 /// Whether the transformation should always rebuild AST nodes, even
141 /// if none of the children have changed.
143 /// Subclasses may override this function to specify when the transformation
144 /// should rebuild all AST nodes.
146 /// We must always rebuild all AST nodes when performing variadic template
147 /// pack expansion, in order to avoid violating the AST invariant that each
148 /// statement node appears at most once in its containing declaration.
149 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
151 /// Whether the transformation is forming an expression or statement that
152 /// replaces the original. In this case, we'll reuse mangling numbers from
153 /// existing lambdas.
154 bool ReplacingOriginal() { return false; }
156 /// Returns the location of the entity being transformed, if that
157 /// information was not available elsewhere in the AST.
159 /// By default, returns no source-location information. Subclasses can
160 /// provide an alternative implementation that provides better location
162 SourceLocation getBaseLocation() { return SourceLocation(); }
164 /// Returns the name of the entity being transformed, if that
165 /// information was not available elsewhere in the AST.
167 /// By default, returns an empty name. Subclasses can provide an alternative
168 /// implementation with a more precise name.
169 DeclarationName getBaseEntity() { return DeclarationName(); }
171 /// Sets the "base" location and entity when that
172 /// information is known based on another transformation.
174 /// By default, the source location and entity are ignored. Subclasses can
175 /// override this function to provide a customized implementation.
176 void setBase(SourceLocation Loc, DeclarationName Entity) { }
178 /// RAII object that temporarily sets the base location and entity
179 /// used for reporting diagnostics in types.
180 class TemporaryBase {
182 SourceLocation OldLocation;
183 DeclarationName OldEntity;
186 TemporaryBase(TreeTransform &Self, SourceLocation Location,
187 DeclarationName Entity) : Self(Self) {
188 OldLocation = Self.getDerived().getBaseLocation();
189 OldEntity = Self.getDerived().getBaseEntity();
191 if (Location.isValid())
192 Self.getDerived().setBase(Location, Entity);
196 Self.getDerived().setBase(OldLocation, OldEntity);
200 /// Determine whether the given type \p T has already been
203 /// Subclasses can provide an alternative implementation of this routine
204 /// to short-circuit evaluation when it is known that a given type will
205 /// not change. For example, template instantiation need not traverse
206 /// non-dependent types.
207 bool AlreadyTransformed(QualType T) {
211 /// Determine whether the given call argument should be dropped, e.g.,
212 /// because it is a default argument.
214 /// Subclasses can provide an alternative implementation of this routine to
215 /// determine which kinds of call arguments get dropped. By default,
216 /// CXXDefaultArgument nodes are dropped (prior to transformation).
217 bool DropCallArgument(Expr *E) {
218 return E->isDefaultArgument();
221 /// Determine whether we should expand a pack expansion with the
222 /// given set of parameter packs into separate arguments by repeatedly
223 /// transforming the pattern.
225 /// By default, the transformer never tries to expand pack expansions.
226 /// Subclasses can override this routine to provide different behavior.
228 /// \param EllipsisLoc The location of the ellipsis that identifies the
231 /// \param PatternRange The source range that covers the entire pattern of
232 /// the pack expansion.
234 /// \param Unexpanded The set of unexpanded parameter packs within the
237 /// \param ShouldExpand Will be set to \c true if the transformer should
238 /// expand the corresponding pack expansions into separate arguments. When
239 /// set, \c NumExpansions must also be set.
241 /// \param RetainExpansion Whether the caller should add an unexpanded
242 /// pack expansion after all of the expanded arguments. This is used
243 /// when extending explicitly-specified template argument packs per
244 /// C++0x [temp.arg.explicit]p9.
246 /// \param NumExpansions The number of separate arguments that will be in
247 /// the expanded form of the corresponding pack expansion. This is both an
248 /// input and an output parameter, which can be set by the caller if the
249 /// number of expansions is known a priori (e.g., due to a prior substitution)
250 /// and will be set by the callee when the number of expansions is known.
251 /// The callee must set this value when \c ShouldExpand is \c true; it may
252 /// set this value in other cases.
254 /// \returns true if an error occurred (e.g., because the parameter packs
255 /// are to be instantiated with arguments of different lengths), false
256 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
258 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
259 SourceRange PatternRange,
260 ArrayRef<UnexpandedParameterPack> Unexpanded,
262 bool &RetainExpansion,
263 Optional<unsigned> &NumExpansions) {
264 ShouldExpand = false;
268 /// "Forget" about the partially-substituted pack template argument,
269 /// when performing an instantiation that must preserve the parameter pack
272 /// This routine is meant to be overridden by the template instantiator.
273 TemplateArgument ForgetPartiallySubstitutedPack() {
274 return TemplateArgument();
277 /// "Remember" the partially-substituted pack template argument
278 /// after performing an instantiation that must preserve the parameter pack
281 /// This routine is meant to be overridden by the template instantiator.
282 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
284 /// Note to the derived class when a function parameter pack is
286 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
288 /// Transforms the given type into another type.
290 /// By default, this routine transforms a type by creating a
291 /// TypeSourceInfo for it and delegating to the appropriate
292 /// function. This is expensive, but we don't mind, because
293 /// this method is deprecated anyway; all users should be
294 /// switched to storing TypeSourceInfos.
296 /// \returns the transformed type.
297 QualType TransformType(QualType T);
299 /// Transforms the given type-with-location into a new
300 /// type-with-location.
302 /// By default, this routine transforms a type by delegating to the
303 /// appropriate TransformXXXType to build a new type. Subclasses
304 /// may override this function (to take over all type
305 /// transformations) or some set of the TransformXXXType functions
306 /// to alter the transformation.
307 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
309 /// Transform the given type-with-location into a new
310 /// type, collecting location information in the given builder
313 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
315 /// Transform a type that is permitted to produce a
316 /// DeducedTemplateSpecializationType.
318 /// This is used in the (relatively rare) contexts where it is acceptable
319 /// for transformation to produce a class template type with deduced
320 /// template arguments.
322 QualType TransformTypeWithDeducedTST(QualType T);
323 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
326 /// The reason why the value of a statement is not discarded, if any.
327 enum StmtDiscardKind {
333 /// Transform the given statement.
335 /// By default, this routine transforms a statement by delegating to the
336 /// appropriate TransformXXXStmt function to transform a specific kind of
337 /// statement or the TransformExpr() function to transform an expression.
338 /// Subclasses may override this function to transform statements using some
341 /// \returns the transformed statement.
342 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
344 /// Transform the given statement.
346 /// By default, this routine transforms a statement by delegating to the
347 /// appropriate TransformOMPXXXClause function to transform a specific kind
348 /// of clause. Subclasses may override this function to transform statements
349 /// using some other mechanism.
351 /// \returns the transformed OpenMP clause.
352 OMPClause *TransformOMPClause(OMPClause *S);
354 /// Transform the given attribute.
356 /// By default, this routine transforms a statement by delegating to the
357 /// appropriate TransformXXXAttr function to transform a specific kind
358 /// of attribute. Subclasses may override this function to transform
359 /// attributed statements using some other mechanism.
361 /// \returns the transformed attribute
362 const Attr *TransformAttr(const Attr *S);
364 /// Transform the specified attribute.
366 /// Subclasses should override the transformation of attributes with a pragma
367 /// spelling to transform expressions stored within the attribute.
369 /// \returns the transformed attribute.
371 #define PRAGMA_SPELLING_ATTR(X) \
372 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
373 #include "clang/Basic/AttrList.inc"
375 /// Transform the given expression.
377 /// By default, this routine transforms an expression by delegating to the
378 /// appropriate TransformXXXExpr function to build a new expression.
379 /// Subclasses may override this function to transform expressions using some
382 /// \returns the transformed expression.
383 ExprResult TransformExpr(Expr *E);
385 /// Transform the given initializer.
387 /// By default, this routine transforms an initializer by stripping off the
388 /// semantic nodes added by initialization, then passing the result to
389 /// TransformExpr or TransformExprs.
391 /// \returns the transformed initializer.
392 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
394 /// Transform the given list of expressions.
396 /// This routine transforms a list of expressions by invoking
397 /// \c TransformExpr() for each subexpression. However, it also provides
398 /// support for variadic templates by expanding any pack expansions (if the
399 /// derived class permits such expansion) along the way. When pack expansions
400 /// are present, the number of outputs may not equal the number of inputs.
402 /// \param Inputs The set of expressions to be transformed.
404 /// \param NumInputs The number of expressions in \c Inputs.
406 /// \param IsCall If \c true, then this transform is being performed on
407 /// function-call arguments, and any arguments that should be dropped, will
410 /// \param Outputs The transformed input expressions will be added to this
413 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
414 /// due to transformation.
416 /// \returns true if an error occurred, false otherwise.
417 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
418 SmallVectorImpl<Expr *> &Outputs,
419 bool *ArgChanged = nullptr);
421 /// Transform the given declaration, which is referenced from a type
424 /// By default, acts as the identity function on declarations, unless the
425 /// transformer has had to transform the declaration itself. Subclasses
426 /// may override this function to provide alternate behavior.
427 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
428 llvm::DenseMap<Decl *, Decl *>::iterator Known
429 = TransformedLocalDecls.find(D);
430 if (Known != TransformedLocalDecls.end())
431 return Known->second;
436 /// Transform the specified condition.
438 /// By default, this transforms the variable and expression and rebuilds
440 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
442 Sema::ConditionKind Kind);
444 /// Transform the attributes associated with the given declaration and
445 /// place them on the new declaration.
447 /// By default, this operation does nothing. Subclasses may override this
448 /// behavior to transform attributes.
449 void transformAttrs(Decl *Old, Decl *New) { }
451 /// Note that a local declaration has been transformed by this
454 /// Local declarations are typically transformed via a call to
455 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
456 /// the transformer itself has to transform the declarations. This routine
457 /// can be overridden by a subclass that keeps track of such mappings.
458 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
459 assert(New.size() == 1 &&
460 "must override transformedLocalDecl if performing pack expansion");
461 TransformedLocalDecls[Old] = New.front();
464 /// Transform the definition of the given declaration.
466 /// By default, invokes TransformDecl() to transform the declaration.
467 /// Subclasses may override this function to provide alternate behavior.
468 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
469 return getDerived().TransformDecl(Loc, D);
472 /// Transform the given declaration, which was the first part of a
473 /// nested-name-specifier in a member access expression.
475 /// This specific declaration transformation only applies to the first
476 /// identifier in a nested-name-specifier of a member access expression, e.g.,
477 /// the \c T in \c x->T::member
479 /// By default, invokes TransformDecl() to transform the declaration.
480 /// Subclasses may override this function to provide alternate behavior.
481 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
482 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
485 /// Transform the set of declarations in an OverloadExpr.
486 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
489 /// Transform the given nested-name-specifier with source-location
492 /// By default, transforms all of the types and declarations within the
493 /// nested-name-specifier. Subclasses may override this function to provide
494 /// alternate behavior.
495 NestedNameSpecifierLoc
496 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
497 QualType ObjectType = QualType(),
498 NamedDecl *FirstQualifierInScope = nullptr);
500 /// Transform the given declaration name.
502 /// By default, transforms the types of conversion function, constructor,
503 /// and destructor names and then (if needed) rebuilds the declaration name.
504 /// Identifiers and selectors are returned unmodified. Sublcasses may
505 /// override this function to provide alternate behavior.
507 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
509 /// Transform the given template name.
511 /// \param SS The nested-name-specifier that qualifies the template
512 /// name. This nested-name-specifier must already have been transformed.
514 /// \param Name The template name to transform.
516 /// \param NameLoc The source location of the template name.
518 /// \param ObjectType If we're translating a template name within a member
519 /// access expression, this is the type of the object whose member template
520 /// is being referenced.
522 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
523 /// also refers to a name within the current (lexical) scope, this is the
524 /// declaration it refers to.
526 /// By default, transforms the template name by transforming the declarations
527 /// and nested-name-specifiers that occur within the template name.
528 /// Subclasses may override this function to provide alternate behavior.
530 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
531 SourceLocation NameLoc,
532 QualType ObjectType = QualType(),
533 NamedDecl *FirstQualifierInScope = nullptr,
534 bool AllowInjectedClassName = false);
536 /// Transform the given template argument.
538 /// By default, this operation transforms the type, expression, or
539 /// declaration stored within the template argument and constructs a
540 /// new template argument from the transformed result. Subclasses may
541 /// override this function to provide alternate behavior.
543 /// Returns true if there was an error.
544 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
545 TemplateArgumentLoc &Output,
546 bool Uneval = false);
548 /// Transform the given set of template arguments.
550 /// By default, this operation transforms all of the template arguments
551 /// in the input set using \c TransformTemplateArgument(), and appends
552 /// the transformed arguments to the output list.
554 /// Note that this overload of \c TransformTemplateArguments() is merely
555 /// a convenience function. Subclasses that wish to override this behavior
556 /// should override the iterator-based member template version.
558 /// \param Inputs The set of template arguments to be transformed.
560 /// \param NumInputs The number of template arguments in \p Inputs.
562 /// \param Outputs The set of transformed template arguments output by this
565 /// Returns true if an error occurred.
566 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
568 TemplateArgumentListInfo &Outputs,
569 bool Uneval = false) {
570 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
574 /// Transform the given set of template arguments.
576 /// By default, this operation transforms all of the template arguments
577 /// in the input set using \c TransformTemplateArgument(), and appends
578 /// the transformed arguments to the output list.
580 /// \param First An iterator to the first template argument.
582 /// \param Last An iterator one step past the last template argument.
584 /// \param Outputs The set of transformed template arguments output by this
587 /// Returns true if an error occurred.
588 template<typename InputIterator>
589 bool TransformTemplateArguments(InputIterator First,
591 TemplateArgumentListInfo &Outputs,
592 bool Uneval = false);
594 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
595 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
596 TemplateArgumentLoc &ArgLoc);
598 /// Fakes up a TypeSourceInfo for a type.
599 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
600 return SemaRef.Context.getTrivialTypeSourceInfo(T,
601 getDerived().getBaseLocation());
604 #define ABSTRACT_TYPELOC(CLASS, PARENT)
605 #define TYPELOC(CLASS, PARENT) \
606 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
607 #include "clang/AST/TypeLocNodes.def"
609 template<typename Fn>
610 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
611 FunctionProtoTypeLoc TL,
612 CXXRecordDecl *ThisContext,
613 Qualifiers ThisTypeQuals,
614 Fn TransformExceptionSpec);
616 bool TransformExceptionSpec(SourceLocation Loc,
617 FunctionProtoType::ExceptionSpecInfo &ESI,
618 SmallVectorImpl<QualType> &Exceptions,
621 StmtResult TransformSEHHandler(Stmt *Handler);
624 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
625 TemplateSpecializationTypeLoc TL,
626 TemplateName Template);
629 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
630 DependentTemplateSpecializationTypeLoc TL,
631 TemplateName Template,
634 QualType TransformDependentTemplateSpecializationType(
635 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
636 NestedNameSpecifierLoc QualifierLoc);
638 /// Transforms the parameters of a function type into the
641 /// The result vectors should be kept in sync; null entries in the
642 /// variables vector are acceptable.
644 /// Return true on error.
645 bool TransformFunctionTypeParams(
646 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
647 const QualType *ParamTypes,
648 const FunctionProtoType::ExtParameterInfo *ParamInfos,
649 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
650 Sema::ExtParameterInfoBuilder &PInfos);
652 /// Transforms a single function-type parameter. Return null
655 /// \param indexAdjustment - A number to add to the parameter's
656 /// scope index; can be negative
657 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
659 Optional<unsigned> NumExpansions,
660 bool ExpectParameterPack);
662 /// Transform the body of a lambda-expression.
663 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
664 /// Alternative implementation of TransformLambdaBody that skips transforming
666 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
668 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
670 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
671 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
673 TemplateParameterList *TransformTemplateParameterList(
674 TemplateParameterList *TPL) {
678 ExprResult TransformAddressOfOperand(Expr *E);
680 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
681 bool IsAddressOfOperand,
682 TypeSourceInfo **RecoveryTSI);
684 ExprResult TransformParenDependentScopeDeclRefExpr(
685 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
686 TypeSourceInfo **RecoveryTSI);
688 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
690 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
691 // amount of stack usage with clang.
692 #define STMT(Node, Parent) \
693 LLVM_ATTRIBUTE_NOINLINE \
694 StmtResult Transform##Node(Node *S);
695 #define VALUESTMT(Node, Parent) \
696 LLVM_ATTRIBUTE_NOINLINE \
697 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
698 #define EXPR(Node, Parent) \
699 LLVM_ATTRIBUTE_NOINLINE \
700 ExprResult Transform##Node(Node *E);
701 #define ABSTRACT_STMT(Stmt)
702 #include "clang/AST/StmtNodes.inc"
704 #define OPENMP_CLAUSE(Name, Class) \
705 LLVM_ATTRIBUTE_NOINLINE \
706 OMPClause *Transform ## Class(Class *S);
707 #include "clang/Basic/OpenMPKinds.def"
709 /// Build a new qualified type given its unqualified type and type location.
711 /// By default, this routine adds type qualifiers only to types that can
712 /// have qualifiers, and silently suppresses those qualifiers that are not
713 /// permitted. Subclasses may override this routine to provide different
715 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
717 /// Build a new pointer type given its pointee type.
719 /// By default, performs semantic analysis when building the pointer type.
720 /// Subclasses may override this routine to provide different behavior.
721 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
723 /// Build a new block pointer type given its pointee type.
725 /// By default, performs semantic analysis when building the block pointer
726 /// type. Subclasses may override this routine to provide different behavior.
727 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
729 /// Build a new reference type given the type it references.
731 /// By default, performs semantic analysis when building the
732 /// reference type. Subclasses may override this routine to provide
733 /// different behavior.
735 /// \param LValue whether the type was written with an lvalue sigil
736 /// or an rvalue sigil.
737 QualType RebuildReferenceType(QualType ReferentType,
739 SourceLocation Sigil);
741 /// Build a new member pointer type given the pointee type and the
742 /// class type it refers into.
744 /// By default, performs semantic analysis when building the member pointer
745 /// type. Subclasses may override this routine to provide different behavior.
746 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
747 SourceLocation Sigil);
749 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
750 SourceLocation ProtocolLAngleLoc,
751 ArrayRef<ObjCProtocolDecl *> Protocols,
752 ArrayRef<SourceLocation> ProtocolLocs,
753 SourceLocation ProtocolRAngleLoc);
755 /// Build an Objective-C object type.
757 /// By default, performs semantic analysis when building the object type.
758 /// Subclasses may override this routine to provide different behavior.
759 QualType RebuildObjCObjectType(QualType BaseType,
761 SourceLocation TypeArgsLAngleLoc,
762 ArrayRef<TypeSourceInfo *> TypeArgs,
763 SourceLocation TypeArgsRAngleLoc,
764 SourceLocation ProtocolLAngleLoc,
765 ArrayRef<ObjCProtocolDecl *> Protocols,
766 ArrayRef<SourceLocation> ProtocolLocs,
767 SourceLocation ProtocolRAngleLoc);
769 /// Build a new Objective-C object pointer type given the pointee type.
771 /// By default, directly builds the pointer type, with no additional semantic
773 QualType RebuildObjCObjectPointerType(QualType PointeeType,
774 SourceLocation Star);
776 /// Build a new array type given the element type, size
777 /// modifier, size of the array (if known), size expression, and index type
780 /// By default, performs semantic analysis when building the array type.
781 /// Subclasses may override this routine to provide different behavior.
782 /// Also by default, all of the other Rebuild*Array
783 QualType RebuildArrayType(QualType ElementType,
784 ArrayType::ArraySizeModifier SizeMod,
785 const llvm::APInt *Size,
787 unsigned IndexTypeQuals,
788 SourceRange BracketsRange);
790 /// Build a new constant array type given the element type, size
791 /// modifier, (known) size of the array, and index type qualifiers.
793 /// By default, performs semantic analysis when building the array type.
794 /// Subclasses may override this routine to provide different behavior.
795 QualType RebuildConstantArrayType(QualType ElementType,
796 ArrayType::ArraySizeModifier SizeMod,
797 const llvm::APInt &Size,
799 unsigned IndexTypeQuals,
800 SourceRange BracketsRange);
802 /// Build a new incomplete array type given the element type, size
803 /// modifier, 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 RebuildIncompleteArrayType(QualType ElementType,
808 ArrayType::ArraySizeModifier SizeMod,
809 unsigned IndexTypeQuals,
810 SourceRange BracketsRange);
812 /// Build a new variable-length array type given the element type,
813 /// size modifier, size expression, and index type qualifiers.
815 /// By default, performs semantic analysis when building the array type.
816 /// Subclasses may override this routine to provide different behavior.
817 QualType RebuildVariableArrayType(QualType ElementType,
818 ArrayType::ArraySizeModifier SizeMod,
820 unsigned IndexTypeQuals,
821 SourceRange BracketsRange);
823 /// Build a new dependent-sized array type given the element type,
824 /// size modifier, size expression, and index type qualifiers.
826 /// By default, performs semantic analysis when building the array type.
827 /// Subclasses may override this routine to provide different behavior.
828 QualType RebuildDependentSizedArrayType(QualType ElementType,
829 ArrayType::ArraySizeModifier SizeMod,
831 unsigned IndexTypeQuals,
832 SourceRange BracketsRange);
834 /// Build a new vector type given the element type and
835 /// number of elements.
837 /// By default, performs semantic analysis when building the vector type.
838 /// Subclasses may override this routine to provide different behavior.
839 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
840 VectorType::VectorKind VecKind);
842 /// Build a new potentially dependently-sized extended vector type
843 /// given the element type and number of elements.
845 /// By default, performs semantic analysis when building the vector type.
846 /// Subclasses may override this routine to provide different behavior.
847 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
848 SourceLocation AttributeLoc,
849 VectorType::VectorKind);
851 /// Build a new extended vector type given the element type and
852 /// number of elements.
854 /// By default, performs semantic analysis when building the vector type.
855 /// Subclasses may override this routine to provide different behavior.
856 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
857 SourceLocation AttributeLoc);
859 /// Build a new potentially dependently-sized extended vector type
860 /// given the element type and number of elements.
862 /// By default, performs semantic analysis when building the vector type.
863 /// Subclasses may override this routine to provide different behavior.
864 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
866 SourceLocation AttributeLoc);
868 /// Build a new DependentAddressSpaceType or return the pointee
869 /// type variable with the correct address space (retrieved from
870 /// AddrSpaceExpr) applied to it. The former will be returned in cases
871 /// where the address space remains dependent.
873 /// By default, performs semantic analysis when building the type with address
874 /// space applied. Subclasses may override this routine to provide different
876 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
878 SourceLocation AttributeLoc);
880 /// Build a new function type.
882 /// By default, performs semantic analysis when building the function type.
883 /// Subclasses may override this routine to provide different behavior.
884 QualType RebuildFunctionProtoType(QualType T,
885 MutableArrayRef<QualType> ParamTypes,
886 const FunctionProtoType::ExtProtoInfo &EPI);
888 /// Build a new unprototyped function type.
889 QualType RebuildFunctionNoProtoType(QualType ResultType);
891 /// Rebuild an unresolved typename type, given the decl that
892 /// the UnresolvedUsingTypenameDecl was transformed to.
893 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
895 /// Build a new typedef type.
896 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
897 return SemaRef.Context.getTypeDeclType(Typedef);
900 /// Build a new MacroDefined type.
901 QualType RebuildMacroQualifiedType(QualType T,
902 const IdentifierInfo *MacroII) {
903 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
906 /// Build a new class/struct/union type.
907 QualType RebuildRecordType(RecordDecl *Record) {
908 return SemaRef.Context.getTypeDeclType(Record);
911 /// Build a new Enum type.
912 QualType RebuildEnumType(EnumDecl *Enum) {
913 return SemaRef.Context.getTypeDeclType(Enum);
916 /// Build a new typeof(expr) type.
918 /// By default, performs semantic analysis when building the typeof type.
919 /// Subclasses may override this routine to provide different behavior.
920 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
922 /// Build a new typeof(type) type.
924 /// By default, builds a new TypeOfType with the given underlying type.
925 QualType RebuildTypeOfType(QualType Underlying);
927 /// Build a new unary transform type.
928 QualType RebuildUnaryTransformType(QualType BaseType,
929 UnaryTransformType::UTTKind UKind,
932 /// Build a new C++11 decltype type.
934 /// By default, performs semantic analysis when building the decltype type.
935 /// Subclasses may override this routine to provide different behavior.
936 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
938 /// Build a new C++11 auto type.
940 /// By default, builds a new AutoType with the given deduced type.
941 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
942 // Note, IsDependent is always false here: we implicitly convert an 'auto'
943 // which has been deduced to a dependent type into an undeduced 'auto', so
944 // that we'll retry deduction after the transformation.
945 return SemaRef.Context.getAutoType(Deduced, Keyword,
946 /*IsDependent*/ false);
949 /// By default, builds a new DeducedTemplateSpecializationType with the given
951 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
953 return SemaRef.Context.getDeducedTemplateSpecializationType(
954 Template, Deduced, /*IsDependent*/ false);
957 /// Build a new template specialization type.
959 /// By default, performs semantic analysis when building the template
960 /// specialization type. Subclasses may override this routine to provide
961 /// different behavior.
962 QualType RebuildTemplateSpecializationType(TemplateName Template,
963 SourceLocation TemplateLoc,
964 TemplateArgumentListInfo &Args);
966 /// Build a new parenthesized type.
968 /// By default, builds a new ParenType type from the inner type.
969 /// Subclasses may override this routine to provide different behavior.
970 QualType RebuildParenType(QualType InnerType) {
971 return SemaRef.BuildParenType(InnerType);
974 /// Build a new qualified name type.
976 /// By default, builds a new ElaboratedType type from the keyword,
977 /// the nested-name-specifier and the named type.
978 /// Subclasses may override this routine to provide different behavior.
979 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
980 ElaboratedTypeKeyword Keyword,
981 NestedNameSpecifierLoc QualifierLoc,
983 return SemaRef.Context.getElaboratedType(Keyword,
984 QualifierLoc.getNestedNameSpecifier(),
988 /// Build a new typename type that refers to a template-id.
990 /// By default, builds a new DependentNameType type from the
991 /// nested-name-specifier and the given type. Subclasses may override
992 /// this routine to provide different behavior.
993 QualType RebuildDependentTemplateSpecializationType(
994 ElaboratedTypeKeyword Keyword,
995 NestedNameSpecifierLoc QualifierLoc,
996 SourceLocation TemplateKWLoc,
997 const IdentifierInfo *Name,
998 SourceLocation NameLoc,
999 TemplateArgumentListInfo &Args,
1000 bool AllowInjectedClassName) {
1001 // Rebuild the template name.
1002 // TODO: avoid TemplateName abstraction
1004 SS.Adopt(QualifierLoc);
1005 TemplateName InstName = getDerived().RebuildTemplateName(
1006 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1007 AllowInjectedClassName);
1009 if (InstName.isNull())
1012 // If it's still dependent, make a dependent specialization.
1013 if (InstName.getAsDependentTemplateName())
1014 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1015 QualifierLoc.getNestedNameSpecifier(),
1019 // Otherwise, make an elaborated type wrapping a non-dependent
1022 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1023 if (T.isNull()) return QualType();
1025 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1028 return SemaRef.Context.getElaboratedType(Keyword,
1029 QualifierLoc.getNestedNameSpecifier(),
1033 /// Build a new typename type that refers to an identifier.
1035 /// By default, performs semantic analysis when building the typename type
1036 /// (or elaborated type). Subclasses may override this routine to provide
1037 /// different behavior.
1038 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1039 SourceLocation KeywordLoc,
1040 NestedNameSpecifierLoc QualifierLoc,
1041 const IdentifierInfo *Id,
1042 SourceLocation IdLoc,
1043 bool DeducedTSTContext) {
1045 SS.Adopt(QualifierLoc);
1047 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1048 // If the name is still dependent, just build a new dependent name type.
1049 if (!SemaRef.computeDeclContext(SS))
1050 return SemaRef.Context.getDependentNameType(Keyword,
1051 QualifierLoc.getNestedNameSpecifier(),
1055 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1056 QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1058 // If a dependent name resolves to a deduced template specialization type,
1059 // check that we're in one of the syntactic contexts permitting it.
1060 if (!DeducedTSTContext) {
1061 if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1062 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1063 SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1064 << (int)SemaRef.getTemplateNameKindForDiagnostics(
1065 Deduced->getTemplateName())
1066 << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1067 if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1068 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1075 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1077 // We had a dependent elaborated-type-specifier that has been transformed
1078 // into a non-dependent elaborated-type-specifier. Find the tag we're
1080 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1081 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1085 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1088 TagDecl *Tag = nullptr;
1089 SemaRef.LookupQualifiedName(Result, DC);
1090 switch (Result.getResultKind()) {
1091 case LookupResult::NotFound:
1092 case LookupResult::NotFoundInCurrentInstantiation:
1095 case LookupResult::Found:
1096 Tag = Result.getAsSingle<TagDecl>();
1099 case LookupResult::FoundOverloaded:
1100 case LookupResult::FoundUnresolvedValue:
1101 llvm_unreachable("Tag lookup cannot find non-tags");
1103 case LookupResult::Ambiguous:
1104 // Let the LookupResult structure handle ambiguities.
1109 // Check where the name exists but isn't a tag type and use that to emit
1110 // better diagnostics.
1111 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1112 SemaRef.LookupQualifiedName(Result, DC);
1113 switch (Result.getResultKind()) {
1114 case LookupResult::Found:
1115 case LookupResult::FoundOverloaded:
1116 case LookupResult::FoundUnresolvedValue: {
1117 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1118 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1119 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1121 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1125 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1126 << Kind << Id << DC << QualifierLoc.getSourceRange();
1132 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1134 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1135 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1139 // Build the elaborated-type-specifier type.
1140 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1141 return SemaRef.Context.getElaboratedType(Keyword,
1142 QualifierLoc.getNestedNameSpecifier(),
1146 /// Build a new pack expansion type.
1148 /// By default, builds a new PackExpansionType type from the given pattern.
1149 /// Subclasses may override this routine to provide different behavior.
1150 QualType RebuildPackExpansionType(QualType Pattern,
1151 SourceRange PatternRange,
1152 SourceLocation EllipsisLoc,
1153 Optional<unsigned> NumExpansions) {
1154 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1158 /// Build a new atomic type given its value type.
1160 /// By default, performs semantic analysis when building the atomic type.
1161 /// Subclasses may override this routine to provide different behavior.
1162 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1164 /// Build a new pipe type given its value type.
1165 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1168 /// Build a new template name given a nested name specifier, a flag
1169 /// indicating whether the "template" keyword was provided, and the template
1170 /// that the template name refers to.
1172 /// By default, builds the new template name directly. Subclasses may override
1173 /// this routine to provide different behavior.
1174 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1176 TemplateDecl *Template);
1178 /// Build a new template name given a nested name specifier and the
1179 /// name that is referred to as a template.
1181 /// By default, performs semantic analysis to determine whether the name can
1182 /// be resolved to a specific template, then builds the appropriate kind of
1183 /// template name. Subclasses may override this routine to provide different
1185 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1186 SourceLocation TemplateKWLoc,
1187 const IdentifierInfo &Name,
1188 SourceLocation NameLoc, QualType ObjectType,
1189 NamedDecl *FirstQualifierInScope,
1190 bool AllowInjectedClassName);
1192 /// Build a new template name given a nested name specifier and the
1193 /// overloaded operator name that is referred to as a template.
1195 /// By default, performs semantic analysis to determine whether the name can
1196 /// be resolved to a specific template, then builds the appropriate kind of
1197 /// template name. Subclasses may override this routine to provide different
1199 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1200 SourceLocation TemplateKWLoc,
1201 OverloadedOperatorKind Operator,
1202 SourceLocation NameLoc, QualType ObjectType,
1203 bool AllowInjectedClassName);
1205 /// Build a new template name given a template template parameter pack
1208 /// By default, performs semantic analysis to determine whether the name can
1209 /// be resolved to a specific template, then builds the appropriate kind of
1210 /// template name. Subclasses may override this routine to provide different
1212 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1213 const TemplateArgument &ArgPack) {
1214 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1217 /// Build a new compound statement.
1219 /// By default, performs semantic analysis to build the new statement.
1220 /// Subclasses may override this routine to provide different behavior.
1221 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1222 MultiStmtArg Statements,
1223 SourceLocation RBraceLoc,
1225 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1229 /// Build a new case statement.
1231 /// By default, performs semantic analysis to build the new statement.
1232 /// Subclasses may override this routine to provide different behavior.
1233 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1235 SourceLocation EllipsisLoc,
1237 SourceLocation ColonLoc) {
1238 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1242 /// Attach the body to a new case statement.
1244 /// By default, performs semantic analysis to build the new statement.
1245 /// Subclasses may override this routine to provide different behavior.
1246 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1247 getSema().ActOnCaseStmtBody(S, Body);
1251 /// Build a new default statement.
1253 /// By default, performs semantic analysis to build the new statement.
1254 /// Subclasses may override this routine to provide different behavior.
1255 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1256 SourceLocation ColonLoc,
1258 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1259 /*CurScope=*/nullptr);
1262 /// Build a new label statement.
1264 /// By default, performs semantic analysis to build the new statement.
1265 /// Subclasses may override this routine to provide different behavior.
1266 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1267 SourceLocation ColonLoc, Stmt *SubStmt) {
1268 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1271 /// Build a new label statement.
1273 /// By default, performs semantic analysis to build the new statement.
1274 /// Subclasses may override this routine to provide different behavior.
1275 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1276 ArrayRef<const Attr*> Attrs,
1278 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1281 /// Build a new "if" statement.
1283 /// By default, performs semantic analysis to build the new statement.
1284 /// Subclasses may override this routine to provide different behavior.
1285 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1286 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1287 SourceLocation ElseLoc, Stmt *Else) {
1288 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1292 /// Start building a new switch statement.
1294 /// By default, performs semantic analysis to build the new statement.
1295 /// Subclasses may override this routine to provide different behavior.
1296 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1297 Sema::ConditionResult Cond) {
1298 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1301 /// Attach the body to the switch statement.
1303 /// By default, performs semantic analysis to build the new statement.
1304 /// Subclasses may override this routine to provide different behavior.
1305 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1306 Stmt *Switch, Stmt *Body) {
1307 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1310 /// Build a new while statement.
1312 /// By default, performs semantic analysis to build the new statement.
1313 /// Subclasses may override this routine to provide different behavior.
1314 StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1315 Sema::ConditionResult Cond, Stmt *Body) {
1316 return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1319 /// Build a new do-while statement.
1321 /// By default, performs semantic analysis to build the new statement.
1322 /// Subclasses may override this routine to provide different behavior.
1323 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1324 SourceLocation WhileLoc, SourceLocation LParenLoc,
1325 Expr *Cond, SourceLocation RParenLoc) {
1326 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1330 /// Build a new for statement.
1332 /// By default, performs semantic analysis to build the new statement.
1333 /// Subclasses may override this routine to provide different behavior.
1334 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1335 Stmt *Init, Sema::ConditionResult Cond,
1336 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1338 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1339 Inc, RParenLoc, Body);
1342 /// Build a new goto statement.
1344 /// By default, performs semantic analysis to build the new statement.
1345 /// Subclasses may override this routine to provide different behavior.
1346 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1348 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1351 /// Build a new indirect goto statement.
1353 /// By default, performs semantic analysis to build the new statement.
1354 /// Subclasses may override this routine to provide different behavior.
1355 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1356 SourceLocation StarLoc,
1358 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1361 /// Build a new return statement.
1363 /// By default, performs semantic analysis to build the new statement.
1364 /// Subclasses may override this routine to provide different behavior.
1365 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1366 return getSema().BuildReturnStmt(ReturnLoc, Result);
1369 /// Build a new declaration statement.
1371 /// By default, performs semantic analysis to build the new statement.
1372 /// Subclasses may override this routine to provide different behavior.
1373 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1374 SourceLocation StartLoc, SourceLocation EndLoc) {
1375 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1376 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1379 /// Build a new inline asm statement.
1381 /// By default, performs semantic analysis to build the new statement.
1382 /// Subclasses may override this routine to provide different behavior.
1383 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1384 bool IsVolatile, unsigned NumOutputs,
1385 unsigned NumInputs, IdentifierInfo **Names,
1386 MultiExprArg Constraints, MultiExprArg Exprs,
1387 Expr *AsmString, MultiExprArg Clobbers,
1389 SourceLocation RParenLoc) {
1390 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1391 NumInputs, Names, Constraints, Exprs,
1392 AsmString, Clobbers, NumLabels, RParenLoc);
1395 /// Build a new MS style inline asm statement.
1397 /// By default, performs semantic analysis to build the new statement.
1398 /// Subclasses may override this routine to provide different behavior.
1399 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1400 ArrayRef<Token> AsmToks,
1401 StringRef AsmString,
1402 unsigned NumOutputs, unsigned NumInputs,
1403 ArrayRef<StringRef> Constraints,
1404 ArrayRef<StringRef> Clobbers,
1405 ArrayRef<Expr*> Exprs,
1406 SourceLocation EndLoc) {
1407 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1408 NumOutputs, NumInputs,
1409 Constraints, Clobbers, Exprs, EndLoc);
1412 /// Build a new co_return statement.
1414 /// By default, performs semantic analysis to build the new statement.
1415 /// Subclasses may override this routine to provide different behavior.
1416 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1418 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1421 /// Build a new co_await expression.
1423 /// By default, performs semantic analysis to build the new expression.
1424 /// Subclasses may override this routine to provide different behavior.
1425 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1427 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1430 /// Build a new co_await expression.
1432 /// By default, performs semantic analysis to build the new expression.
1433 /// Subclasses may override this routine to provide different behavior.
1434 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1436 UnresolvedLookupExpr *Lookup) {
1437 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1440 /// Build a new co_yield expression.
1442 /// By default, performs semantic analysis to build the new expression.
1443 /// Subclasses may override this routine to provide different behavior.
1444 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1445 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1448 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1449 return getSema().BuildCoroutineBodyStmt(Args);
1452 /// Build a new Objective-C \@try statement.
1454 /// By default, performs semantic analysis to build the new statement.
1455 /// Subclasses may override this routine to provide different behavior.
1456 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1458 MultiStmtArg CatchStmts,
1460 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1464 /// Rebuild an Objective-C exception declaration.
1466 /// By default, performs semantic analysis to build the new declaration.
1467 /// Subclasses may override this routine to provide different behavior.
1468 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1469 TypeSourceInfo *TInfo, QualType T) {
1470 return getSema().BuildObjCExceptionDecl(TInfo, T,
1471 ExceptionDecl->getInnerLocStart(),
1472 ExceptionDecl->getLocation(),
1473 ExceptionDecl->getIdentifier());
1476 /// Build a new Objective-C \@catch statement.
1478 /// By default, performs semantic analysis to build the new statement.
1479 /// Subclasses may override this routine to provide different behavior.
1480 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1481 SourceLocation RParenLoc,
1484 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1488 /// Build a new Objective-C \@finally statement.
1490 /// By default, performs semantic analysis to build the new statement.
1491 /// Subclasses may override this routine to provide different behavior.
1492 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1494 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1497 /// Build a new Objective-C \@throw statement.
1499 /// By default, performs semantic analysis to build the new statement.
1500 /// Subclasses may override this routine to provide different behavior.
1501 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1503 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1506 /// Build a new OpenMP executable directive.
1508 /// By default, performs semantic analysis to build the new statement.
1509 /// Subclasses may override this routine to provide different behavior.
1510 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1511 DeclarationNameInfo DirName,
1512 OpenMPDirectiveKind CancelRegion,
1513 ArrayRef<OMPClause *> Clauses,
1514 Stmt *AStmt, SourceLocation StartLoc,
1515 SourceLocation EndLoc) {
1516 return getSema().ActOnOpenMPExecutableDirective(
1517 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1520 /// Build a new OpenMP 'if' clause.
1522 /// By default, performs semantic analysis to build the new OpenMP clause.
1523 /// Subclasses may override this routine to provide different behavior.
1524 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1525 Expr *Condition, SourceLocation StartLoc,
1526 SourceLocation LParenLoc,
1527 SourceLocation NameModifierLoc,
1528 SourceLocation ColonLoc,
1529 SourceLocation EndLoc) {
1530 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1531 LParenLoc, NameModifierLoc, ColonLoc,
1535 /// Build a new OpenMP 'final' clause.
1537 /// By default, performs semantic analysis to build the new OpenMP clause.
1538 /// Subclasses may override this routine to provide different behavior.
1539 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1540 SourceLocation LParenLoc,
1541 SourceLocation EndLoc) {
1542 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1546 /// Build a new OpenMP 'num_threads' clause.
1548 /// By default, performs semantic analysis to build the new OpenMP clause.
1549 /// Subclasses may override this routine to provide different behavior.
1550 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1551 SourceLocation StartLoc,
1552 SourceLocation LParenLoc,
1553 SourceLocation EndLoc) {
1554 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1558 /// Build a new OpenMP 'safelen' clause.
1560 /// By default, performs semantic analysis to build the new OpenMP clause.
1561 /// Subclasses may override this routine to provide different behavior.
1562 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1563 SourceLocation LParenLoc,
1564 SourceLocation EndLoc) {
1565 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1568 /// Build a new OpenMP 'simdlen' clause.
1570 /// By default, performs semantic analysis to build the new OpenMP clause.
1571 /// Subclasses may override this routine to provide different behavior.
1572 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1573 SourceLocation LParenLoc,
1574 SourceLocation EndLoc) {
1575 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1578 /// Build a new OpenMP 'allocator' clause.
1580 /// By default, performs semantic analysis to build the new OpenMP clause.
1581 /// Subclasses may override this routine to provide different behavior.
1582 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1583 SourceLocation LParenLoc,
1584 SourceLocation EndLoc) {
1585 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1588 /// Build a new OpenMP 'collapse' clause.
1590 /// By default, performs semantic analysis to build the new OpenMP clause.
1591 /// Subclasses may override this routine to provide different behavior.
1592 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1593 SourceLocation LParenLoc,
1594 SourceLocation EndLoc) {
1595 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1599 /// Build a new OpenMP 'default' clause.
1601 /// By default, performs semantic analysis to build the new OpenMP clause.
1602 /// Subclasses may override this routine to provide different behavior.
1603 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1604 SourceLocation KindKwLoc,
1605 SourceLocation StartLoc,
1606 SourceLocation LParenLoc,
1607 SourceLocation EndLoc) {
1608 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1609 StartLoc, LParenLoc, EndLoc);
1612 /// Build a new OpenMP 'proc_bind' clause.
1614 /// By default, performs semantic analysis to build the new OpenMP clause.
1615 /// Subclasses may override this routine to provide different behavior.
1616 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1617 SourceLocation KindKwLoc,
1618 SourceLocation StartLoc,
1619 SourceLocation LParenLoc,
1620 SourceLocation EndLoc) {
1621 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1622 StartLoc, LParenLoc, EndLoc);
1625 /// Build a new OpenMP 'schedule' 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 *RebuildOMPScheduleClause(
1630 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1631 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1632 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1633 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1634 return getSema().ActOnOpenMPScheduleClause(
1635 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1639 /// Build a new OpenMP 'ordered' clause.
1641 /// By default, performs semantic analysis to build the new OpenMP clause.
1642 /// Subclasses may override this routine to provide different behavior.
1643 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1644 SourceLocation EndLoc,
1645 SourceLocation LParenLoc, Expr *Num) {
1646 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1649 /// Build a new OpenMP 'private' clause.
1651 /// By default, performs semantic analysis to build the new OpenMP clause.
1652 /// Subclasses may override this routine to provide different behavior.
1653 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1654 SourceLocation StartLoc,
1655 SourceLocation LParenLoc,
1656 SourceLocation EndLoc) {
1657 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1661 /// Build a new OpenMP 'firstprivate' clause.
1663 /// By default, performs semantic analysis to build the new OpenMP clause.
1664 /// Subclasses may override this routine to provide different behavior.
1665 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1666 SourceLocation StartLoc,
1667 SourceLocation LParenLoc,
1668 SourceLocation EndLoc) {
1669 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1673 /// Build a new OpenMP 'lastprivate' clause.
1675 /// By default, performs semantic analysis to build the new OpenMP clause.
1676 /// Subclasses may override this routine to provide different behavior.
1677 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1678 SourceLocation StartLoc,
1679 SourceLocation LParenLoc,
1680 SourceLocation EndLoc) {
1681 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1685 /// Build a new OpenMP 'shared' clause.
1687 /// By default, performs semantic analysis to build the new OpenMP clause.
1688 /// Subclasses may override this routine to provide different behavior.
1689 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1690 SourceLocation StartLoc,
1691 SourceLocation LParenLoc,
1692 SourceLocation EndLoc) {
1693 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1697 /// Build a new OpenMP 'reduction' clause.
1699 /// By default, performs semantic analysis to build the new statement.
1700 /// Subclasses may override this routine to provide different behavior.
1701 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1702 SourceLocation StartLoc,
1703 SourceLocation LParenLoc,
1704 SourceLocation ColonLoc,
1705 SourceLocation EndLoc,
1706 CXXScopeSpec &ReductionIdScopeSpec,
1707 const DeclarationNameInfo &ReductionId,
1708 ArrayRef<Expr *> UnresolvedReductions) {
1709 return getSema().ActOnOpenMPReductionClause(
1710 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1711 ReductionId, UnresolvedReductions);
1714 /// Build a new OpenMP 'task_reduction' clause.
1716 /// By default, performs semantic analysis to build the new statement.
1717 /// Subclasses may override this routine to provide different behavior.
1718 OMPClause *RebuildOMPTaskReductionClause(
1719 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1720 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1721 CXXScopeSpec &ReductionIdScopeSpec,
1722 const DeclarationNameInfo &ReductionId,
1723 ArrayRef<Expr *> UnresolvedReductions) {
1724 return getSema().ActOnOpenMPTaskReductionClause(
1725 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1726 ReductionId, UnresolvedReductions);
1729 /// Build a new OpenMP 'in_reduction' clause.
1731 /// By default, performs semantic analysis to build the new statement.
1732 /// Subclasses may override this routine to provide different behavior.
1734 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1735 SourceLocation LParenLoc, SourceLocation ColonLoc,
1736 SourceLocation EndLoc,
1737 CXXScopeSpec &ReductionIdScopeSpec,
1738 const DeclarationNameInfo &ReductionId,
1739 ArrayRef<Expr *> UnresolvedReductions) {
1740 return getSema().ActOnOpenMPInReductionClause(
1741 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1742 ReductionId, UnresolvedReductions);
1745 /// Build a new OpenMP 'linear' clause.
1747 /// By default, performs semantic analysis to build the new OpenMP clause.
1748 /// Subclasses may override this routine to provide different behavior.
1749 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1750 SourceLocation StartLoc,
1751 SourceLocation LParenLoc,
1752 OpenMPLinearClauseKind Modifier,
1753 SourceLocation ModifierLoc,
1754 SourceLocation ColonLoc,
1755 SourceLocation EndLoc) {
1756 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1757 Modifier, ModifierLoc, ColonLoc,
1761 /// Build a new OpenMP 'aligned' clause.
1763 /// By default, performs semantic analysis to build the new OpenMP clause.
1764 /// Subclasses may override this routine to provide different behavior.
1765 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1766 SourceLocation StartLoc,
1767 SourceLocation LParenLoc,
1768 SourceLocation ColonLoc,
1769 SourceLocation EndLoc) {
1770 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1771 LParenLoc, ColonLoc, EndLoc);
1774 /// Build a new OpenMP 'copyin' clause.
1776 /// By default, performs semantic analysis to build the new OpenMP clause.
1777 /// Subclasses may override this routine to provide different behavior.
1778 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1779 SourceLocation StartLoc,
1780 SourceLocation LParenLoc,
1781 SourceLocation EndLoc) {
1782 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1786 /// Build a new OpenMP 'copyprivate' clause.
1788 /// By default, performs semantic analysis to build the new OpenMP clause.
1789 /// Subclasses may override this routine to provide different behavior.
1790 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1791 SourceLocation StartLoc,
1792 SourceLocation LParenLoc,
1793 SourceLocation EndLoc) {
1794 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1798 /// Build a new OpenMP 'flush' pseudo clause.
1800 /// By default, performs semantic analysis to build the new OpenMP clause.
1801 /// Subclasses may override this routine to provide different behavior.
1802 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1803 SourceLocation StartLoc,
1804 SourceLocation LParenLoc,
1805 SourceLocation EndLoc) {
1806 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1810 /// Build a new OpenMP 'depend' pseudo clause.
1812 /// By default, performs semantic analysis to build the new OpenMP clause.
1813 /// Subclasses may override this routine to provide different behavior.
1815 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1816 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1817 SourceLocation StartLoc, SourceLocation LParenLoc,
1818 SourceLocation EndLoc) {
1819 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1820 StartLoc, LParenLoc, EndLoc);
1823 /// Build a new OpenMP 'device' clause.
1825 /// By default, performs semantic analysis to build the new statement.
1826 /// Subclasses may override this routine to provide different behavior.
1827 OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1828 SourceLocation LParenLoc,
1829 SourceLocation EndLoc) {
1830 return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1834 /// Build a new OpenMP 'map' clause.
1836 /// By default, performs semantic analysis to build the new OpenMP clause.
1837 /// Subclasses may override this routine to provide different behavior.
1838 OMPClause *RebuildOMPMapClause(
1839 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1840 ArrayRef<SourceLocation> MapTypeModifiersLoc,
1841 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1842 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1843 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1844 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1845 return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1846 MapperIdScopeSpec, MapperId, MapType,
1847 IsMapTypeImplicit, MapLoc, ColonLoc,
1848 VarList, Locs, UnresolvedMappers);
1851 /// Build a new OpenMP 'allocate' clause.
1853 /// By default, performs semantic analysis to build the new OpenMP clause.
1854 /// Subclasses may override this routine to provide different behavior.
1855 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1856 SourceLocation StartLoc,
1857 SourceLocation LParenLoc,
1858 SourceLocation ColonLoc,
1859 SourceLocation EndLoc) {
1860 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1861 LParenLoc, ColonLoc, EndLoc);
1864 /// Build a new OpenMP 'num_teams' clause.
1866 /// By default, performs semantic analysis to build the new statement.
1867 /// Subclasses may override this routine to provide different behavior.
1868 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1869 SourceLocation LParenLoc,
1870 SourceLocation EndLoc) {
1871 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1875 /// Build a new OpenMP 'thread_limit' clause.
1877 /// By default, performs semantic analysis to build the new statement.
1878 /// Subclasses may override this routine to provide different behavior.
1879 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1880 SourceLocation StartLoc,
1881 SourceLocation LParenLoc,
1882 SourceLocation EndLoc) {
1883 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1887 /// Build a new OpenMP 'priority' clause.
1889 /// By default, performs semantic analysis to build the new statement.
1890 /// Subclasses may override this routine to provide different behavior.
1891 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1892 SourceLocation LParenLoc,
1893 SourceLocation EndLoc) {
1894 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1898 /// Build a new OpenMP 'grainsize' clause.
1900 /// By default, performs semantic analysis to build the new statement.
1901 /// Subclasses may override this routine to provide different behavior.
1902 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1903 SourceLocation LParenLoc,
1904 SourceLocation EndLoc) {
1905 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1909 /// Build a new OpenMP 'num_tasks' clause.
1911 /// By default, performs semantic analysis to build the new statement.
1912 /// Subclasses may override this routine to provide different behavior.
1913 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1914 SourceLocation LParenLoc,
1915 SourceLocation EndLoc) {
1916 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1920 /// Build a new OpenMP 'hint' clause.
1922 /// By default, performs semantic analysis to build the new statement.
1923 /// Subclasses may override this routine to provide different behavior.
1924 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1925 SourceLocation LParenLoc,
1926 SourceLocation EndLoc) {
1927 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1930 /// Build a new OpenMP 'dist_schedule' clause.
1932 /// By default, performs semantic analysis to build the new OpenMP clause.
1933 /// Subclasses may override this routine to provide different behavior.
1935 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1936 Expr *ChunkSize, SourceLocation StartLoc,
1937 SourceLocation LParenLoc, SourceLocation KindLoc,
1938 SourceLocation CommaLoc, SourceLocation EndLoc) {
1939 return getSema().ActOnOpenMPDistScheduleClause(
1940 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1943 /// Build a new OpenMP 'to' clause.
1945 /// By default, performs semantic analysis to build the new statement.
1946 /// Subclasses may override this routine to provide different behavior.
1947 OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1948 CXXScopeSpec &MapperIdScopeSpec,
1949 DeclarationNameInfo &MapperId,
1950 const OMPVarListLocTy &Locs,
1951 ArrayRef<Expr *> UnresolvedMappers) {
1952 return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1953 Locs, UnresolvedMappers);
1956 /// Build a new OpenMP 'from' clause.
1958 /// By default, performs semantic analysis to build the new statement.
1959 /// Subclasses may override this routine to provide different behavior.
1960 OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1961 CXXScopeSpec &MapperIdScopeSpec,
1962 DeclarationNameInfo &MapperId,
1963 const OMPVarListLocTy &Locs,
1964 ArrayRef<Expr *> UnresolvedMappers) {
1965 return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1966 Locs, UnresolvedMappers);
1969 /// Build a new OpenMP 'use_device_ptr' clause.
1971 /// By default, performs semantic analysis to build the new OpenMP clause.
1972 /// Subclasses may override this routine to provide different behavior.
1973 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1974 const OMPVarListLocTy &Locs) {
1975 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1978 /// Build a new OpenMP 'is_device_ptr' clause.
1980 /// By default, performs semantic analysis to build the new OpenMP clause.
1981 /// Subclasses may override this routine to provide different behavior.
1982 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1983 const OMPVarListLocTy &Locs) {
1984 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1987 /// Rebuild the operand to an Objective-C \@synchronized statement.
1989 /// By default, performs semantic analysis to build the new statement.
1990 /// Subclasses may override this routine to provide different behavior.
1991 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1993 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1996 /// Build a new Objective-C \@synchronized statement.
1998 /// By default, performs semantic analysis to build the new statement.
1999 /// Subclasses may override this routine to provide different behavior.
2000 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2001 Expr *Object, Stmt *Body) {
2002 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2005 /// Build a new Objective-C \@autoreleasepool statement.
2007 /// By default, performs semantic analysis to build the new statement.
2008 /// Subclasses may override this routine to provide different behavior.
2009 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2011 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2014 /// Build a new Objective-C fast enumeration statement.
2016 /// By default, performs semantic analysis to build the new statement.
2017 /// Subclasses may override this routine to provide different behavior.
2018 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2021 SourceLocation RParenLoc,
2023 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2027 if (ForEachStmt.isInvalid())
2030 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2033 /// Build a new C++ exception declaration.
2035 /// By default, performs semantic analysis to build the new decaration.
2036 /// Subclasses may override this routine to provide different behavior.
2037 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2038 TypeSourceInfo *Declarator,
2039 SourceLocation StartLoc,
2040 SourceLocation IdLoc,
2041 IdentifierInfo *Id) {
2042 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2043 StartLoc, IdLoc, Id);
2045 getSema().CurContext->addDecl(Var);
2049 /// Build a new C++ catch statement.
2051 /// By default, performs semantic analysis to build the new statement.
2052 /// Subclasses may override this routine to provide different behavior.
2053 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2054 VarDecl *ExceptionDecl,
2056 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2060 /// Build a new C++ try statement.
2062 /// By default, performs semantic analysis to build the new statement.
2063 /// Subclasses may override this routine to provide different behavior.
2064 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2065 ArrayRef<Stmt *> Handlers) {
2066 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2069 /// Build a new C++0x range-based for statement.
2071 /// By default, performs semantic analysis to build the new statement.
2072 /// Subclasses may override this routine to provide different behavior.
2073 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2074 SourceLocation CoawaitLoc, Stmt *Init,
2075 SourceLocation ColonLoc, Stmt *Range,
2076 Stmt *Begin, Stmt *End, Expr *Cond,
2077 Expr *Inc, Stmt *LoopVar,
2078 SourceLocation RParenLoc) {
2079 // If we've just learned that the range is actually an Objective-C
2080 // collection, treat this as an Objective-C fast enumeration loop.
2081 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2082 if (RangeStmt->isSingleDecl()) {
2083 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2084 if (RangeVar->isInvalidDecl())
2087 Expr *RangeExpr = RangeVar->getInit();
2088 if (!RangeExpr->isTypeDependent() &&
2089 RangeExpr->getType()->isObjCObjectPointerType()) {
2090 // FIXME: Support init-statements in Objective-C++20 ranged for
2093 return SemaRef.Diag(Init->getBeginLoc(),
2094 diag::err_objc_for_range_init_stmt)
2095 << Init->getSourceRange();
2097 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2098 RangeExpr, RParenLoc);
2104 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2105 Range, Begin, End, Cond, Inc, LoopVar,
2106 RParenLoc, Sema::BFRK_Rebuild);
2109 /// Build a new C++0x range-based for statement.
2111 /// By default, performs semantic analysis to build the new statement.
2112 /// Subclasses may override this routine to provide different behavior.
2113 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2115 NestedNameSpecifierLoc QualifierLoc,
2116 DeclarationNameInfo NameInfo,
2118 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2119 QualifierLoc, NameInfo, Nested);
2122 /// Attach body to a C++0x range-based for statement.
2124 /// By default, performs semantic analysis to finish the new statement.
2125 /// Subclasses may override this routine to provide different behavior.
2126 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2127 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2130 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2131 Stmt *TryBlock, Stmt *Handler) {
2132 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2135 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2137 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2140 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2141 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2144 /// Build a new predefined expression.
2146 /// By default, performs semantic analysis to build the new expression.
2147 /// Subclasses may override this routine to provide different behavior.
2148 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2149 PredefinedExpr::IdentKind IK) {
2150 return getSema().BuildPredefinedExpr(Loc, IK);
2153 /// Build a new expression that references a declaration.
2155 /// By default, performs semantic analysis to build the new expression.
2156 /// Subclasses may override this routine to provide different behavior.
2157 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2160 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2164 /// Build a new expression that references a declaration.
2166 /// By default, performs semantic analysis to build the new expression.
2167 /// Subclasses may override this routine to provide different behavior.
2168 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2170 const DeclarationNameInfo &NameInfo,
2172 TemplateArgumentListInfo *TemplateArgs) {
2174 SS.Adopt(QualifierLoc);
2175 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2179 /// Build a new expression in parentheses.
2181 /// By default, performs semantic analysis to build the new expression.
2182 /// Subclasses may override this routine to provide different behavior.
2183 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2184 SourceLocation RParen) {
2185 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2188 /// Build a new pseudo-destructor expression.
2190 /// By default, performs semantic analysis to build the new expression.
2191 /// Subclasses may override this routine to provide different behavior.
2192 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2193 SourceLocation OperatorLoc,
2196 TypeSourceInfo *ScopeType,
2197 SourceLocation CCLoc,
2198 SourceLocation TildeLoc,
2199 PseudoDestructorTypeStorage Destroyed);
2201 /// Build a new unary operator expression.
2203 /// By default, performs semantic analysis to build the new expression.
2204 /// Subclasses may override this routine to provide different behavior.
2205 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2206 UnaryOperatorKind Opc,
2208 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2211 /// Build a new builtin offsetof expression.
2213 /// By default, performs semantic analysis to build the new expression.
2214 /// Subclasses may override this routine to provide different behavior.
2215 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2216 TypeSourceInfo *Type,
2217 ArrayRef<Sema::OffsetOfComponent> Components,
2218 SourceLocation RParenLoc) {
2219 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2223 /// Build a new sizeof, alignof or vec_step expression with a
2226 /// By default, performs semantic analysis to build the new expression.
2227 /// Subclasses may override this routine to provide different behavior.
2228 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2229 SourceLocation OpLoc,
2230 UnaryExprOrTypeTrait ExprKind,
2232 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2235 /// Build a new sizeof, alignof or vec step expression with an
2236 /// expression argument.
2238 /// By default, performs semantic analysis to build the new expression.
2239 /// Subclasses may override this routine to provide different behavior.
2240 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2241 UnaryExprOrTypeTrait ExprKind,
2244 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2245 if (Result.isInvalid())
2251 /// Build a new array subscript expression.
2253 /// By default, performs semantic analysis to build the new expression.
2254 /// Subclasses may override this routine to provide different behavior.
2255 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2256 SourceLocation LBracketLoc,
2258 SourceLocation RBracketLoc) {
2259 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2264 /// Build a new array section expression.
2266 /// By default, performs semantic analysis to build the new expression.
2267 /// Subclasses may override this routine to provide different behavior.
2268 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2270 SourceLocation ColonLoc, Expr *Length,
2271 SourceLocation RBracketLoc) {
2272 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2273 ColonLoc, Length, RBracketLoc);
2276 /// Build a new call expression.
2278 /// By default, performs semantic analysis to build the new expression.
2279 /// Subclasses may override this routine to provide different behavior.
2280 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2282 SourceLocation RParenLoc,
2283 Expr *ExecConfig = nullptr) {
2284 return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2285 RParenLoc, ExecConfig);
2288 /// Build a new member access expression.
2290 /// By default, performs semantic analysis to build the new expression.
2291 /// Subclasses may override this routine to provide different behavior.
2292 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2294 NestedNameSpecifierLoc QualifierLoc,
2295 SourceLocation TemplateKWLoc,
2296 const DeclarationNameInfo &MemberNameInfo,
2298 NamedDecl *FoundDecl,
2299 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2300 NamedDecl *FirstQualifierInScope) {
2301 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2303 if (!Member->getDeclName()) {
2304 // We have a reference to an unnamed field. This is always the
2305 // base of an anonymous struct/union member access, i.e. the
2306 // field is always of record type.
2307 assert(Member->getType()->isRecordType() &&
2308 "unnamed member not of record type?");
2311 getSema().PerformObjectMemberConversion(BaseResult.get(),
2312 QualifierLoc.getNestedNameSpecifier(),
2314 if (BaseResult.isInvalid())
2316 Base = BaseResult.get();
2318 CXXScopeSpec EmptySS;
2319 return getSema().BuildFieldReferenceExpr(
2320 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2321 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2325 SS.Adopt(QualifierLoc);
2327 Base = BaseResult.get();
2328 QualType BaseType = Base->getType();
2330 if (isArrow && !BaseType->isPointerType())
2333 // FIXME: this involves duplicating earlier analysis in a lot of
2334 // cases; we should avoid this when possible.
2335 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2336 R.addDecl(FoundDecl);
2339 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2341 FirstQualifierInScope,
2342 R, ExplicitTemplateArgs,
2346 /// Build a new binary operator expression.
2348 /// By default, performs semantic analysis to build the new expression.
2349 /// Subclasses may override this routine to provide different behavior.
2350 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2351 BinaryOperatorKind Opc,
2352 Expr *LHS, Expr *RHS) {
2353 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2356 /// Build a new rewritten operator expression.
2358 /// By default, performs semantic analysis to build the new expression.
2359 /// Subclasses may override this routine to provide different behavior.
2360 ExprResult RebuildCXXRewrittenBinaryOperator(
2361 SourceLocation OpLoc, BinaryOperatorKind Opcode,
2362 const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2363 return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2364 RHS, /*RequiresADL*/false);
2367 /// Build a new conditional operator expression.
2369 /// By default, performs semantic analysis to build the new expression.
2370 /// Subclasses may override this routine to provide different behavior.
2371 ExprResult RebuildConditionalOperator(Expr *Cond,
2372 SourceLocation QuestionLoc,
2374 SourceLocation ColonLoc,
2376 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2380 /// Build a new C-style cast expression.
2382 /// By default, performs semantic analysis to build the new expression.
2383 /// Subclasses may override this routine to provide different behavior.
2384 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2385 TypeSourceInfo *TInfo,
2386 SourceLocation RParenLoc,
2388 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2392 /// Build a new compound literal expression.
2394 /// By default, performs semantic analysis to build the new expression.
2395 /// Subclasses may override this routine to provide different behavior.
2396 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2397 TypeSourceInfo *TInfo,
2398 SourceLocation RParenLoc,
2400 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2404 /// Build a new extended vector element access expression.
2406 /// By default, performs semantic analysis to build the new expression.
2407 /// Subclasses may override this routine to provide different behavior.
2408 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2409 SourceLocation OpLoc,
2410 SourceLocation AccessorLoc,
2411 IdentifierInfo &Accessor) {
2414 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2415 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2416 OpLoc, /*IsArrow*/ false,
2417 SS, SourceLocation(),
2418 /*FirstQualifierInScope*/ nullptr,
2420 /* TemplateArgs */ nullptr,
2424 /// Build a new initializer list expression.
2426 /// By default, performs semantic analysis to build the new expression.
2427 /// Subclasses may override this routine to provide different behavior.
2428 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2430 SourceLocation RBraceLoc) {
2431 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2434 /// Build a new designated initializer expression.
2436 /// By default, performs semantic analysis to build the new expression.
2437 /// Subclasses may override this routine to provide different behavior.
2438 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2439 MultiExprArg ArrayExprs,
2440 SourceLocation EqualOrColonLoc,
2444 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2446 if (Result.isInvalid())
2452 /// Build a new value-initialized expression.
2454 /// By default, builds the implicit value initialization without performing
2455 /// any semantic analysis. Subclasses may override this routine to provide
2456 /// different behavior.
2457 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2458 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2461 /// Build a new \c va_arg expression.
2463 /// By default, performs semantic analysis to build the new expression.
2464 /// Subclasses may override this routine to provide different behavior.
2465 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2466 Expr *SubExpr, TypeSourceInfo *TInfo,
2467 SourceLocation RParenLoc) {
2468 return getSema().BuildVAArgExpr(BuiltinLoc,
2473 /// Build a new expression list in parentheses.
2475 /// By default, performs semantic analysis to build the new expression.
2476 /// Subclasses may override this routine to provide different behavior.
2477 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2478 MultiExprArg SubExprs,
2479 SourceLocation RParenLoc) {
2480 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2483 /// Build a new address-of-label expression.
2485 /// By default, performs semantic analysis, using the name of the label
2486 /// rather than attempting to map the label statement itself.
2487 /// Subclasses may override this routine to provide different behavior.
2488 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2489 SourceLocation LabelLoc, LabelDecl *Label) {
2490 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2493 /// Build a new GNU statement expression.
2495 /// By default, performs semantic analysis to build the new expression.
2496 /// Subclasses may override this routine to provide different behavior.
2497 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2499 SourceLocation RParenLoc) {
2500 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2503 /// Build a new __builtin_choose_expr expression.
2505 /// By default, performs semantic analysis to build the new expression.
2506 /// Subclasses may override this routine to provide different behavior.
2507 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2508 Expr *Cond, Expr *LHS, Expr *RHS,
2509 SourceLocation RParenLoc) {
2510 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2515 /// Build a new generic selection expression.
2517 /// By default, performs semantic analysis to build the new expression.
2518 /// Subclasses may override this routine to provide different behavior.
2519 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2520 SourceLocation DefaultLoc,
2521 SourceLocation RParenLoc,
2522 Expr *ControllingExpr,
2523 ArrayRef<TypeSourceInfo *> Types,
2524 ArrayRef<Expr *> Exprs) {
2525 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2526 ControllingExpr, Types, Exprs);
2529 /// Build a new overloaded operator call expression.
2531 /// By default, performs semantic analysis to build the new expression.
2532 /// The semantic analysis provides the behavior of template instantiation,
2533 /// copying with transformations that turn what looks like an overloaded
2534 /// operator call into a use of a builtin operator, performing
2535 /// argument-dependent lookup, etc. Subclasses may override this routine to
2536 /// provide different behavior.
2537 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2538 SourceLocation OpLoc,
2543 /// Build a new C++ "named" cast expression, such as static_cast or
2544 /// reinterpret_cast.
2546 /// By default, this routine dispatches to one of the more-specific routines
2547 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2548 /// Subclasses may override this routine to provide different behavior.
2549 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2550 Stmt::StmtClass Class,
2551 SourceLocation LAngleLoc,
2552 TypeSourceInfo *TInfo,
2553 SourceLocation RAngleLoc,
2554 SourceLocation LParenLoc,
2556 SourceLocation RParenLoc) {
2558 case Stmt::CXXStaticCastExprClass:
2559 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2560 RAngleLoc, LParenLoc,
2561 SubExpr, RParenLoc);
2563 case Stmt::CXXDynamicCastExprClass:
2564 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2565 RAngleLoc, LParenLoc,
2566 SubExpr, RParenLoc);
2568 case Stmt::CXXReinterpretCastExprClass:
2569 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2570 RAngleLoc, LParenLoc,
2574 case Stmt::CXXConstCastExprClass:
2575 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2576 RAngleLoc, LParenLoc,
2577 SubExpr, RParenLoc);
2580 llvm_unreachable("Invalid C++ named cast");
2584 /// Build a new C++ static_cast expression.
2586 /// By default, performs semantic analysis to build the new expression.
2587 /// Subclasses may override this routine to provide different behavior.
2588 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2589 SourceLocation LAngleLoc,
2590 TypeSourceInfo *TInfo,
2591 SourceLocation RAngleLoc,
2592 SourceLocation LParenLoc,
2594 SourceLocation RParenLoc) {
2595 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2597 SourceRange(LAngleLoc, RAngleLoc),
2598 SourceRange(LParenLoc, RParenLoc));
2601 /// Build a new C++ dynamic_cast expression.
2603 /// By default, performs semantic analysis to build the new expression.
2604 /// Subclasses may override this routine to provide different behavior.
2605 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2606 SourceLocation LAngleLoc,
2607 TypeSourceInfo *TInfo,
2608 SourceLocation RAngleLoc,
2609 SourceLocation LParenLoc,
2611 SourceLocation RParenLoc) {
2612 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2614 SourceRange(LAngleLoc, RAngleLoc),
2615 SourceRange(LParenLoc, RParenLoc));
2618 /// Build a new C++ reinterpret_cast expression.
2620 /// By default, performs semantic analysis to build the new expression.
2621 /// Subclasses may override this routine to provide different behavior.
2622 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2623 SourceLocation LAngleLoc,
2624 TypeSourceInfo *TInfo,
2625 SourceLocation RAngleLoc,
2626 SourceLocation LParenLoc,
2628 SourceLocation RParenLoc) {
2629 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2631 SourceRange(LAngleLoc, RAngleLoc),
2632 SourceRange(LParenLoc, RParenLoc));
2635 /// Build a new C++ const_cast expression.
2637 /// By default, performs semantic analysis to build the new expression.
2638 /// Subclasses may override this routine to provide different behavior.
2639 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2640 SourceLocation LAngleLoc,
2641 TypeSourceInfo *TInfo,
2642 SourceLocation RAngleLoc,
2643 SourceLocation LParenLoc,
2645 SourceLocation RParenLoc) {
2646 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2648 SourceRange(LAngleLoc, RAngleLoc),
2649 SourceRange(LParenLoc, RParenLoc));
2652 /// Build a new C++ functional-style cast expression.
2654 /// By default, performs semantic analysis to build the new expression.
2655 /// Subclasses may override this routine to provide different behavior.
2656 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2657 SourceLocation LParenLoc,
2659 SourceLocation RParenLoc,
2660 bool ListInitialization) {
2661 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2662 MultiExprArg(&Sub, 1), RParenLoc,
2663 ListInitialization);
2666 /// Build a new C++ __builtin_bit_cast expression.
2668 /// By default, performs semantic analysis to build the new expression.
2669 /// Subclasses may override this routine to provide different behavior.
2670 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2671 TypeSourceInfo *TSI, Expr *Sub,
2672 SourceLocation RParenLoc) {
2673 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2676 /// Build a new C++ typeid(type) expression.
2678 /// By default, performs semantic analysis to build the new expression.
2679 /// Subclasses may override this routine to provide different behavior.
2680 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2681 SourceLocation TypeidLoc,
2682 TypeSourceInfo *Operand,
2683 SourceLocation RParenLoc) {
2684 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2689 /// Build a new C++ typeid(expr) expression.
2691 /// By default, performs semantic analysis to build the new expression.
2692 /// Subclasses may override this routine to provide different behavior.
2693 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2694 SourceLocation TypeidLoc,
2696 SourceLocation RParenLoc) {
2697 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2701 /// Build a new C++ __uuidof(type) expression.
2703 /// By default, performs semantic analysis to build the new expression.
2704 /// Subclasses may override this routine to provide different behavior.
2705 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2706 SourceLocation TypeidLoc,
2707 TypeSourceInfo *Operand,
2708 SourceLocation RParenLoc) {
2709 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2713 /// Build a new C++ __uuidof(expr) expression.
2715 /// By default, performs semantic analysis to build the new expression.
2716 /// Subclasses may override this routine to provide different behavior.
2717 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2718 SourceLocation TypeidLoc,
2720 SourceLocation RParenLoc) {
2721 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2725 /// Build a new C++ "this" expression.
2727 /// By default, builds a new "this" expression without performing any
2728 /// semantic analysis. Subclasses may override this routine to provide
2729 /// different behavior.
2730 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2733 return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2736 /// Build a new C++ throw expression.
2738 /// By default, performs semantic analysis to build the new expression.
2739 /// Subclasses may override this routine to provide different behavior.
2740 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2741 bool IsThrownVariableInScope) {
2742 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2745 /// Build a new C++ default-argument expression.
2747 /// By default, builds a new default-argument expression, which does not
2748 /// require any semantic analysis. Subclasses may override this routine to
2749 /// provide different behavior.
2750 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2751 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2752 getSema().CurContext);
2755 /// Build a new C++11 default-initialization expression.
2757 /// By default, builds a new default field initialization expression, which
2758 /// does not require any semantic analysis. Subclasses may override this
2759 /// routine to provide different behavior.
2760 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2762 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2763 getSema().CurContext);
2766 /// Build a new C++ zero-initialization expression.
2768 /// By default, performs semantic analysis to build the new expression.
2769 /// Subclasses may override this routine to provide different behavior.
2770 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2771 SourceLocation LParenLoc,
2772 SourceLocation RParenLoc) {
2773 return getSema().BuildCXXTypeConstructExpr(
2774 TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2777 /// Build a new C++ "new" expression.
2779 /// By default, performs semantic analysis to build the new expression.
2780 /// Subclasses may override this routine to provide different behavior.
2781 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2783 SourceLocation PlacementLParen,
2784 MultiExprArg PlacementArgs,
2785 SourceLocation PlacementRParen,
2786 SourceRange TypeIdParens,
2787 QualType AllocatedType,
2788 TypeSourceInfo *AllocatedTypeInfo,
2789 Optional<Expr *> ArraySize,
2790 SourceRange DirectInitRange,
2791 Expr *Initializer) {
2792 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2804 /// Build a new C++ "delete" expression.
2806 /// By default, performs semantic analysis to build the new expression.
2807 /// Subclasses may override this routine to provide different behavior.
2808 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2809 bool IsGlobalDelete,
2812 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2816 /// Build a new type trait expression.
2818 /// By default, performs semantic analysis to build the new expression.
2819 /// Subclasses may override this routine to provide different behavior.
2820 ExprResult RebuildTypeTrait(TypeTrait Trait,
2821 SourceLocation StartLoc,
2822 ArrayRef<TypeSourceInfo *> Args,
2823 SourceLocation RParenLoc) {
2824 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2827 /// Build a new array type trait expression.
2829 /// By default, performs semantic analysis to build the new expression.
2830 /// Subclasses may override this routine to provide different behavior.
2831 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2832 SourceLocation StartLoc,
2833 TypeSourceInfo *TSInfo,
2835 SourceLocation RParenLoc) {
2836 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2839 /// Build a new expression trait expression.
2841 /// By default, performs semantic analysis to build the new expression.
2842 /// Subclasses may override this routine to provide different behavior.
2843 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2844 SourceLocation StartLoc,
2846 SourceLocation RParenLoc) {
2847 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2850 /// Build a new (previously unresolved) declaration reference
2853 /// By default, performs semantic analysis to build the new expression.
2854 /// Subclasses may override this routine to provide different behavior.
2855 ExprResult RebuildDependentScopeDeclRefExpr(
2856 NestedNameSpecifierLoc QualifierLoc,
2857 SourceLocation TemplateKWLoc,
2858 const DeclarationNameInfo &NameInfo,
2859 const TemplateArgumentListInfo *TemplateArgs,
2860 bool IsAddressOfOperand,
2861 TypeSourceInfo **RecoveryTSI) {
2863 SS.Adopt(QualifierLoc);
2865 if (TemplateArgs || TemplateKWLoc.isValid())
2866 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2869 return getSema().BuildQualifiedDeclarationNameExpr(
2870 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2873 /// Build a new template-id expression.
2875 /// By default, performs semantic analysis to build the new expression.
2876 /// Subclasses may override this routine to provide different behavior.
2877 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2878 SourceLocation TemplateKWLoc,
2881 const TemplateArgumentListInfo *TemplateArgs) {
2882 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2886 /// Build a new object-construction expression.
2888 /// By default, performs semantic analysis to build the new expression.
2889 /// Subclasses may override this routine to provide different behavior.
2890 ExprResult RebuildCXXConstructExpr(QualType T,
2892 CXXConstructorDecl *Constructor,
2895 bool HadMultipleCandidates,
2896 bool ListInitialization,
2897 bool StdInitListInitialization,
2898 bool RequiresZeroInit,
2899 CXXConstructExpr::ConstructionKind ConstructKind,
2900 SourceRange ParenRange) {
2901 SmallVector<Expr*, 8> ConvertedArgs;
2902 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2906 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2909 HadMultipleCandidates,
2911 StdInitListInitialization,
2912 RequiresZeroInit, ConstructKind,
2916 /// Build a new implicit construction via inherited constructor
2918 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2919 CXXConstructorDecl *Constructor,
2920 bool ConstructsVBase,
2921 bool InheritedFromVBase) {
2922 return new (getSema().Context) CXXInheritedCtorInitExpr(
2923 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2926 /// Build a new object-construction expression.
2928 /// By default, performs semantic analysis to build the new expression.
2929 /// Subclasses may override this routine to provide different behavior.
2930 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2931 SourceLocation LParenOrBraceLoc,
2933 SourceLocation RParenOrBraceLoc,
2934 bool ListInitialization) {
2935 return getSema().BuildCXXTypeConstructExpr(
2936 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2939 /// Build a new object-construction expression.
2941 /// By default, performs semantic analysis to build the new expression.
2942 /// Subclasses may override this routine to provide different behavior.
2943 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2944 SourceLocation LParenLoc,
2946 SourceLocation RParenLoc,
2947 bool ListInitialization) {
2948 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2949 RParenLoc, ListInitialization);
2952 /// Build a new member reference expression.
2954 /// By default, performs semantic analysis to build the new expression.
2955 /// Subclasses may override this routine to provide different behavior.
2956 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2959 SourceLocation OperatorLoc,
2960 NestedNameSpecifierLoc QualifierLoc,
2961 SourceLocation TemplateKWLoc,
2962 NamedDecl *FirstQualifierInScope,
2963 const DeclarationNameInfo &MemberNameInfo,
2964 const TemplateArgumentListInfo *TemplateArgs) {
2966 SS.Adopt(QualifierLoc);
2968 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2969 OperatorLoc, IsArrow,
2971 FirstQualifierInScope,
2973 TemplateArgs, /*S*/nullptr);
2976 /// Build a new member reference expression.
2978 /// By default, performs semantic analysis to build the new expression.
2979 /// Subclasses may override this routine to provide different behavior.
2980 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2981 SourceLocation OperatorLoc,
2983 NestedNameSpecifierLoc QualifierLoc,
2984 SourceLocation TemplateKWLoc,
2985 NamedDecl *FirstQualifierInScope,
2987 const TemplateArgumentListInfo *TemplateArgs) {
2989 SS.Adopt(QualifierLoc);
2991 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2992 OperatorLoc, IsArrow,
2994 FirstQualifierInScope,
2995 R, TemplateArgs, /*S*/nullptr);
2998 /// Build a new noexcept expression.
3000 /// By default, performs semantic analysis to build the new expression.
3001 /// Subclasses may override this routine to provide different behavior.
3002 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3003 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3006 /// Build a new expression to compute the length of a parameter pack.
3007 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3009 SourceLocation PackLoc,
3010 SourceLocation RParenLoc,
3011 Optional<unsigned> Length,
3012 ArrayRef<TemplateArgument> PartialArgs) {
3013 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3014 RParenLoc, Length, PartialArgs);
3017 /// Build a new expression representing a call to a source location
3020 /// By default, performs semantic analysis to build the new expression.
3021 /// Subclasses may override this routine to provide different behavior.
3022 ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3023 SourceLocation BuiltinLoc,
3024 SourceLocation RPLoc,
3025 DeclContext *ParentContext) {
3026 return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3029 /// Build a new Objective-C boxed expression.
3031 /// By default, performs semantic analysis to build the new expression.
3032 /// Subclasses may override this routine to provide different behavior.
3033 ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3034 SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc,
3035 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3036 TemplateArgumentListInfo *TALI) {
3039 ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3042 NamedConcept, TALI);
3043 if (Result.isInvalid())
3048 /// \brief Build a new Objective-C boxed expression.
3050 /// By default, performs semantic analysis to build the new expression.
3051 /// Subclasses may override this routine to provide different behavior.
3052 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3053 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3056 /// Build a new Objective-C array literal.
3058 /// By default, performs semantic analysis to build the new expression.
3059 /// Subclasses may override this routine to provide different behavior.
3060 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3061 Expr **Elements, unsigned NumElements) {
3062 return getSema().BuildObjCArrayLiteral(Range,
3063 MultiExprArg(Elements, NumElements));
3066 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3067 Expr *Base, Expr *Key,
3068 ObjCMethodDecl *getterMethod,
3069 ObjCMethodDecl *setterMethod) {
3070 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3071 getterMethod, setterMethod);
3074 /// Build a new Objective-C dictionary literal.
3076 /// By default, performs semantic analysis to build the new expression.
3077 /// Subclasses may override this routine to provide different behavior.
3078 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3079 MutableArrayRef<ObjCDictionaryElement> Elements) {
3080 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3083 /// Build a new Objective-C \@encode expression.
3085 /// By default, performs semantic analysis to build the new expression.
3086 /// Subclasses may override this routine to provide different behavior.
3087 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3088 TypeSourceInfo *EncodeTypeInfo,
3089 SourceLocation RParenLoc) {
3090 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3093 /// Build a new Objective-C class message.
3094 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3096 ArrayRef<SourceLocation> SelectorLocs,
3097 ObjCMethodDecl *Method,
3098 SourceLocation LBracLoc,
3100 SourceLocation RBracLoc) {
3101 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3102 ReceiverTypeInfo->getType(),
3103 /*SuperLoc=*/SourceLocation(),
3104 Sel, Method, LBracLoc, SelectorLocs,
3108 /// Build a new Objective-C instance message.
3109 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3111 ArrayRef<SourceLocation> SelectorLocs,
3112 ObjCMethodDecl *Method,
3113 SourceLocation LBracLoc,
3115 SourceLocation RBracLoc) {
3116 return SemaRef.BuildInstanceMessage(Receiver,
3117 Receiver->getType(),
3118 /*SuperLoc=*/SourceLocation(),
3119 Sel, Method, LBracLoc, SelectorLocs,
3123 /// Build a new Objective-C instance/class message to 'super'.
3124 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3126 ArrayRef<SourceLocation> SelectorLocs,
3128 ObjCMethodDecl *Method,
3129 SourceLocation LBracLoc,
3131 SourceLocation RBracLoc) {
3132 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3135 Sel, Method, LBracLoc, SelectorLocs,
3137 : SemaRef.BuildClassMessage(nullptr,
3140 Sel, Method, LBracLoc, SelectorLocs,
3146 /// Build a new Objective-C ivar reference expression.
3148 /// By default, performs semantic analysis to build the new expression.
3149 /// Subclasses may override this routine to provide different behavior.
3150 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3151 SourceLocation IvarLoc,
3152 bool IsArrow, bool IsFreeIvar) {
3154 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3155 ExprResult Result = getSema().BuildMemberReferenceExpr(
3156 BaseArg, BaseArg->getType(),
3157 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3158 /*FirstQualifierInScope=*/nullptr, NameInfo,
3159 /*TemplateArgs=*/nullptr,
3161 if (IsFreeIvar && Result.isUsable())
3162 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3166 /// Build a new Objective-C property reference expression.
3168 /// By default, performs semantic analysis to build the new expression.
3169 /// Subclasses may override this routine to provide different behavior.
3170 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3171 ObjCPropertyDecl *Property,
3172 SourceLocation PropertyLoc) {
3174 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3175 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3176 /*FIXME:*/PropertyLoc,
3178 SS, SourceLocation(),
3179 /*FirstQualifierInScope=*/nullptr,
3181 /*TemplateArgs=*/nullptr,
3185 /// Build a new Objective-C property reference expression.
3187 /// By default, performs semantic analysis to build the new expression.
3188 /// Subclasses may override this routine to provide different behavior.
3189 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3190 ObjCMethodDecl *Getter,
3191 ObjCMethodDecl *Setter,
3192 SourceLocation PropertyLoc) {
3193 // Since these expressions can only be value-dependent, we do not
3194 // need to perform semantic analysis again.
3196 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3197 VK_LValue, OK_ObjCProperty,
3198 PropertyLoc, Base));
3201 /// Build a new Objective-C "isa" expression.
3203 /// By default, performs semantic analysis to build the new expression.
3204 /// Subclasses may override this routine to provide different behavior.
3205 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3206 SourceLocation OpLoc, bool IsArrow) {
3208 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3209 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3211 SS, SourceLocation(),
3212 /*FirstQualifierInScope=*/nullptr,
3214 /*TemplateArgs=*/nullptr,
3218 /// Build a new shuffle vector expression.
3220 /// By default, performs semantic analysis to build the new expression.
3221 /// Subclasses may override this routine to provide different behavior.
3222 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3223 MultiExprArg SubExprs,
3224 SourceLocation RParenLoc) {
3225 // Find the declaration for __builtin_shufflevector
3226 const IdentifierInfo &Name
3227 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3228 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3229 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3230 assert(!Lookup.empty() && "No __builtin_shufflevector?");
3232 // Build a reference to the __builtin_shufflevector builtin
3233 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3234 Expr *Callee = new (SemaRef.Context)
3235 DeclRefExpr(SemaRef.Context, Builtin, false,
3236 SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3237 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3238 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3239 CK_BuiltinFnToFnPtr).get();
3241 // Build the CallExpr
3242 ExprResult TheCall = CallExpr::Create(
3243 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3244 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3246 // Type-check the __builtin_shufflevector expression.
3247 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3250 /// Build a new convert vector expression.
3251 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3252 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3253 SourceLocation RParenLoc) {
3254 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3255 BuiltinLoc, RParenLoc);
3258 /// Build a new template argument pack expansion.
3260 /// By default, performs semantic analysis to build a new pack expansion
3261 /// for a template argument. Subclasses may override this routine to provide
3262 /// different behavior.
3263 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3264 SourceLocation EllipsisLoc,
3265 Optional<unsigned> NumExpansions) {
3266 switch (Pattern.getArgument().getKind()) {
3267 case TemplateArgument::Expression: {
3269 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3270 EllipsisLoc, NumExpansions);
3271 if (Result.isInvalid())
3272 return TemplateArgumentLoc();
3274 return TemplateArgumentLoc(Result.get(), Result.get());
3277 case TemplateArgument::Template:
3278 return TemplateArgumentLoc(TemplateArgument(
3279 Pattern.getArgument().getAsTemplate(),
3281 Pattern.getTemplateQualifierLoc(),
3282 Pattern.getTemplateNameLoc(),
3285 case TemplateArgument::Null:
3286 case TemplateArgument::Integral:
3287 case TemplateArgument::Declaration:
3288 case TemplateArgument::Pack:
3289 case TemplateArgument::TemplateExpansion:
3290 case TemplateArgument::NullPtr:
3291 llvm_unreachable("Pack expansion pattern has no parameter packs");
3293 case TemplateArgument::Type:
3294 if (TypeSourceInfo *Expansion
3295 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3298 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3303 return TemplateArgumentLoc();
3306 /// Build a new expression pack expansion.
3308 /// By default, performs semantic analysis to build a new pack expansion
3309 /// for an expression. Subclasses may override this routine to provide
3310 /// different behavior.
3311 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3312 Optional<unsigned> NumExpansions) {
3313 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3316 /// Build a new C++1z fold-expression.
3318 /// By default, performs semantic analysis in order to build a new fold
3320 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3321 BinaryOperatorKind Operator,
3322 SourceLocation EllipsisLoc, Expr *RHS,
3323 SourceLocation RParenLoc,
3324 Optional<unsigned> NumExpansions) {
3325 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3326 RHS, RParenLoc, NumExpansions);
3329 /// Build an empty C++1z fold-expression with the given operator.
3331 /// By default, produces the fallback value for the fold-expression, or
3332 /// produce an error if there is no fallback value.
3333 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3334 BinaryOperatorKind Operator) {
3335 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3338 /// Build a new atomic operation expression.
3340 /// By default, performs semantic analysis to build the new expression.
3341 /// Subclasses may override this routine to provide different behavior.
3342 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3343 AtomicExpr::AtomicOp Op,
3344 SourceLocation RParenLoc) {
3345 // Use this for all of the locations, since we don't know the difference
3346 // between the call and the expr at this point.
3347 SourceRange Range{BuiltinLoc, RParenLoc};
3348 return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3349 Sema::AtomicArgumentOrder::AST);
3353 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3354 QualType ObjectType,
3355 NamedDecl *FirstQualifierInScope,
3358 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3359 QualType ObjectType,
3360 NamedDecl *FirstQualifierInScope,
3363 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3364 NamedDecl *FirstQualifierInScope,
3367 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3368 DependentNameTypeLoc TL,
3369 bool DeducibleTSTContext);
3372 template <typename Derived>
3373 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3377 switch (S->getStmtClass()) {
3378 case Stmt::NoStmtClass: break;
3380 // Transform individual statement nodes
3381 // Pass SDK into statements that can produce a value
3382 #define STMT(Node, Parent) \
3383 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3384 #define VALUESTMT(Node, Parent) \
3385 case Stmt::Node##Class: \
3386 return getDerived().Transform##Node(cast<Node>(S), SDK);
3387 #define ABSTRACT_STMT(Node)
3388 #define EXPR(Node, Parent)
3389 #include "clang/AST/StmtNodes.inc"
3391 // Transform expressions by calling TransformExpr.
3392 #define STMT(Node, Parent)
3393 #define ABSTRACT_STMT(Stmt)
3394 #define EXPR(Node, Parent) case Stmt::Node##Class:
3395 #include "clang/AST/StmtNodes.inc"
3397 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3399 if (SDK == SDK_StmtExprResult)
3400 E = getSema().ActOnStmtExprResult(E);
3401 return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3408 template<typename Derived>
3409 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3413 switch (S->getClauseKind()) {
3415 // Transform individual clause nodes
3416 #define OPENMP_CLAUSE(Name, Class) \
3417 case OMPC_ ## Name : \
3418 return getDerived().Transform ## Class(cast<Class>(S));
3419 #include "clang/Basic/OpenMPKinds.def"
3426 template<typename Derived>
3427 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3431 switch (E->getStmtClass()) {
3432 case Stmt::NoStmtClass: break;
3433 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3434 #define ABSTRACT_STMT(Stmt)
3435 #define EXPR(Node, Parent) \
3436 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3437 #include "clang/AST/StmtNodes.inc"
3443 template<typename Derived>
3444 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3446 // Initializers are instantiated like expressions, except that various outer
3447 // layers are stripped.
3451 if (auto *FE = dyn_cast<FullExpr>(Init))
3452 Init = FE->getSubExpr();
3454 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3455 Init = AIL->getCommonExpr();
3457 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3458 Init = MTE->GetTemporaryExpr();
3460 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3461 Init = Binder->getSubExpr();
3463 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3464 Init = ICE->getSubExprAsWritten();
3466 if (CXXStdInitializerListExpr *ILE =
3467 dyn_cast<CXXStdInitializerListExpr>(Init))
3468 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3470 // If this is copy-initialization, we only need to reconstruct
3471 // InitListExprs. Other forms of copy-initialization will be a no-op if
3472 // the initializer is already the right type.
3473 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3474 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3475 return getDerived().TransformExpr(Init);
3477 // Revert value-initialization back to empty parens.
3478 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3479 SourceRange Parens = VIE->getSourceRange();
3480 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3484 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3485 if (isa<ImplicitValueInitExpr>(Init))
3486 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3489 // Revert initialization by constructor back to a parenthesized or braced list
3490 // of expressions. Any other form of initializer can just be reused directly.
3491 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3492 return getDerived().TransformExpr(Init);
3494 // If the initialization implicitly converted an initializer list to a
3495 // std::initializer_list object, unwrap the std::initializer_list too.
3496 if (Construct && Construct->isStdInitListInitialization())
3497 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3499 // Enter a list-init context if this was list initialization.
3500 EnterExpressionEvaluationContext Context(
3501 getSema(), EnterExpressionEvaluationContext::InitList,
3502 Construct->isListInitialization());
3504 SmallVector<Expr*, 8> NewArgs;
3505 bool ArgChanged = false;
3506 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3507 /*IsCall*/true, NewArgs, &ArgChanged))
3510 // If this was list initialization, revert to syntactic list form.
3511 if (Construct->isListInitialization())
3512 return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3513 Construct->getEndLoc());
3515 // Build a ParenListExpr to represent anything else.
3516 SourceRange Parens = Construct->getParenOrBraceRange();
3517 if (Parens.isInvalid()) {
3518 // This was a variable declaration's initialization for which no initializer
3520 assert(NewArgs.empty() &&
3521 "no parens or braces but have direct init with arguments?");
3524 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3528 template<typename Derived>
3529 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3532 SmallVectorImpl<Expr *> &Outputs,
3534 for (unsigned I = 0; I != NumInputs; ++I) {
3535 // If requested, drop call arguments that need to be dropped.
3536 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3543 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3544 Expr *Pattern = Expansion->getPattern();
3546 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3547 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3548 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3550 // Determine whether the set of unexpanded parameter packs can and should
3553 bool RetainExpansion = false;
3554 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3555 Optional<unsigned> NumExpansions = OrigNumExpansions;
3556 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3557 Pattern->getSourceRange(),
3559 Expand, RetainExpansion,
3564 // The transform has determined that we should perform a simple
3565 // transformation on the pack expansion, producing another pack
3567 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3568 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3569 if (OutPattern.isInvalid())
3572 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3573 Expansion->getEllipsisLoc(),
3575 if (Out.isInvalid())
3580 Outputs.push_back(Out.get());
3584 // Record right away that the argument was changed. This needs
3585 // to happen even if the array expands to nothing.
3586 if (ArgChanged) *ArgChanged = true;
3588 // The transform has determined that we should perform an elementwise
3589 // expansion of the pattern. Do so.
3590 for (unsigned I = 0; I != *NumExpansions; ++I) {
3591 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3592 ExprResult Out = getDerived().TransformExpr(Pattern);
3593 if (Out.isInvalid())
3596 if (Out.get()->containsUnexpandedParameterPack()) {
3597 Out = getDerived().RebuildPackExpansion(
3598 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3599 if (Out.isInvalid())
3603 Outputs.push_back(Out.get());
3606 // If we're supposed to retain a pack expansion, do so by temporarily
3607 // forgetting the partially-substituted parameter pack.
3608 if (RetainExpansion) {
3609 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3611 ExprResult Out = getDerived().TransformExpr(Pattern);
3612 if (Out.isInvalid())
3615 Out = getDerived().RebuildPackExpansion(
3616 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3617 if (Out.isInvalid())
3620 Outputs.push_back(Out.get());
3627 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3628 : getDerived().TransformExpr(Inputs[I]);
3629 if (Result.isInvalid())
3632 if (Result.get() != Inputs[I] && ArgChanged)
3635 Outputs.push_back(Result.get());
3641 template <typename Derived>
3642 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3643 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3645 VarDecl *ConditionVar = cast_or_null<VarDecl>(
3646 getDerived().TransformDefinition(Var->getLocation(), Var));
3649 return Sema::ConditionError();
3651 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3655 ExprResult CondExpr = getDerived().TransformExpr(Expr);
3657 if (CondExpr.isInvalid())
3658 return Sema::ConditionError();
3660 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3663 return Sema::ConditionResult();
3666 template<typename Derived>
3667 NestedNameSpecifierLoc
3668 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3669 NestedNameSpecifierLoc NNS,
3670 QualType ObjectType,
3671 NamedDecl *FirstQualifierInScope) {
3672 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3673 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3674 Qualifier = Qualifier.getPrefix())
3675 Qualifiers.push_back(Qualifier);
3678 while (!Qualifiers.empty()) {
3679 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3680 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3682 switch (QNNS->getKind()) {
3683 case NestedNameSpecifier::Identifier: {
3684 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3685 Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3686 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3687 SS, FirstQualifierInScope, false))
3688 return NestedNameSpecifierLoc();
3692 case NestedNameSpecifier::Namespace: {
3694 = cast_or_null<NamespaceDecl>(
3695 getDerived().TransformDecl(
3696 Q.getLocalBeginLoc(),
3697 QNNS->getAsNamespace()));
3698 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3702 case NestedNameSpecifier::NamespaceAlias: {
3703 NamespaceAliasDecl *Alias
3704 = cast_or_null<NamespaceAliasDecl>(
3705 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3706 QNNS->getAsNamespaceAlias()));
3707 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3708 Q.getLocalEndLoc());
3712 case NestedNameSpecifier::Global:
3713 // There is no meaningful transformation that one could perform on the
3715 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3718 case NestedNameSpecifier::Super: {
3720 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3721 SourceLocation(), QNNS->getAsRecordDecl()));
3722 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3726 case NestedNameSpecifier::TypeSpecWithTemplate:
3727 case NestedNameSpecifier::TypeSpec: {
3728 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3729 FirstQualifierInScope, SS);
3732 return NestedNameSpecifierLoc();
3734 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3735 (SemaRef.getLangOpts().CPlusPlus11 &&
3736 TL.getType()->isEnumeralType())) {
3737 assert(!TL.getType().hasLocalQualifiers() &&
3738 "Can't get cv-qualifiers here");
3739 if (TL.getType()->isEnumeralType())
3740 SemaRef.Diag(TL.getBeginLoc(),
3741 diag::warn_cxx98_compat_enum_nested_name_spec);
3742 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3743 Q.getLocalEndLoc());
3746 // If the nested-name-specifier is an invalid type def, don't emit an
3747 // error because a previous error should have already been emitted.
3748 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3749 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3750 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3751 << TL.getType() << SS.getRange();
3753 return NestedNameSpecifierLoc();
3757 // The qualifier-in-scope and object type only apply to the leftmost entity.
3758 FirstQualifierInScope = nullptr;
3759 ObjectType = QualType();
3762 // Don't rebuild the nested-name-specifier if we don't have to.
3763 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3764 !getDerived().AlwaysRebuild())
3767 // If we can re-use the source-location data from the original
3768 // nested-name-specifier, do so.
3769 if (SS.location_size() == NNS.getDataLength() &&
3770 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3771 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3773 // Allocate new nested-name-specifier location information.
3774 return SS.getWithLocInContext(SemaRef.Context);
3777 template<typename Derived>
3779 TreeTransform<Derived>
3780 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3781 DeclarationName Name = NameInfo.getName();
3783 return DeclarationNameInfo();
3785 switch (Name.getNameKind()) {
3786 case DeclarationName::Identifier:
3787 case DeclarationName::ObjCZeroArgSelector:
3788 case DeclarationName::ObjCOneArgSelector:
3789 case DeclarationName::ObjCMultiArgSelector:
3790 case DeclarationName::CXXOperatorName:
3791 case DeclarationName::CXXLiteralOperatorName:
3792 case DeclarationName::CXXUsingDirective:
3795 case DeclarationName::CXXDeductionGuideName: {
3796 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3797 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3798 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3800 return DeclarationNameInfo();
3802 DeclarationNameInfo NewNameInfo(NameInfo);
3803 NewNameInfo.setName(
3804 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3808 case DeclarationName::CXXConstructorName:
3809 case DeclarationName::CXXDestructorName:
3810 case DeclarationName::CXXConversionFunctionName: {
3811 TypeSourceInfo *NewTInfo;
3812 CanQualType NewCanTy;
3813 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3814 NewTInfo = getDerived().TransformType(OldTInfo);
3816 return DeclarationNameInfo();
3817 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3821 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3822 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3824 return DeclarationNameInfo();
3825 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3828 DeclarationName NewName
3829 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3831 DeclarationNameInfo NewNameInfo(NameInfo);
3832 NewNameInfo.setName(NewName);
3833 NewNameInfo.setNamedTypeInfo(NewTInfo);
3838 llvm_unreachable("Unknown name kind.");
3841 template<typename Derived>
3843 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3845 SourceLocation NameLoc,
3846 QualType ObjectType,
3847 NamedDecl *FirstQualifierInScope,
3848 bool AllowInjectedClassName) {
3849 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3850 TemplateDecl *Template = QTN->getTemplateDecl();
3851 assert(Template && "qualified template name must refer to a template");
3853 TemplateDecl *TransTemplate
3854 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3857 return TemplateName();
3859 if (!getDerived().AlwaysRebuild() &&
3860 SS.getScopeRep() == QTN->getQualifier() &&
3861 TransTemplate == Template)
3864 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3868 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3869 if (SS.getScopeRep()) {
3870 // These apply to the scope specifier, not the template.
3871 ObjectType = QualType();
3872 FirstQualifierInScope = nullptr;
3875 if (!getDerived().AlwaysRebuild() &&
3876 SS.getScopeRep() == DTN->getQualifier() &&
3877 ObjectType.isNull())
3880 // FIXME: Preserve the location of the "template" keyword.
3881 SourceLocation TemplateKWLoc = NameLoc;
3883 if (DTN->isIdentifier()) {
3884 return getDerived().RebuildTemplateName(SS,
3886 *DTN->getIdentifier(),
3889 FirstQualifierInScope,
3890 AllowInjectedClassName);
3893 return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3894 DTN->getOperator(), NameLoc,
3895 ObjectType, AllowInjectedClassName);
3898 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3899 TemplateDecl *TransTemplate
3900 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3903 return TemplateName();
3905 if (!getDerived().AlwaysRebuild() &&
3906 TransTemplate == Template)
3909 return TemplateName(TransTemplate);
3912 if (SubstTemplateTemplateParmPackStorage *SubstPack
3913 = Name.getAsSubstTemplateTemplateParmPack()) {
3914 TemplateTemplateParmDecl *TransParam
3915 = cast_or_null<TemplateTemplateParmDecl>(
3916 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3918 return TemplateName();
3920 if (!getDerived().AlwaysRebuild() &&
3921 TransParam == SubstPack->getParameterPack())
3924 return getDerived().RebuildTemplateName(TransParam,
3925 SubstPack->getArgumentPack());
3928 // These should be getting filtered out before they reach the AST.
3929 llvm_unreachable("overloaded function decl survived to here");
3932 template<typename Derived>
3933 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3934 const TemplateArgument &Arg,
3935 TemplateArgumentLoc &Output) {
3936 SourceLocation Loc = getDerived().getBaseLocation();
3937 switch (Arg.getKind()) {
3938 case TemplateArgument::Null:
3939 llvm_unreachable("null template argument in TreeTransform");
3942 case TemplateArgument::Type:
3943 Output = TemplateArgumentLoc(Arg,
3944 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3948 case TemplateArgument::Template:
3949 case TemplateArgument::TemplateExpansion: {
3950 NestedNameSpecifierLocBuilder Builder;
3951 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3952 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3953 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3954 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3955 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3957 if (Arg.getKind() == TemplateArgument::Template)
3958 Output = TemplateArgumentLoc(Arg,
3959 Builder.getWithLocInContext(SemaRef.Context),
3962 Output = TemplateArgumentLoc(Arg,
3963 Builder.getWithLocInContext(SemaRef.Context),
3969 case TemplateArgument::Expression:
3970 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3973 case TemplateArgument::Declaration:
3974 case TemplateArgument::Integral:
3975 case TemplateArgument::Pack:
3976 case TemplateArgument::NullPtr:
3977 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3982 template<typename Derived>
3983 bool TreeTransform<Derived>::TransformTemplateArgument(
3984 const TemplateArgumentLoc &Input,
3985 TemplateArgumentLoc &Output, bool Uneval) {
3986 const TemplateArgument &Arg = Input.getArgument();
3987 switch (Arg.getKind()) {
3988 case TemplateArgument::Null:
3989 case TemplateArgument::Integral:
3990 case TemplateArgument::Pack:
3991 case TemplateArgument::Declaration:
3992 case TemplateArgument::NullPtr:
3993 llvm_unreachable("Unexpected TemplateArgument");
3995 case TemplateArgument::Type: {
3996 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3998 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4000 DI = getDerived().TransformType(DI);
4001 if (!DI) return true;
4003 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4007 case TemplateArgument::Template: {
4008 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4010 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4016 SS.Adopt(QualifierLoc);
4017 TemplateName Template
4018 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
4019 Input.getTemplateNameLoc());
4020 if (Template.isNull())
4023 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
4024 Input.getTemplateNameLoc());
4028 case TemplateArgument::TemplateExpansion:
4029 llvm_unreachable("Caller should expand pack expansions");
4031 case TemplateArgument::Expression: {
4032 // Template argument expressions are constant expressions.
4033 EnterExpressionEvaluationContext Unevaluated(
4035 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4036 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4037 /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4038 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4040 Expr *InputExpr = Input.getSourceExpression();
4041 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4043 ExprResult E = getDerived().TransformExpr(InputExpr);
4044 E = SemaRef.ActOnConstantExpression(E);
4045 if (E.isInvalid()) return true;
4046 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4051 // Work around bogus GCC warning
4055 /// Iterator adaptor that invents template argument location information
4056 /// for each of the template arguments in its underlying iterator.
4057 template<typename Derived, typename InputIterator>
4058 class TemplateArgumentLocInventIterator {
4059 TreeTransform<Derived> &Self;
4063 typedef TemplateArgumentLoc value_type;
4064 typedef TemplateArgumentLoc reference;
4065 typedef typename std::iterator_traits<InputIterator>::difference_type
4067 typedef std::input_iterator_tag iterator_category;
4070 TemplateArgumentLoc Arg;
4073 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4075 const TemplateArgumentLoc *operator->() const { return &Arg; }
4078 TemplateArgumentLocInventIterator() { }
4080 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4082 : Self(Self), Iter(Iter) { }
4084 TemplateArgumentLocInventIterator &operator++() {
4089 TemplateArgumentLocInventIterator operator++(int) {
4090 TemplateArgumentLocInventIterator Old(*this);
4095 reference operator*() const {
4096 TemplateArgumentLoc Result;
4097 Self.InventTemplateArgumentLoc(*Iter, Result);
4101 pointer operator->() const { return pointer(**this); }
4103 friend bool operator==(const TemplateArgumentLocInventIterator &X,
4104 const TemplateArgumentLocInventIterator &Y) {
4105 return X.Iter == Y.Iter;
4108 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4109 const TemplateArgumentLocInventIterator &Y) {
4110 return X.Iter != Y.Iter;
4114 template<typename Derived>
4115 template<typename InputIterator>
4116 bool TreeTransform<Derived>::TransformTemplateArguments(
4117 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4119 for (; First != Last; ++First) {
4120 TemplateArgumentLoc Out;
4121 TemplateArgumentLoc In = *First;
4123 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4124 // Unpack argument packs, which we translate them into separate
4126 // FIXME: We could do much better if we could guarantee that the
4127 // TemplateArgumentLocInfo for the pack expansion would be usable for
4128 // all of the template arguments in the argument pack.
4129 typedef TemplateArgumentLocInventIterator<Derived,
4130 TemplateArgument::pack_iterator>
4132 if (TransformTemplateArguments(PackLocIterator(*this,
4133 In.getArgument().pack_begin()),
4134 PackLocIterator(*this,
4135 In.getArgument().pack_end()),
4142 if (In.getArgument().isPackExpansion()) {
4143 // We have a pack expansion, for which we will be substituting into
4145 SourceLocation Ellipsis;
4146 Optional<unsigned> OrigNumExpansions;
4147 TemplateArgumentLoc Pattern
4148 = getSema().getTemplateArgumentPackExpansionPattern(
4149 In, Ellipsis, OrigNumExpansions);
4151 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4152 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4153 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4155 // Determine whether the set of unexpanded parameter packs can and should
4158 bool RetainExpansion = false;
4159 Optional<unsigned> NumExpansions = OrigNumExpansions;
4160 if (getDerived().TryExpandParameterPacks(Ellipsis,
4161 Pattern.getSourceRange(),
4169 // The transform has determined that we should perform a simple
4170 // transformation on the pack expansion, producing another pack
4172 TemplateArgumentLoc OutPattern;
4173 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4174 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4177 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4179 if (Out.getArgument().isNull())
4182 Outputs.addArgument(Out);
4186 // The transform has determined that we should perform an elementwise
4187 // expansion of the pattern. Do so.
4188 for (unsigned I = 0; I != *NumExpansions; ++I) {
4189 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4191 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4194 if (Out.getArgument().containsUnexpandedParameterPack()) {
4195 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4197 if (Out.getArgument().isNull())
4201 Outputs.addArgument(Out);
4204 // If we're supposed to retain a pack expansion, do so by temporarily
4205 // forgetting the partially-substituted parameter pack.
4206 if (RetainExpansion) {
4207 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4209 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4212 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4214 if (Out.getArgument().isNull())
4217 Outputs.addArgument(Out);
4224 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4227 Outputs.addArgument(Out);
4234 //===----------------------------------------------------------------------===//
4235 // Type transformation
4236 //===----------------------------------------------------------------------===//
4238 template<typename Derived>
4239 QualType TreeTransform<Derived>::TransformType(QualType T) {
4240 if (getDerived().AlreadyTransformed(T))
4243 // Temporary workaround. All of these transformations should
4244 // eventually turn into transformations on TypeLocs.
4245 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4246 getDerived().getBaseLocation());
4248 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4253 return NewDI->getType();
4256 template<typename Derived>
4257 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4258 // Refine the base location to the type's location.
4259 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4260 getDerived().getBaseEntity());
4261 if (getDerived().AlreadyTransformed(DI->getType()))
4266 TypeLoc TL = DI->getTypeLoc();
4267 TLB.reserve(TL.getFullDataSize());
4269 QualType Result = getDerived().TransformType(TLB, TL);
4270 if (Result.isNull())
4273 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4276 template<typename Derived>
4278 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4279 switch (T.getTypeLocClass()) {
4280 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4281 #define TYPELOC(CLASS, PARENT) \
4282 case TypeLoc::CLASS: \
4283 return getDerived().Transform##CLASS##Type(TLB, \
4284 T.castAs<CLASS##TypeLoc>());
4285 #include "clang/AST/TypeLocNodes.def"
4288 llvm_unreachable("unhandled type loc!");
4291 template<typename Derived>
4292 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4293 if (!isa<DependentNameType>(T))
4294 return TransformType(T);
4296 if (getDerived().AlreadyTransformed(T))
4298 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4299 getDerived().getBaseLocation());
4300 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4301 return NewDI ? NewDI->getType() : QualType();
4304 template<typename Derived>
4306 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4307 if (!isa<DependentNameType>(DI->getType()))
4308 return TransformType(DI);
4310 // Refine the base location to the type's location.
4311 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4312 getDerived().getBaseEntity());
4313 if (getDerived().AlreadyTransformed(DI->getType()))
4318 TypeLoc TL = DI->getTypeLoc();
4319 TLB.reserve(TL.getFullDataSize());
4321 auto QTL = TL.getAs<QualifiedTypeLoc>();
4323 TL = QTL.getUnqualifiedLoc();
4325 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4327 QualType Result = getDerived().TransformDependentNameType(
4328 TLB, DNTL, /*DeducedTSTContext*/true);
4329 if (Result.isNull())
4333 Result = getDerived().RebuildQualifiedType(Result, QTL);
4334 if (Result.isNull())
4336 TLB.TypeWasModifiedSafely(Result);
4339 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4342 template<typename Derived>
4344 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4345 QualifiedTypeLoc T) {
4346 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4347 if (Result.isNull())
4350 Result = getDerived().RebuildQualifiedType(Result, T);
4352 if (Result.isNull())
4355 // RebuildQualifiedType might have updated the type, but not in a way
4356 // that invalidates the TypeLoc. (There's no location information for
4358 TLB.TypeWasModifiedSafely(Result);
4363 template <typename Derived>
4364 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4365 QualifiedTypeLoc TL) {
4367 SourceLocation Loc = TL.getBeginLoc();
4368 Qualifiers Quals = TL.getType().getLocalQualifiers();
4370 if (((T.getAddressSpace() != LangAS::Default &&
4371 Quals.getAddressSpace() != LangAS::Default)) &&
4372 T.getAddressSpace() != Quals.getAddressSpace()) {
4373 SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4374 << TL.getType() << T;
4379 // [When] adding cv-qualifications on top of the function type [...] the
4380 // cv-qualifiers are ignored.
4381 if (T->isFunctionType()) {
4382 T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4383 Quals.getAddressSpace());
4388 // when the cv-qualifiers are introduced through the use of a typedef-name
4389 // or decltype-specifier [...] the cv-qualifiers are ignored.
4390 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4391 // applied to a reference type.
4392 if (T->isReferenceType()) {
4393 // The only qualifier that applies to a reference type is restrict.
4394 if (!Quals.hasRestrict())
4396 Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4399 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4401 if (Quals.hasObjCLifetime()) {
4402 if (!T->isObjCLifetimeType() && !T->isDependentType())
4403 Quals.removeObjCLifetime();
4404 else if (T.getObjCLifetime()) {
4406 // A lifetime qualifier applied to a substituted template parameter
4407 // overrides the lifetime qualifier from the template argument.
4408 const AutoType *AutoTy;
4409 if (const SubstTemplateTypeParmType *SubstTypeParam
4410 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4411 QualType Replacement = SubstTypeParam->getReplacementType();
4412 Qualifiers Qs = Replacement.getQualifiers();
4413 Qs.removeObjCLifetime();
4414 Replacement = SemaRef.Context.getQualifiedType(
4415 Replacement.getUnqualifiedType(), Qs);
4416 T = SemaRef.Context.getSubstTemplateTypeParmType(
4417 SubstTypeParam->getReplacedParameter(), Replacement);
4418 } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4419 // 'auto' types behave the same way as template parameters.
4420 QualType Deduced = AutoTy->getDeducedType();
4421 Qualifiers Qs = Deduced.getQualifiers();
4422 Qs.removeObjCLifetime();
4424 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4425 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4426 AutoTy->isDependentType());
4428 // Otherwise, complain about the addition of a qualifier to an
4429 // already-qualified type.
4430 // FIXME: Why is this check not in Sema::BuildQualifiedType?
4431 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4432 Quals.removeObjCLifetime();
4437 return SemaRef.BuildQualifiedType(T, Loc, Quals);
4440 template<typename Derived>
4442 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4443 QualType ObjectType,
4444 NamedDecl *UnqualLookup,
4446 if (getDerived().AlreadyTransformed(TL.getType()))
4449 TypeSourceInfo *TSI =
4450 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4452 return TSI->getTypeLoc();
4456 template<typename Derived>
4458 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4459 QualType ObjectType,
4460 NamedDecl *UnqualLookup,
4462 if (getDerived().AlreadyTransformed(TSInfo->getType()))
4465 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4469 template <typename Derived>
4470 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4471 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4473 QualType T = TL.getType();
4474 assert(!getDerived().AlreadyTransformed(T));
4479 if (isa<TemplateSpecializationType>(T)) {
4480 TemplateSpecializationTypeLoc SpecTL =
4481 TL.castAs<TemplateSpecializationTypeLoc>();
4483 TemplateName Template = getDerived().TransformTemplateName(
4484 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4485 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4486 if (Template.isNull())
4489 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4491 } else if (isa<DependentTemplateSpecializationType>(T)) {
4492 DependentTemplateSpecializationTypeLoc SpecTL =
4493 TL.castAs<DependentTemplateSpecializationTypeLoc>();
4495 TemplateName Template
4496 = getDerived().RebuildTemplateName(SS,
4497 SpecTL.getTemplateKeywordLoc(),
4498 *SpecTL.getTypePtr()->getIdentifier(),
4499 SpecTL.getTemplateNameLoc(),
4500 ObjectType, UnqualLookup,
4501 /*AllowInjectedClassName*/true);
4502 if (Template.isNull())
4505 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4510 // Nothing special needs to be done for these.
4511 Result = getDerived().TransformType(TLB, TL);
4514 if (Result.isNull())
4517 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4520 template <class TyLoc> static inline
4521 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4522 TyLoc NewT = TLB.push<TyLoc>(T.getType());
4523 NewT.setNameLoc(T.getNameLoc());
4527 template<typename Derived>
4528 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4530 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4531 NewT.setBuiltinLoc(T.getBuiltinLoc());
4532 if (T.needsExtraLocalData())
4533 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4537 template<typename Derived>
4538 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4541 return TransformTypeSpecType(TLB, T);
4544 template <typename Derived>
4545 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4546 AdjustedTypeLoc TL) {
4547 // Adjustments applied during transformation are handled elsewhere.
4548 return getDerived().TransformType(TLB, TL.getOriginalLoc());
4551 template<typename Derived>
4552 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4553 DecayedTypeLoc TL) {
4554 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4555 if (OriginalType.isNull())
4558 QualType Result = TL.getType();
4559 if (getDerived().AlwaysRebuild() ||
4560 OriginalType != TL.getOriginalLoc().getType())
4561 Result = SemaRef.Context.getDecayedType(OriginalType);
4562 TLB.push<DecayedTypeLoc>(Result);
4563 // Nothing to set for DecayedTypeLoc.
4567 /// Helper to deduce addr space of a pointee type in OpenCL mode.
4568 /// If the type is updated it will be overwritten in PointeeType param.
4569 static void deduceOpenCLPointeeAddrSpace(Sema &SemaRef, QualType &PointeeType) {
4570 if (PointeeType.getAddressSpace() == LangAS::Default)
4571 PointeeType = SemaRef.Context.getAddrSpaceQualType(PointeeType,
4572 LangAS::opencl_generic);
4575 template<typename Derived>
4576 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4577 PointerTypeLoc TL) {
4578 QualType PointeeType
4579 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4580 if (PointeeType.isNull())
4583 if (SemaRef.getLangOpts().OpenCL)
4584 deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4586 QualType Result = TL.getType();
4587 if (PointeeType->getAs<ObjCObjectType>()) {
4588 // A dependent pointer type 'T *' has is being transformed such
4589 // that an Objective-C class type is being replaced for 'T'. The
4590 // resulting pointer type is an ObjCObjectPointerType, not a
4592 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4594 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4595 NewT.setStarLoc(TL.getStarLoc());
4599 if (getDerived().AlwaysRebuild() ||
4600 PointeeType != TL.getPointeeLoc().getType()) {
4601 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4602 if (Result.isNull())
4606 // Objective-C ARC can add lifetime qualifiers to the type that we're
4608 TLB.TypeWasModifiedSafely(Result->getPointeeType());
4610 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4611 NewT.setSigilLoc(TL.getSigilLoc());
4615 template<typename Derived>
4617 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4618 BlockPointerTypeLoc TL) {
4619 QualType PointeeType
4620 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4621 if (PointeeType.isNull())
4624 if (SemaRef.getLangOpts().OpenCL)
4625 deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4627 QualType Result = TL.getType();
4628 if (getDerived().AlwaysRebuild() ||
4629 PointeeType != TL.getPointeeLoc().getType()) {
4630 Result = getDerived().RebuildBlockPointerType(PointeeType,
4632 if (Result.isNull())
4636 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4637 NewT.setSigilLoc(TL.getSigilLoc());
4641 /// Transforms a reference type. Note that somewhat paradoxically we
4642 /// don't care whether the type itself is an l-value type or an r-value
4643 /// type; we only care if the type was *written* as an l-value type
4644 /// or an r-value type.
4645 template<typename Derived>
4647 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4648 ReferenceTypeLoc TL) {
4649 const ReferenceType *T = TL.getTypePtr();
4651 // Note that this works with the pointee-as-written.
4652 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4653 if (PointeeType.isNull())
4656 if (SemaRef.getLangOpts().OpenCL)
4657 deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4659 QualType Result = TL.getType();
4660 if (getDerived().AlwaysRebuild() ||
4661 PointeeType != T->getPointeeTypeAsWritten()) {
4662 Result = getDerived().RebuildReferenceType(PointeeType,
4663 T->isSpelledAsLValue(),
4665 if (Result.isNull())
4669 // Objective-C ARC can add lifetime qualifiers to the type that we're
4671 TLB.TypeWasModifiedSafely(
4672 Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
4674 // r-value references can be rebuilt as l-value references.
4675 ReferenceTypeLoc NewTL;
4676 if (isa<LValueReferenceType>(Result))
4677 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4679 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4680 NewTL.setSigilLoc(TL.getSigilLoc());
4685 template<typename Derived>
4687 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4688 LValueReferenceTypeLoc TL) {
4689 return TransformReferenceType(TLB, TL);
4692 template<typename Derived>
4694 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4695 RValueReferenceTypeLoc TL) {
4696 return TransformReferenceType(TLB, TL);
4699 template<typename Derived>
4701 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4702 MemberPointerTypeLoc TL) {
4703 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4704 if (PointeeType.isNull())
4707 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4708 TypeSourceInfo *NewClsTInfo = nullptr;
4710 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4715 const MemberPointerType *T = TL.getTypePtr();
4716 QualType OldClsType = QualType(T->getClass(), 0);
4717 QualType NewClsType;
4719 NewClsType = NewClsTInfo->getType();
4721 NewClsType = getDerived().TransformType(OldClsType);
4722 if (NewClsType.isNull())
4726 QualType Result = TL.getType();
4727 if (getDerived().AlwaysRebuild() ||
4728 PointeeType != T->getPointeeType() ||
4729 NewClsType != OldClsType) {
4730 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4732 if (Result.isNull())
4736 // If we had to adjust the pointee type when building a member pointer, make
4737 // sure to push TypeLoc info for it.
4738 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4739 if (MPT && PointeeType != MPT->getPointeeType()) {
4740 assert(isa<AdjustedType>(MPT->getPointeeType()));
4741 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4744 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4745 NewTL.setSigilLoc(TL.getSigilLoc());
4746 NewTL.setClassTInfo(NewClsTInfo);
4751 template<typename Derived>
4753 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4754 ConstantArrayTypeLoc TL) {
4755 const ConstantArrayType *T = TL.getTypePtr();
4756 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4757 if (ElementType.isNull())
4760 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4761 Expr *OldSize = TL.getSizeExpr();
4763 OldSize = const_cast<Expr*>(T->getSizeExpr());
4764 Expr *NewSize = nullptr;
4766 EnterExpressionEvaluationContext Unevaluated(
4767 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4768 NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
4769 NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
4772 QualType Result = TL.getType();
4773 if (getDerived().AlwaysRebuild() ||
4774 ElementType != T->getElementType() ||
4775 (T->getSizeExpr() && NewSize != OldSize)) {
4776 Result = getDerived().RebuildConstantArrayType(ElementType,
4777 T->getSizeModifier(),
4778 T->getSize(), NewSize,
4779 T->getIndexTypeCVRQualifiers(),
4780 TL.getBracketsRange());
4781 if (Result.isNull())
4785 // We might have either a ConstantArrayType or a VariableArrayType now:
4786 // a ConstantArrayType is allowed to have an element type which is a
4787 // VariableArrayType if the type is dependent. Fortunately, all array
4788 // types have the same location layout.
4789 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4790 NewTL.setLBracketLoc(TL.getLBracketLoc());
4791 NewTL.setRBracketLoc(TL.getRBracketLoc());
4792 NewTL.setSizeExpr(NewSize);
4797 template<typename Derived>
4798 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4799 TypeLocBuilder &TLB,
4800 IncompleteArrayTypeLoc TL) {
4801 const IncompleteArrayType *T = TL.getTypePtr();
4802 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4803 if (ElementType.isNull())
4806 QualType Result = TL.getType();
4807 if (getDerived().AlwaysRebuild() ||
4808 ElementType != T->getElementType()) {
4809 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4810 T->getSizeModifier(),
4811 T->getIndexTypeCVRQualifiers(),
4812 TL.getBracketsRange());
4813 if (Result.isNull())
4817 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4818 NewTL.setLBracketLoc(TL.getLBracketLoc());
4819 NewTL.setRBracketLoc(TL.getRBracketLoc());
4820 NewTL.setSizeExpr(nullptr);
4825 template<typename Derived>
4827 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4828 VariableArrayTypeLoc TL) {
4829 const VariableArrayType *T = TL.getTypePtr();
4830 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4831 if (ElementType.isNull())
4834 ExprResult SizeResult;
4836 EnterExpressionEvaluationContext Context(
4837 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4838 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4840 if (SizeResult.isInvalid())
4843 SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
4844 if (SizeResult.isInvalid())
4847 Expr *Size = SizeResult.get();
4849 QualType Result = TL.getType();
4850 if (getDerived().AlwaysRebuild() ||
4851 ElementType != T->getElementType() ||
4852 Size != T->getSizeExpr()) {
4853 Result = getDerived().RebuildVariableArrayType(ElementType,
4854 T->getSizeModifier(),
4856 T->getIndexTypeCVRQualifiers(),
4857 TL.getBracketsRange());
4858 if (Result.isNull())
4862 // We might have constant size array now, but fortunately it has the same
4864 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4865 NewTL.setLBracketLoc(TL.getLBracketLoc());
4866 NewTL.setRBracketLoc(TL.getRBracketLoc());
4867 NewTL.setSizeExpr(Size);
4872 template<typename Derived>
4874 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4875 DependentSizedArrayTypeLoc TL) {
4876 const DependentSizedArrayType *T = TL.getTypePtr();
4877 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4878 if (ElementType.isNull())
4881 // Array bounds are constant expressions.
4882 EnterExpressionEvaluationContext Unevaluated(
4883 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4885 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4886 Expr *origSize = TL.getSizeExpr();
4887 if (!origSize) origSize = T->getSizeExpr();
4889 ExprResult sizeResult
4890 = getDerived().TransformExpr(origSize);
4891 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4892 if (sizeResult.isInvalid())
4895 Expr *size = sizeResult.get();
4897 QualType Result = TL.getType();
4898 if (getDerived().AlwaysRebuild() ||
4899 ElementType != T->getElementType() ||
4901 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4902 T->getSizeModifier(),
4904 T->getIndexTypeCVRQualifiers(),
4905 TL.getBracketsRange());
4906 if (Result.isNull())
4910 // We might have any sort of array type now, but fortunately they
4911 // all have the same location layout.
4912 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4913 NewTL.setLBracketLoc(TL.getLBracketLoc());
4914 NewTL.setRBracketLoc(TL.getRBracketLoc());
4915 NewTL.setSizeExpr(size);
4920 template <typename Derived>
4921 QualType TreeTransform<Derived>::TransformDependentVectorType(
4922 TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4923 const DependentVectorType *T = TL.getTypePtr();
4924 QualType ElementType = getDerived().TransformType(T->getElementType());
4925 if (ElementType.isNull())
4928 EnterExpressionEvaluationContext Unevaluated(
4929 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4931 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4932 Size = SemaRef.ActOnConstantExpression(Size);
4933 if (Size.isInvalid())
4936 QualType Result = TL.getType();
4937 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
4938 Size.get() != T->getSizeExpr()) {
4939 Result = getDerived().RebuildDependentVectorType(
4940 ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
4941 if (Result.isNull())
4945 // Result might be dependent or not.
4946 if (isa<DependentVectorType>(Result)) {
4947 DependentVectorTypeLoc NewTL =
4948 TLB.push<DependentVectorTypeLoc>(Result);
4949 NewTL.setNameLoc(TL.getNameLoc());
4951 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4952 NewTL.setNameLoc(TL.getNameLoc());
4958 template<typename Derived>
4959 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4960 TypeLocBuilder &TLB,
4961 DependentSizedExtVectorTypeLoc TL) {
4962 const DependentSizedExtVectorType *T = TL.getTypePtr();
4964 // FIXME: ext vector locs should be nested
4965 QualType ElementType = getDerived().TransformType(T->getElementType());
4966 if (ElementType.isNull())
4969 // Vector sizes are constant expressions.
4970 EnterExpressionEvaluationContext Unevaluated(
4971 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4973 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4974 Size = SemaRef.ActOnConstantExpression(Size);
4975 if (Size.isInvalid())
4978 QualType Result = TL.getType();
4979 if (getDerived().AlwaysRebuild() ||
4980 ElementType != T->getElementType() ||
4981 Size.get() != T->getSizeExpr()) {
4982 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4984 T->getAttributeLoc());
4985 if (Result.isNull())
4989 // Result might be dependent or not.
4990 if (isa<DependentSizedExtVectorType>(Result)) {
4991 DependentSizedExtVectorTypeLoc NewTL
4992 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4993 NewTL.setNameLoc(TL.getNameLoc());
4995 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4996 NewTL.setNameLoc(TL.getNameLoc());
5002 template <typename Derived>
5003 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5004 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5005 const DependentAddressSpaceType *T = TL.getTypePtr();
5007 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5009 if (pointeeType.isNull())
5012 // Address spaces are constant expressions.
5013 EnterExpressionEvaluationContext Unevaluated(
5014 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5016 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5017 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5018 if (AddrSpace.isInvalid())
5021 QualType Result = TL.getType();
5022 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5023 AddrSpace.get() != T->getAddrSpaceExpr()) {
5024 Result = getDerived().RebuildDependentAddressSpaceType(
5025 pointeeType, AddrSpace.get(), T->getAttributeLoc());
5026 if (Result.isNull())
5030 // Result might be dependent or not.
5031 if (isa<DependentAddressSpaceType>(Result)) {
5032 DependentAddressSpaceTypeLoc NewTL =
5033 TLB.push<DependentAddressSpaceTypeLoc>(Result);
5035 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5036 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5037 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5040 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5041 Result, getDerived().getBaseLocation());
5042 TransformType(TLB, DI->getTypeLoc());
5048 template <typename Derived>
5049 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5051 const VectorType *T = TL.getTypePtr();
5052 QualType ElementType = getDerived().TransformType(T->getElementType());
5053 if (ElementType.isNull())
5056 QualType Result = TL.getType();
5057 if (getDerived().AlwaysRebuild() ||
5058 ElementType != T->getElementType()) {
5059 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5060 T->getVectorKind());
5061 if (Result.isNull())
5065 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5066 NewTL.setNameLoc(TL.getNameLoc());
5071 template<typename Derived>
5072 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5073 ExtVectorTypeLoc TL) {
5074 const VectorType *T = TL.getTypePtr();
5075 QualType ElementType = getDerived().TransformType(T->getElementType());
5076 if (ElementType.isNull())
5079 QualType Result = TL.getType();
5080 if (getDerived().AlwaysRebuild() ||
5081 ElementType != T->getElementType()) {
5082 Result = getDerived().RebuildExtVectorType(ElementType,
5083 T->getNumElements(),
5084 /*FIXME*/ SourceLocation());
5085 if (Result.isNull())
5089 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5090 NewTL.setNameLoc(TL.getNameLoc());
5095 template <typename Derived>
5096 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5097 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5098 bool ExpectParameterPack) {
5099 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5100 TypeSourceInfo *NewDI = nullptr;
5102 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5103 // If we're substituting into a pack expansion type and we know the
5104 // length we want to expand to, just substitute for the pattern.
5105 TypeLoc OldTL = OldDI->getTypeLoc();
5106 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5109 TypeLoc NewTL = OldDI->getTypeLoc();
5110 TLB.reserve(NewTL.getFullDataSize());
5112 QualType Result = getDerived().TransformType(TLB,
5113 OldExpansionTL.getPatternLoc());
5114 if (Result.isNull())
5117 Result = RebuildPackExpansionType(Result,
5118 OldExpansionTL.getPatternLoc().getSourceRange(),
5119 OldExpansionTL.getEllipsisLoc(),
5121 if (Result.isNull())
5124 PackExpansionTypeLoc NewExpansionTL
5125 = TLB.push<PackExpansionTypeLoc>(Result);
5126 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5127 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5129 NewDI = getDerived().TransformType(OldDI);
5133 if (NewDI == OldDI && indexAdjustment == 0)
5136 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5137 OldParm->getDeclContext(),
5138 OldParm->getInnerLocStart(),
5139 OldParm->getLocation(),
5140 OldParm->getIdentifier(),
5143 OldParm->getStorageClass(),
5144 /* DefArg */ nullptr);
5145 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5146 OldParm->getFunctionScopeIndex() + indexAdjustment);
5150 template <typename Derived>
5151 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5152 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5153 const QualType *ParamTypes,
5154 const FunctionProtoType::ExtParameterInfo *ParamInfos,
5155 SmallVectorImpl<QualType> &OutParamTypes,
5156 SmallVectorImpl<ParmVarDecl *> *PVars,
5157 Sema::ExtParameterInfoBuilder &PInfos) {
5158 int indexAdjustment = 0;
5160 unsigned NumParams = Params.size();
5161 for (unsigned i = 0; i != NumParams; ++i) {
5162 if (ParmVarDecl *OldParm = Params[i]) {
5163 assert(OldParm->getFunctionScopeIndex() == i);
5165 Optional<unsigned> NumExpansions;
5166 ParmVarDecl *NewParm = nullptr;
5167 if (OldParm->isParameterPack()) {
5168 // We have a function parameter pack that may need to be expanded.
5169 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5171 // Find the parameter packs that could be expanded.
5172 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5173 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5174 TypeLoc Pattern = ExpansionTL.getPatternLoc();
5175 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5176 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
5178 // Determine whether we should expand the parameter packs.
5179 bool ShouldExpand = false;
5180 bool RetainExpansion = false;
5181 Optional<unsigned> OrigNumExpansions =
5182 ExpansionTL.getTypePtr()->getNumExpansions();
5183 NumExpansions = OrigNumExpansions;
5184 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5185 Pattern.getSourceRange(),
5194 // Expand the function parameter pack into multiple, separate
5196 getDerived().ExpandingFunctionParameterPack(OldParm);
5197 for (unsigned I = 0; I != *NumExpansions; ++I) {
5198 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5199 ParmVarDecl *NewParm
5200 = getDerived().TransformFunctionTypeParam(OldParm,
5203 /*ExpectParameterPack=*/false);
5208 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5209 OutParamTypes.push_back(NewParm->getType());
5211 PVars->push_back(NewParm);
5214 // If we're supposed to retain a pack expansion, do so by temporarily
5215 // forgetting the partially-substituted parameter pack.
5216 if (RetainExpansion) {
5217 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5218 ParmVarDecl *NewParm
5219 = getDerived().TransformFunctionTypeParam(OldParm,
5222 /*ExpectParameterPack=*/false);
5227 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5228 OutParamTypes.push_back(NewParm->getType());
5230 PVars->push_back(NewParm);
5233 // The next parameter should have the same adjustment as the
5234 // last thing we pushed, but we post-incremented indexAdjustment
5235 // on every push. Also, if we push nothing, the adjustment should
5239 // We're done with the pack expansion.
5243 // We'll substitute the parameter now without expanding the pack
5245 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5246 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5249 /*ExpectParameterPack=*/true);
5251 NewParm = getDerived().TransformFunctionTypeParam(
5252 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5259 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5260 OutParamTypes.push_back(NewParm->getType());
5262 PVars->push_back(NewParm);
5266 // Deal with the possibility that we don't have a parameter
5267 // declaration for this parameter.
5268 QualType OldType = ParamTypes[i];
5269 bool IsPackExpansion = false;
5270 Optional<unsigned> NumExpansions;
5272 if (const PackExpansionType *Expansion
5273 = dyn_cast<PackExpansionType>(OldType)) {
5274 // We have a function parameter pack that may need to be expanded.
5275 QualType Pattern = Expansion->getPattern();
5276 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5277 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5279 // Determine whether we should expand the parameter packs.
5280 bool ShouldExpand = false;
5281 bool RetainExpansion = false;
5282 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5291 // Expand the function parameter pack into multiple, separate
5293 for (unsigned I = 0; I != *NumExpansions; ++I) {
5294 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5295 QualType NewType = getDerived().TransformType(Pattern);
5296 if (NewType.isNull())
5299 if (NewType->containsUnexpandedParameterPack()) {
5301 getSema().getASTContext().getPackExpansionType(NewType, None);
5303 if (NewType.isNull())
5308 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5309 OutParamTypes.push_back(NewType);
5311 PVars->push_back(nullptr);
5314 // We're done with the pack expansion.
5318 // If we're supposed to retain a pack expansion, do so by temporarily
5319 // forgetting the partially-substituted parameter pack.
5320 if (RetainExpansion) {
5321 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5322 QualType NewType = getDerived().TransformType(Pattern);
5323 if (NewType.isNull())
5327 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5328 OutParamTypes.push_back(NewType);
5330 PVars->push_back(nullptr);
5333 // We'll substitute the parameter now without expanding the pack
5335 OldType = Expansion->getPattern();
5336 IsPackExpansion = true;
5337 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5338 NewType = getDerived().TransformType(OldType);
5340 NewType = getDerived().TransformType(OldType);
5343 if (NewType.isNull())
5346 if (IsPackExpansion)
5347 NewType = getSema().Context.getPackExpansionType(NewType,
5351 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5352 OutParamTypes.push_back(NewType);
5354 PVars->push_back(nullptr);
5359 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5360 if (ParmVarDecl *parm = (*PVars)[i])
5361 assert(parm->getFunctionScopeIndex() == i);
5368 template<typename Derived>
5370 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5371 FunctionProtoTypeLoc TL) {
5372 SmallVector<QualType, 4> ExceptionStorage;
5373 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5374 return getDerived().TransformFunctionProtoType(
5375 TLB, TL, nullptr, Qualifiers(),
5376 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5377 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5378 ExceptionStorage, Changed);
5382 template<typename Derived> template<typename Fn>
5383 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5384 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5385 Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5387 // Transform the parameters and return type.
5389 // We are required to instantiate the params and return type in source order.
5390 // When the function has a trailing return type, we instantiate the
5391 // parameters before the return type, since the return type can then refer
5392 // to the parameters themselves (via decltype, sizeof, etc.).
5394 SmallVector<QualType, 4> ParamTypes;
5395 SmallVector<ParmVarDecl*, 4> ParamDecls;
5396 Sema::ExtParameterInfoBuilder ExtParamInfos;
5397 const FunctionProtoType *T = TL.getTypePtr();
5399 QualType ResultType;
5401 if (T->hasTrailingReturn()) {
5402 if (getDerived().TransformFunctionTypeParams(
5403 TL.getBeginLoc(), TL.getParams(),
5404 TL.getTypePtr()->param_type_begin(),
5405 T->getExtParameterInfosOrNull(),
5406 ParamTypes, &ParamDecls, ExtParamInfos))
5410 // C++11 [expr.prim.general]p3:
5411 // If a declaration declares a member function or member function
5412 // template of a class X, the expression this is a prvalue of type
5413 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5414 // and the end of the function-definition, member-declarator, or
5416 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5418 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5419 if (ResultType.isNull())
5424 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5425 if (ResultType.isNull())
5428 if (getDerived().TransformFunctionTypeParams(
5429 TL.getBeginLoc(), TL.getParams(),
5430 TL.getTypePtr()->param_type_begin(),
5431 T->getExtParameterInfosOrNull(),
5432 ParamTypes, &ParamDecls, ExtParamInfos))
5436 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5438 bool EPIChanged = false;
5439 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5442 // Handle extended parameter information.
5443 if (auto NewExtParamInfos =
5444 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5445 if (!EPI.ExtParameterInfos ||
5446 llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5447 != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5450 EPI.ExtParameterInfos = NewExtParamInfos;
5451 } else if (EPI.ExtParameterInfos) {
5453 EPI.ExtParameterInfos = nullptr;
5456 QualType Result = TL.getType();
5457 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5458 T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5459 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5460 if (Result.isNull())
5464 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5465 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5466 NewTL.setLParenLoc(TL.getLParenLoc());
5467 NewTL.setRParenLoc(TL.getRParenLoc());
5468 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5469 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5470 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5471 NewTL.setParam(i, ParamDecls[i]);
5476 template<typename Derived>
5477 bool TreeTransform<Derived>::TransformExceptionSpec(
5478 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5479 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5480 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5482 // Instantiate a dynamic noexcept expression, if any.
5483 if (isComputedNoexcept(ESI.Type)) {
5484 EnterExpressionEvaluationContext Unevaluated(
5485 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5486 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5487 if (NoexceptExpr.isInvalid())
5490 ExceptionSpecificationType EST = ESI.Type;
5492 getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5493 if (NoexceptExpr.isInvalid())
5496 if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5498 ESI.NoexceptExpr = NoexceptExpr.get();
5502 if (ESI.Type != EST_Dynamic)
5505 // Instantiate a dynamic exception specification's type.
5506 for (QualType T : ESI.Exceptions) {
5507 if (const PackExpansionType *PackExpansion =
5508 T->getAs<PackExpansionType>()) {
5511 // We have a pack expansion. Instantiate it.
5512 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5513 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5515 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5517 // Determine whether the set of unexpanded parameter packs can and
5520 bool Expand = false;
5521 bool RetainExpansion = false;
5522 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5523 // FIXME: Track the location of the ellipsis (and track source location
5524 // information for the types in the exception specification in general).
5525 if (getDerived().TryExpandParameterPacks(
5526 Loc, SourceRange(), Unexpanded, Expand,
5527 RetainExpansion, NumExpansions))
5531 // We can't expand this pack expansion into separate arguments yet;
5532 // just substitute into the pattern and create a new pack expansion
5534 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5535 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5539 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5540 Exceptions.push_back(U);
5544 // Substitute into the pack expansion pattern for each slice of the
5546 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5547 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5549 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5550 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5553 Exceptions.push_back(U);
5556 QualType U = getDerived().TransformType(T);
5557 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5562 Exceptions.push_back(U);
5566 ESI.Exceptions = Exceptions;
5567 if (ESI.Exceptions.empty())
5568 ESI.Type = EST_DynamicNone;
5572 template<typename Derived>
5573 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5574 TypeLocBuilder &TLB,
5575 FunctionNoProtoTypeLoc TL) {
5576 const FunctionNoProtoType *T = TL.getTypePtr();
5577 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5578 if (ResultType.isNull())
5581 QualType Result = TL.getType();
5582 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5583 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5585 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5586 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5587 NewTL.setLParenLoc(TL.getLParenLoc());
5588 NewTL.setRParenLoc(TL.getRParenLoc());
5589 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5594 template<typename Derived> QualType
5595 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5596 UnresolvedUsingTypeLoc TL) {
5597 const UnresolvedUsingType *T = TL.getTypePtr();
5598 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5602 QualType Result = TL.getType();
5603 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5604 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5605 if (Result.isNull())
5609 // We might get an arbitrary type spec type back. We should at
5610 // least always get a type spec type, though.
5611 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5612 NewTL.setNameLoc(TL.getNameLoc());
5617 template<typename Derived>
5618 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5619 TypedefTypeLoc TL) {
5620 const TypedefType *T = TL.getTypePtr();
5621 TypedefNameDecl *Typedef
5622 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5627 QualType Result = TL.getType();
5628 if (getDerived().AlwaysRebuild() ||
5629 Typedef != T->getDecl()) {
5630 Result = getDerived().RebuildTypedefType(Typedef);
5631 if (Result.isNull())
5635 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5636 NewTL.setNameLoc(TL.getNameLoc());
5641 template<typename Derived>
5642 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5643 TypeOfExprTypeLoc TL) {
5644 // typeof expressions are not potentially evaluated contexts
5645 EnterExpressionEvaluationContext Unevaluated(
5646 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5647 Sema::ReuseLambdaContextDecl);
5649 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5653 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5657 QualType Result = TL.getType();
5658 if (getDerived().AlwaysRebuild() ||
5659 E.get() != TL.getUnderlyingExpr()) {
5660 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5661 if (Result.isNull())
5666 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5667 NewTL.setTypeofLoc(TL.getTypeofLoc());
5668 NewTL.setLParenLoc(TL.getLParenLoc());
5669 NewTL.setRParenLoc(TL.getRParenLoc());
5674 template<typename Derived>
5675 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5677 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5678 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5682 QualType Result = TL.getType();
5683 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5684 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5685 if (Result.isNull())
5689 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5690 NewTL.setTypeofLoc(TL.getTypeofLoc());
5691 NewTL.setLParenLoc(TL.getLParenLoc());
5692 NewTL.setRParenLoc(TL.getRParenLoc());
5693 NewTL.setUnderlyingTInfo(New_Under_TI);
5698 template<typename Derived>
5699 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5700 DecltypeTypeLoc TL) {
5701 const DecltypeType *T = TL.getTypePtr();
5703 // decltype expressions are not potentially evaluated contexts
5704 EnterExpressionEvaluationContext Unevaluated(
5705 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5706 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5708 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5712 E = getSema().ActOnDecltypeExpression(E.get());
5716 QualType Result = TL.getType();
5717 if (getDerived().AlwaysRebuild() ||
5718 E.get() != T->getUnderlyingExpr()) {
5719 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5720 if (Result.isNull())
5725 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5726 NewTL.setNameLoc(TL.getNameLoc());
5731 template<typename Derived>
5732 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5733 TypeLocBuilder &TLB,
5734 UnaryTransformTypeLoc TL) {
5735 QualType Result = TL.getType();
5736 if (Result->isDependentType()) {
5737 const UnaryTransformType *T = TL.getTypePtr();
5739 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5740 Result = getDerived().RebuildUnaryTransformType(NewBase,
5743 if (Result.isNull())
5747 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5748 NewTL.setKWLoc(TL.getKWLoc());
5749 NewTL.setParensRange(TL.getParensRange());
5750 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5754 template<typename Derived>
5755 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5757 const AutoType *T = TL.getTypePtr();
5758 QualType OldDeduced = T->getDeducedType();
5759 QualType NewDeduced;
5760 if (!OldDeduced.isNull()) {
5761 NewDeduced = getDerived().TransformType(OldDeduced);
5762 if (NewDeduced.isNull())
5766 QualType Result = TL.getType();
5767 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5768 T->isDependentType()) {
5769 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5770 if (Result.isNull())
5774 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5775 NewTL.setNameLoc(TL.getNameLoc());
5780 template<typename Derived>
5781 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5782 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5783 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5786 TemplateName TemplateName = getDerived().TransformTemplateName(
5787 SS, T->getTemplateName(), TL.getTemplateNameLoc());
5788 if (TemplateName.isNull())
5791 QualType OldDeduced = T->getDeducedType();
5792 QualType NewDeduced;
5793 if (!OldDeduced.isNull()) {
5794 NewDeduced = getDerived().TransformType(OldDeduced);
5795 if (NewDeduced.isNull())
5799 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5800 TemplateName, NewDeduced);
5801 if (Result.isNull())
5804 DeducedTemplateSpecializationTypeLoc NewTL =
5805 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5806 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5811 template<typename Derived>
5812 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5814 const RecordType *T = TL.getTypePtr();
5816 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5821 QualType Result = TL.getType();
5822 if (getDerived().AlwaysRebuild() ||
5823 Record != T->getDecl()) {
5824 Result = getDerived().RebuildRecordType(Record);
5825 if (Result.isNull())
5829 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5830 NewTL.setNameLoc(TL.getNameLoc());
5835 template<typename Derived>
5836 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5838 const EnumType *T = TL.getTypePtr();
5840 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5845 QualType Result = TL.getType();
5846 if (getDerived().AlwaysRebuild() ||
5847 Enum != T->getDecl()) {
5848 Result = getDerived().RebuildEnumType(Enum);
5849 if (Result.isNull())
5853 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5854 NewTL.setNameLoc(TL.getNameLoc());
5859 template<typename Derived>
5860 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5861 TypeLocBuilder &TLB,
5862 InjectedClassNameTypeLoc TL) {
5863 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5864 TL.getTypePtr()->getDecl());
5865 if (!D) return QualType();
5867 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5868 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5872 template<typename Derived>
5873 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5874 TypeLocBuilder &TLB,
5875 TemplateTypeParmTypeLoc TL) {
5876 return TransformTypeSpecType(TLB, TL);
5879 template<typename Derived>
5880 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5881 TypeLocBuilder &TLB,
5882 SubstTemplateTypeParmTypeLoc TL) {
5883 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5885 // Substitute into the replacement type, which itself might involve something
5886 // that needs to be transformed. This only tends to occur with default
5887 // template arguments of template template parameters.
5888 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5889 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5890 if (Replacement.isNull())
5893 // Always canonicalize the replacement type.
5894 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5896 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5899 // Propagate type-source information.
5900 SubstTemplateTypeParmTypeLoc NewTL
5901 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5902 NewTL.setNameLoc(TL.getNameLoc());
5907 template<typename Derived>
5908 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5909 TypeLocBuilder &TLB,
5910 SubstTemplateTypeParmPackTypeLoc TL) {
5911 return TransformTypeSpecType(TLB, TL);
5914 template<typename Derived>
5915 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5916 TypeLocBuilder &TLB,
5917 TemplateSpecializationTypeLoc TL) {
5918 const TemplateSpecializationType *T = TL.getTypePtr();
5920 // The nested-name-specifier never matters in a TemplateSpecializationType,
5921 // because we can't have a dependent nested-name-specifier anyway.
5923 TemplateName Template
5924 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5925 TL.getTemplateNameLoc());
5926 if (Template.isNull())
5929 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5932 template<typename Derived>
5933 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5935 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5936 if (ValueType.isNull())
5939 QualType Result = TL.getType();
5940 if (getDerived().AlwaysRebuild() ||
5941 ValueType != TL.getValueLoc().getType()) {
5942 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5943 if (Result.isNull())
5947 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5948 NewTL.setKWLoc(TL.getKWLoc());
5949 NewTL.setLParenLoc(TL.getLParenLoc());
5950 NewTL.setRParenLoc(TL.getRParenLoc());
5955 template <typename Derived>
5956 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5958 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5959 if (ValueType.isNull())
5962 QualType Result = TL.getType();
5963 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5964 const PipeType *PT = Result->castAs<PipeType>();
5965 bool isReadPipe = PT->isReadOnly();
5966 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5967 if (Result.isNull())
5971 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5972 NewTL.setKWLoc(TL.getKWLoc());
5977 /// Simple iterator that traverses the template arguments in a
5978 /// container that provides a \c getArgLoc() member function.
5980 /// This iterator is intended to be used with the iterator form of
5981 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5982 template<typename ArgLocContainer>
5983 class TemplateArgumentLocContainerIterator {
5984 ArgLocContainer *Container;
5988 typedef TemplateArgumentLoc value_type;
5989 typedef TemplateArgumentLoc reference;
5990 typedef int difference_type;
5991 typedef std::input_iterator_tag iterator_category;
5994 TemplateArgumentLoc Arg;
5997 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5999 const TemplateArgumentLoc *operator->() const {
6005 TemplateArgumentLocContainerIterator() {}
6007 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6009 : Container(&Container), Index(Index) { }
6011 TemplateArgumentLocContainerIterator &operator++() {
6016 TemplateArgumentLocContainerIterator operator++(int) {
6017 TemplateArgumentLocContainerIterator Old(*this);
6022 TemplateArgumentLoc operator*() const {
6023 return Container->getArgLoc(Index);
6026 pointer operator->() const {
6027 return pointer(Container->getArgLoc(Index));
6030 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6031 const TemplateArgumentLocContainerIterator &Y) {
6032 return X.Container == Y.Container && X.Index == Y.Index;
6035 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6036 const TemplateArgumentLocContainerIterator &Y) {
6042 template <typename Derived>
6043 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6044 TypeLocBuilder &TLB,
6045 TemplateSpecializationTypeLoc TL,
6046 TemplateName Template) {
6047 TemplateArgumentListInfo NewTemplateArgs;
6048 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6049 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6050 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6052 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6053 ArgIterator(TL, TL.getNumArgs()),
6057 // FIXME: maybe don't rebuild if all the template arguments are the same.
6060 getDerived().RebuildTemplateSpecializationType(Template,
6061 TL.getTemplateNameLoc(),
6064 if (!Result.isNull()) {
6065 // Specializations of template template parameters are represented as
6066 // TemplateSpecializationTypes, and substitution of type alias templates
6067 // within a dependent context can transform them into
6068 // DependentTemplateSpecializationTypes.
6069 if (isa<DependentTemplateSpecializationType>(Result)) {
6070 DependentTemplateSpecializationTypeLoc NewTL
6071 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6072 NewTL.setElaboratedKeywordLoc(SourceLocation());
6073 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6074 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6075 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6076 NewTL.setLAngleLoc(TL.getLAngleLoc());
6077 NewTL.setRAngleLoc(TL.getRAngleLoc());
6078 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6079 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6083 TemplateSpecializationTypeLoc NewTL
6084 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6085 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6086 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6087 NewTL.setLAngleLoc(TL.getLAngleLoc());
6088 NewTL.setRAngleLoc(TL.getRAngleLoc());
6089 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6090 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6096 template <typename Derived>
6097 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6098 TypeLocBuilder &TLB,
6099 DependentTemplateSpecializationTypeLoc TL,
6100 TemplateName Template,
6102 TemplateArgumentListInfo NewTemplateArgs;
6103 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6104 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6105 typedef TemplateArgumentLocContainerIterator<
6106 DependentTemplateSpecializationTypeLoc> ArgIterator;
6107 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6108 ArgIterator(TL, TL.getNumArgs()),
6112 // FIXME: maybe don't rebuild if all the template arguments are the same.
6114 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6116 = getSema().Context.getDependentTemplateSpecializationType(
6117 TL.getTypePtr()->getKeyword(),
6118 DTN->getQualifier(),
6119 DTN->getIdentifier(),
6122 DependentTemplateSpecializationTypeLoc NewTL
6123 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6124 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6125 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6126 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6127 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6128 NewTL.setLAngleLoc(TL.getLAngleLoc());
6129 NewTL.setRAngleLoc(TL.getRAngleLoc());
6130 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6131 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6136 = getDerived().RebuildTemplateSpecializationType(Template,
6137 TL.getTemplateNameLoc(),
6140 if (!Result.isNull()) {
6141 /// FIXME: Wrap this in an elaborated-type-specifier?
6142 TemplateSpecializationTypeLoc NewTL
6143 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6144 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6145 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6146 NewTL.setLAngleLoc(TL.getLAngleLoc());
6147 NewTL.setRAngleLoc(TL.getRAngleLoc());
6148 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6149 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6155 template<typename Derived>
6157 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6158 ElaboratedTypeLoc TL) {
6159 const ElaboratedType *T = TL.getTypePtr();
6161 NestedNameSpecifierLoc QualifierLoc;
6162 // NOTE: the qualifier in an ElaboratedType is optional.
6163 if (TL.getQualifierLoc()) {
6165 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6170 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6171 if (NamedT.isNull())
6174 // C++0x [dcl.type.elab]p2:
6175 // If the identifier resolves to a typedef-name or the simple-template-id
6176 // resolves to an alias template specialization, the
6177 // elaborated-type-specifier is ill-formed.
6178 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6179 if (const TemplateSpecializationType *TST =
6180 NamedT->getAs<TemplateSpecializationType>()) {
6181 TemplateName Template = TST->getTemplateName();
6182 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6183 Template.getAsTemplateDecl())) {
6184 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6185 diag::err_tag_reference_non_tag)
6186 << TAT << Sema::NTK_TypeAliasTemplate
6187 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6188 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6193 QualType Result = TL.getType();
6194 if (getDerived().AlwaysRebuild() ||
6195 QualifierLoc != TL.getQualifierLoc() ||
6196 NamedT != T->getNamedType()) {
6197 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6199 QualifierLoc, NamedT);
6200 if (Result.isNull())
6204 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6205 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6206 NewTL.setQualifierLoc(QualifierLoc);
6210 template<typename Derived>
6211 QualType TreeTransform<Derived>::TransformAttributedType(
6212 TypeLocBuilder &TLB,
6213 AttributedTypeLoc TL) {
6214 const AttributedType *oldType = TL.getTypePtr();
6215 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6216 if (modifiedType.isNull())
6219 // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6220 const Attr *oldAttr = TL.getAttr();
6221 const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6222 if (oldAttr && !newAttr)
6225 QualType result = TL.getType();
6227 // FIXME: dependent operand expressions?
6228 if (getDerived().AlwaysRebuild() ||
6229 modifiedType != oldType->getModifiedType()) {
6230 // TODO: this is really lame; we should really be rebuilding the
6231 // equivalent type from first principles.
6232 QualType equivalentType
6233 = getDerived().TransformType(oldType->getEquivalentType());
6234 if (equivalentType.isNull())
6237 // Check whether we can add nullability; it is only represented as
6238 // type sugar, and therefore cannot be diagnosed in any other way.
6239 if (auto nullability = oldType->getImmediateNullability()) {
6240 if (!modifiedType->canHaveNullability()) {
6241 SemaRef.Diag(TL.getAttr()->getLocation(),
6242 diag::err_nullability_nonpointer)
6243 << DiagNullabilityKind(*nullability, false) << modifiedType;
6248 result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6253 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6254 newTL.setAttr(newAttr);
6258 template<typename Derived>
6260 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6262 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6266 QualType Result = TL.getType();
6267 if (getDerived().AlwaysRebuild() ||
6268 Inner != TL.getInnerLoc().getType()) {
6269 Result = getDerived().RebuildParenType(Inner);
6270 if (Result.isNull())
6274 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6275 NewTL.setLParenLoc(TL.getLParenLoc());
6276 NewTL.setRParenLoc(TL.getRParenLoc());
6280 template <typename Derived>
6282 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6283 MacroQualifiedTypeLoc TL) {
6284 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6288 QualType Result = TL.getType();
6289 if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6291 getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6292 if (Result.isNull())
6296 MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6297 NewTL.setExpansionLoc(TL.getExpansionLoc());
6301 template<typename Derived>
6302 QualType TreeTransform<Derived>::TransformDependentNameType(
6303 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6304 return TransformDependentNameType(TLB, TL, false);
6307 template<typename Derived>
6308 QualType TreeTransform<Derived>::TransformDependentNameType(
6309 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6310 const DependentNameType *T = TL.getTypePtr();
6312 NestedNameSpecifierLoc QualifierLoc
6313 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6318 = getDerived().RebuildDependentNameType(T->getKeyword(),
6319 TL.getElaboratedKeywordLoc(),
6324 if (Result.isNull())
6327 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6328 QualType NamedT = ElabT->getNamedType();
6329 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6331 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6332 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6333 NewTL.setQualifierLoc(QualifierLoc);
6335 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6336 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6337 NewTL.setQualifierLoc(QualifierLoc);
6338 NewTL.setNameLoc(TL.getNameLoc());
6343 template<typename Derived>
6344 QualType TreeTransform<Derived>::
6345 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6346 DependentTemplateSpecializationTypeLoc TL) {
6347 NestedNameSpecifierLoc QualifierLoc;
6348 if (TL.getQualifierLoc()) {
6350 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6356 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6359 template<typename Derived>
6360 QualType TreeTransform<Derived>::
6361 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6362 DependentTemplateSpecializationTypeLoc TL,
6363 NestedNameSpecifierLoc QualifierLoc) {
6364 const DependentTemplateSpecializationType *T = TL.getTypePtr();
6366 TemplateArgumentListInfo NewTemplateArgs;
6367 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6368 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6370 typedef TemplateArgumentLocContainerIterator<
6371 DependentTemplateSpecializationTypeLoc> ArgIterator;
6372 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6373 ArgIterator(TL, TL.getNumArgs()),
6377 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6378 T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6379 T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6380 /*AllowInjectedClassName*/ false);
6381 if (Result.isNull())
6384 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6385 QualType NamedT = ElabT->getNamedType();
6387 // Copy information relevant to the template specialization.
6388 TemplateSpecializationTypeLoc NamedTL
6389 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6390 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6391 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6392 NamedTL.setLAngleLoc(TL.getLAngleLoc());
6393 NamedTL.setRAngleLoc(TL.getRAngleLoc());
6394 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6395 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6397 // Copy information relevant to the elaborated type.
6398 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6399 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6400 NewTL.setQualifierLoc(QualifierLoc);
6401 } else if (isa<DependentTemplateSpecializationType>(Result)) {
6402 DependentTemplateSpecializationTypeLoc SpecTL
6403 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6404 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6405 SpecTL.setQualifierLoc(QualifierLoc);
6406 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6407 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6408 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6409 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6410 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6411 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6413 TemplateSpecializationTypeLoc SpecTL
6414 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6415 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6416 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6417 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6418 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6419 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6420 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6425 template<typename Derived>
6426 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6427 PackExpansionTypeLoc TL) {
6429 = getDerived().TransformType(TLB, TL.getPatternLoc());
6430 if (Pattern.isNull())
6433 QualType Result = TL.getType();
6434 if (getDerived().AlwaysRebuild() ||
6435 Pattern != TL.getPatternLoc().getType()) {
6436 Result = getDerived().RebuildPackExpansionType(Pattern,
6437 TL.getPatternLoc().getSourceRange(),
6438 TL.getEllipsisLoc(),
6439 TL.getTypePtr()->getNumExpansions());
6440 if (Result.isNull())
6444 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6445 NewT.setEllipsisLoc(TL.getEllipsisLoc());
6449 template<typename Derived>
6451 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6452 ObjCInterfaceTypeLoc TL) {
6453 // ObjCInterfaceType is never dependent.
6454 TLB.pushFullCopy(TL);
6455 return TL.getType();
6458 template<typename Derived>
6460 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6461 ObjCTypeParamTypeLoc TL) {
6462 const ObjCTypeParamType *T = TL.getTypePtr();
6463 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6464 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6468 QualType Result = TL.getType();
6469 if (getDerived().AlwaysRebuild() ||
6470 OTP != T->getDecl()) {
6471 Result = getDerived().RebuildObjCTypeParamType(OTP,
6472 TL.getProtocolLAngleLoc(),
6473 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6474 TL.getNumProtocols()),
6475 TL.getProtocolLocs(),
6476 TL.getProtocolRAngleLoc());
6477 if (Result.isNull())
6481 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6482 if (TL.getNumProtocols()) {
6483 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6484 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6485 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6486 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6491 template<typename Derived>
6493 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6494 ObjCObjectTypeLoc TL) {
6495 // Transform base type.
6496 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6497 if (BaseType.isNull())
6500 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6502 // Transform type arguments.
6503 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6504 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6505 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6506 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6507 QualType TypeArg = TypeArgInfo->getType();
6508 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6511 // We have a pack expansion. Instantiate it.
6512 const auto *PackExpansion = PackExpansionLoc.getType()
6513 ->castAs<PackExpansionType>();
6514 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6515 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6517 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6519 // Determine whether the set of unexpanded parameter packs can
6520 // and should be expanded.
6521 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6522 bool Expand = false;
6523 bool RetainExpansion = false;
6524 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6525 if (getDerived().TryExpandParameterPacks(
6526 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6527 Unexpanded, Expand, RetainExpansion, NumExpansions))
6531 // We can't expand this pack expansion into separate arguments yet;
6532 // just substitute into the pattern and create a new pack expansion
6534 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6536 TypeLocBuilder TypeArgBuilder;
6537 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6538 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6540 if (NewPatternType.isNull())
6543 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6544 NewPatternType, NumExpansions);
6545 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6546 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6547 NewTypeArgInfos.push_back(
6548 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6552 // Substitute into the pack expansion pattern for each slice of the
6554 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6555 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6557 TypeLocBuilder TypeArgBuilder;
6558 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6560 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6562 if (NewTypeArg.isNull())
6565 NewTypeArgInfos.push_back(
6566 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6572 TypeLocBuilder TypeArgBuilder;
6573 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6574 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6575 if (NewTypeArg.isNull())
6578 // If nothing changed, just keep the old TypeSourceInfo.
6579 if (NewTypeArg == TypeArg) {
6580 NewTypeArgInfos.push_back(TypeArgInfo);
6584 NewTypeArgInfos.push_back(
6585 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6589 QualType Result = TL.getType();
6590 if (getDerived().AlwaysRebuild() || AnyChanged) {
6591 // Rebuild the type.
6592 Result = getDerived().RebuildObjCObjectType(
6593 BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6594 TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6595 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6596 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6598 if (Result.isNull())
6602 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6603 NewT.setHasBaseTypeAsWritten(true);
6604 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6605 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6606 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6607 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6608 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6609 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6610 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6611 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6615 template<typename Derived>
6617 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6618 ObjCObjectPointerTypeLoc TL) {
6619 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6620 if (PointeeType.isNull())
6623 QualType Result = TL.getType();
6624 if (getDerived().AlwaysRebuild() ||
6625 PointeeType != TL.getPointeeLoc().getType()) {
6626 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6628 if (Result.isNull())
6632 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6633 NewT.setStarLoc(TL.getStarLoc());
6637 //===----------------------------------------------------------------------===//
6638 // Statement transformation
6639 //===----------------------------------------------------------------------===//
6640 template<typename Derived>
6642 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6646 template<typename Derived>
6648 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6649 return getDerived().TransformCompoundStmt(S, false);
6652 template<typename Derived>
6654 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6656 Sema::CompoundScopeRAII CompoundScope(getSema());
6658 const Stmt *ExprResult = S->getStmtExprResult();
6659 bool SubStmtInvalid = false;
6660 bool SubStmtChanged = false;
6661 SmallVector<Stmt*, 8> Statements;
6662 for (auto *B : S->body()) {
6663 StmtResult Result = getDerived().TransformStmt(
6664 B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
6666 if (Result.isInvalid()) {
6667 // Immediately fail if this was a DeclStmt, since it's very
6668 // likely that this will cause problems for future statements.
6669 if (isa<DeclStmt>(B))
6672 // Otherwise, just keep processing substatements and fail later.
6673 SubStmtInvalid = true;
6677 SubStmtChanged = SubStmtChanged || Result.get() != B;
6678 Statements.push_back(Result.getAs<Stmt>());
6684 if (!getDerived().AlwaysRebuild() &&
6688 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6694 template<typename Derived>
6696 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6697 ExprResult LHS, RHS;
6699 EnterExpressionEvaluationContext Unevaluated(
6700 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6702 // Transform the left-hand case value.
6703 LHS = getDerived().TransformExpr(S->getLHS());
6704 LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6705 if (LHS.isInvalid())
6708 // Transform the right-hand case value (for the GNU case-range extension).
6709 RHS = getDerived().TransformExpr(S->getRHS());
6710 RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6711 if (RHS.isInvalid())
6715 // Build the case statement.
6716 // Case statements are always rebuilt so that they will attached to their
6717 // transformed switch statement.
6718 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6720 S->getEllipsisLoc(),
6723 if (Case.isInvalid())
6726 // Transform the statement following the case
6727 StmtResult SubStmt =
6728 getDerived().TransformStmt(S->getSubStmt());
6729 if (SubStmt.isInvalid())
6732 // Attach the body to the case statement
6733 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6736 template <typename Derived>
6737 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6738 // Transform the statement following the default case
6739 StmtResult SubStmt =
6740 getDerived().TransformStmt(S->getSubStmt());
6741 if (SubStmt.isInvalid())
6744 // Default statements are always rebuilt
6745 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6749 template<typename Derived>
6751 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
6752 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6753 if (SubStmt.isInvalid())
6756 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6761 // If we're transforming "in-place" (we're not creating new local
6762 // declarations), assume we're replacing the old label statement
6763 // and clear out the reference to it.
6764 if (LD == S->getDecl())
6765 S->getDecl()->setStmt(nullptr);
6767 // FIXME: Pass the real colon location in.
6768 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6769 cast<LabelDecl>(LD), SourceLocation(),
6773 template <typename Derived>
6774 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6778 switch (R->getKind()) {
6779 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6781 #define PRAGMA_SPELLING_ATTR(X) \
6783 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6784 #include "clang/Basic/AttrList.inc"
6790 template <typename Derived>
6792 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
6793 StmtDiscardKind SDK) {
6794 bool AttrsChanged = false;
6795 SmallVector<const Attr *, 1> Attrs;
6797 // Visit attributes and keep track if any are transformed.
6798 for (const auto *I : S->getAttrs()) {
6799 const Attr *R = getDerived().TransformAttr(I);
6800 AttrsChanged |= (I != R);
6804 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6805 if (SubStmt.isInvalid())
6808 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6811 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6815 template<typename Derived>
6817 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6818 // Transform the initialization statement
6819 StmtResult Init = getDerived().TransformStmt(S->getInit());
6820 if (Init.isInvalid())
6823 // Transform the condition
6824 Sema::ConditionResult Cond = getDerived().TransformCondition(
6825 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6826 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6827 : Sema::ConditionKind::Boolean);
6828 if (Cond.isInvalid())
6831 // If this is a constexpr if, determine which arm we should instantiate.
6832 llvm::Optional<bool> ConstexprConditionValue;
6833 if (S->isConstexpr())
6834 ConstexprConditionValue = Cond.getKnownValue();
6836 // Transform the "then" branch.
6838 if (!ConstexprConditionValue || *ConstexprConditionValue) {
6839 Then = getDerived().TransformStmt(S->getThen());
6840 if (Then.isInvalid())
6843 Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6846 // Transform the "else" branch.
6848 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6849 Else = getDerived().TransformStmt(S->getElse());
6850 if (Else.isInvalid())
6854 if (!getDerived().AlwaysRebuild() &&
6855 Init.get() == S->getInit() &&
6856 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6857 Then.get() == S->getThen() &&
6858 Else.get() == S->getElse())
6861 return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6862 Init.get(), Then.get(), S->getElseLoc(),
6866 template<typename Derived>
6868 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6869 // Transform the initialization statement
6870 StmtResult Init = getDerived().TransformStmt(S->getInit());
6871 if (Init.isInvalid())
6874 // Transform the condition.
6875 Sema::ConditionResult Cond = getDerived().TransformCondition(
6876 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6877 Sema::ConditionKind::Switch);
6878 if (Cond.isInvalid())
6881 // Rebuild the switch statement.
6883 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
6884 if (Switch.isInvalid())
6887 // Transform the body of the switch statement.
6888 StmtResult Body = getDerived().TransformStmt(S->getBody());
6889 if (Body.isInvalid())
6892 // Complete the switch statement.
6893 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6897 template<typename Derived>
6899 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6900 // Transform the condition
6901 Sema::ConditionResult Cond = getDerived().TransformCondition(
6902 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6903 Sema::ConditionKind::Boolean);
6904 if (Cond.isInvalid())
6907 // Transform the body
6908 StmtResult Body = getDerived().TransformStmt(S->getBody());
6909 if (Body.isInvalid())
6912 if (!getDerived().AlwaysRebuild() &&
6913 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6914 Body.get() == S->getBody())
6917 return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6920 template<typename Derived>
6922 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6923 // Transform the body
6924 StmtResult Body = getDerived().TransformStmt(S->getBody());
6925 if (Body.isInvalid())
6928 // Transform the condition
6929 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6930 if (Cond.isInvalid())
6933 if (!getDerived().AlwaysRebuild() &&
6934 Cond.get() == S->getCond() &&
6935 Body.get() == S->getBody())
6938 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6939 /*FIXME:*/S->getWhileLoc(), Cond.get(),
6943 template<typename Derived>
6945 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6946 if (getSema().getLangOpts().OpenMP)
6947 getSema().startOpenMPLoop();
6949 // Transform the initialization statement
6950 StmtResult Init = getDerived().TransformStmt(S->getInit());
6951 if (Init.isInvalid())
6954 // In OpenMP loop region loop control variable must be captured and be
6955 // private. Perform analysis of first part (if any).
6956 if (getSema().getLangOpts().OpenMP && Init.isUsable())
6957 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6959 // Transform the condition
6960 Sema::ConditionResult Cond = getDerived().TransformCondition(
6961 S->getForLoc(), S->getConditionVariable(), S->getCond(),
6962 Sema::ConditionKind::Boolean);
6963 if (Cond.isInvalid())
6966 // Transform the increment
6967 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6968 if (Inc.isInvalid())
6971 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6972 if (S->getInc() && !FullInc.get())
6975 // Transform the body
6976 StmtResult Body = getDerived().TransformStmt(S->getBody());
6977 if (Body.isInvalid())
6980 if (!getDerived().AlwaysRebuild() &&
6981 Init.get() == S->getInit() &&
6982 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6983 Inc.get() == S->getInc() &&
6984 Body.get() == S->getBody())
6987 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6988 Init.get(), Cond, FullInc,
6989 S->getRParenLoc(), Body.get());
6992 template<typename Derived>
6994 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6995 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7000 // Goto statements must always be rebuilt, to resolve the label.
7001 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7002 cast<LabelDecl>(LD));
7005 template<typename Derived>
7007 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7008 ExprResult Target = getDerived().TransformExpr(S->getTarget());
7009 if (Target.isInvalid())
7011 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7013 if (!getDerived().AlwaysRebuild() &&
7014 Target.get() == S->getTarget())
7017 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7021 template<typename Derived>
7023 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7027 template<typename Derived>
7029 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7033 template<typename Derived>
7035 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7036 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7037 /*NotCopyInit*/false);
7038 if (Result.isInvalid())
7041 // FIXME: We always rebuild the return statement because there is no way
7042 // to tell whether the return type of the function has changed.
7043 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7046 template<typename Derived>
7048 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7049 bool DeclChanged = false;
7050 SmallVector<Decl *, 4> Decls;
7051 for (auto *D : S->decls()) {
7052 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7056 if (Transformed != D)
7059 Decls.push_back(Transformed);
7062 if (!getDerived().AlwaysRebuild() && !DeclChanged)
7065 return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7068 template<typename Derived>
7070 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7072 SmallVector<Expr*, 8> Constraints;
7073 SmallVector<Expr*, 8> Exprs;
7074 SmallVector<IdentifierInfo *, 4> Names;
7076 ExprResult AsmString;
7077 SmallVector<Expr*, 8> Clobbers;
7079 bool ExprsChanged = false;
7081 // Go through the outputs.
7082 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7083 Names.push_back(S->getOutputIdentifier(I));
7085 // No need to transform the constraint literal.
7086 Constraints.push_back(S->getOutputConstraintLiteral(I));
7088 // Transform the output expr.
7089 Expr *OutputExpr = S->getOutputExpr(I);
7090 ExprResult Result = getDerived().TransformExpr(OutputExpr);
7091 if (Result.isInvalid())
7094 ExprsChanged |= Result.get() != OutputExpr;
7096 Exprs.push_back(Result.get());
7099 // Go through the inputs.
7100 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7101 Names.push_back(S->getInputIdentifier(I));
7103 // No need to transform the constraint literal.
7104 Constraints.push_back(S->getInputConstraintLiteral(I));
7106 // Transform the input expr.
7107 Expr *InputExpr = S->getInputExpr(I);
7108 ExprResult Result = getDerived().TransformExpr(InputExpr);
7109 if (Result.isInvalid())
7112 ExprsChanged |= Result.get() != InputExpr;
7114 Exprs.push_back(Result.get());
7117 // Go through the Labels.
7118 for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7119 Names.push_back(S->getLabelIdentifier(I));
7121 ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7122 if (Result.isInvalid())
7124 ExprsChanged |= Result.get() != S->getLabelExpr(I);
7125 Exprs.push_back(Result.get());
7127 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7130 // Go through the clobbers.
7131 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7132 Clobbers.push_back(S->getClobberStringLiteral(I));
7134 // No need to transform the asm string literal.
7135 AsmString = S->getAsmString();
7136 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7137 S->isVolatile(), S->getNumOutputs(),
7138 S->getNumInputs(), Names.data(),
7139 Constraints, Exprs, AsmString.get(),
7140 Clobbers, S->getNumLabels(),
7144 template<typename Derived>
7146 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7147 ArrayRef<Token> AsmToks =
7148 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7150 bool HadError = false, HadChange = false;
7152 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7153 SmallVector<Expr*, 8> TransformedExprs;
7154 TransformedExprs.reserve(SrcExprs.size());
7155 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7156 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7157 if (!Result.isUsable()) {
7160 HadChange |= (Result.get() != SrcExprs[i]);
7161 TransformedExprs.push_back(Result.get());
7165 if (HadError) return StmtError();
7166 if (!HadChange && !getDerived().AlwaysRebuild())
7169 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7170 AsmToks, S->getAsmString(),
7171 S->getNumOutputs(), S->getNumInputs(),
7172 S->getAllConstraints(), S->getClobbers(),
7173 TransformedExprs, S->getEndLoc());
7176 // C++ Coroutines TS
7178 template<typename Derived>
7180 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7181 auto *ScopeInfo = SemaRef.getCurFunction();
7182 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7183 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7184 ScopeInfo->NeedsCoroutineSuspends &&
7185 ScopeInfo->CoroutineSuspends.first == nullptr &&
7186 ScopeInfo->CoroutineSuspends.second == nullptr &&
7187 "expected clean scope info");
7189 // Set that we have (possibly-invalid) suspend points before we do anything
7191 ScopeInfo->setNeedsCoroutineSuspends(false);
7193 // The new CoroutinePromise object needs to be built and put into the current
7194 // FunctionScopeInfo before any transformations or rebuilding occurs.
7195 if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7197 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7200 getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7201 ScopeInfo->CoroutinePromise = Promise;
7203 // Transform the implicit coroutine statements we built during the initial
7205 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7206 if (InitSuspend.isInvalid())
7208 StmtResult FinalSuspend =
7209 getDerived().TransformStmt(S->getFinalSuspendStmt());
7210 if (FinalSuspend.isInvalid())
7212 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7213 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7215 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7216 if (BodyRes.isInvalid())
7219 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7220 if (Builder.isInvalid())
7223 Expr *ReturnObject = S->getReturnValueInit();
7224 assert(ReturnObject && "the return object is expected to be valid");
7225 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7226 /*NoCopyInit*/ false);
7227 if (Res.isInvalid())
7229 Builder.ReturnValue = Res.get();
7231 if (S->hasDependentPromiseType()) {
7232 // PR41909: We may find a generic coroutine lambda definition within a
7233 // template function that is being instantiated. In this case, the lambda
7234 // will have a dependent promise type, until it is used in an expression
7235 // that creates an instantiation with a non-dependent promise type. We
7236 // should not assert or build coroutine dependent statements for such a
7238 auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD);
7239 if (!MD || !MD->getParent()->isGenericLambda()) {
7240 assert(!Promise->getType()->isDependentType() &&
7241 "the promise type must no longer be dependent");
7242 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7243 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7244 "these nodes should not have been built yet");
7245 if (!Builder.buildDependentStatements())
7249 if (auto *OnFallthrough = S->getFallthroughHandler()) {
7250 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7251 if (Res.isInvalid())
7253 Builder.OnFallthrough = Res.get();
7256 if (auto *OnException = S->getExceptionHandler()) {
7257 StmtResult Res = getDerived().TransformStmt(OnException);
7258 if (Res.isInvalid())
7260 Builder.OnException = Res.get();
7263 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7264 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7265 if (Res.isInvalid())
7267 Builder.ReturnStmtOnAllocFailure = Res.get();
7270 // Transform any additional statements we may have already built
7271 assert(S->getAllocate() && S->getDeallocate() &&
7272 "allocation and deallocation calls must already be built");
7273 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7274 if (AllocRes.isInvalid())
7276 Builder.Allocate = AllocRes.get();
7278 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7279 if (DeallocRes.isInvalid())
7281 Builder.Deallocate = DeallocRes.get();
7283 assert(S->getResultDecl() && "ResultDecl must already be built");
7284 StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7285 if (ResultDecl.isInvalid())
7287 Builder.ResultDecl = ResultDecl.get();
7289 if (auto *ReturnStmt = S->getReturnStmt()) {
7290 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7291 if (Res.isInvalid())
7293 Builder.ReturnStmt = Res.get();
7297 return getDerived().RebuildCoroutineBodyStmt(Builder);
7300 template<typename Derived>
7302 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7303 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7304 /*NotCopyInit*/false);
7305 if (Result.isInvalid())
7308 // Always rebuild; we don't know if this needs to be injected into a new
7309 // context or if the promise type has changed.
7310 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7314 template<typename Derived>
7316 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7317 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7318 /*NotCopyInit*/false);
7319 if (Result.isInvalid())
7322 // Always rebuild; we don't know if this needs to be injected into a new
7323 // context or if the promise type has changed.
7324 return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7328 template <typename Derived>
7330 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7331 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7332 /*NotCopyInit*/ false);
7333 if (OperandResult.isInvalid())
7336 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7337 E->getOperatorCoawaitLookup());
7339 if (LookupResult.isInvalid())
7342 // Always rebuild; we don't know if this needs to be injected into a new
7343 // context or if the promise type has changed.
7344 return getDerived().RebuildDependentCoawaitExpr(
7345 E->getKeywordLoc(), OperandResult.get(),
7346 cast<UnresolvedLookupExpr>(LookupResult.get()));
7349 template<typename Derived>
7351 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7352 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7353 /*NotCopyInit*/false);
7354 if (Result.isInvalid())
7357 // Always rebuild; we don't know if this needs to be injected into a new
7358 // context or if the promise type has changed.
7359 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7362 // Objective-C Statements.
7364 template<typename Derived>
7366 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7367 // Transform the body of the @try.
7368 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7369 if (TryBody.isInvalid())
7372 // Transform the @catch statements (if present).
7373 bool AnyCatchChanged = false;
7374 SmallVector<Stmt*, 8> CatchStmts;
7375 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7376 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7377 if (Catch.isInvalid())
7379 if (Catch.get() != S->getCatchStmt(I))
7380 AnyCatchChanged = true;
7381 CatchStmts.push_back(Catch.get());
7384 // Transform the @finally statement (if present).
7386 if (S->getFinallyStmt()) {
7387 Finally = getDerived().TransformStmt(S->getFinallyStmt());
7388 if (Finally.isInvalid())
7392 // If nothing changed, just retain this statement.
7393 if (!getDerived().AlwaysRebuild() &&
7394 TryBody.get() == S->getTryBody() &&
7396 Finally.get() == S->getFinallyStmt())
7399 // Build a new statement.
7400 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7401 CatchStmts, Finally.get());
7404 template<typename Derived>
7406 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7407 // Transform the @catch parameter, if there is one.
7408 VarDecl *Var = nullptr;
7409 if (VarDecl *FromVar = S->getCatchParamDecl()) {
7410 TypeSourceInfo *TSInfo = nullptr;
7411 if (FromVar->getTypeSourceInfo()) {
7412 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7419 T = TSInfo->getType();
7421 T = getDerived().TransformType(FromVar->getType());
7426 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7431 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7432 if (Body.isInvalid())
7435 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7440 template<typename Derived>
7442 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7443 // Transform the body.
7444 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7445 if (Body.isInvalid())
7448 // If nothing changed, just retain this statement.
7449 if (!getDerived().AlwaysRebuild() &&
7450 Body.get() == S->getFinallyBody())
7453 // Build a new statement.
7454 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7458 template<typename Derived>
7460 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7462 if (S->getThrowExpr()) {
7463 Operand = getDerived().TransformExpr(S->getThrowExpr());
7464 if (Operand.isInvalid())
7468 if (!getDerived().AlwaysRebuild() &&
7469 Operand.get() == S->getThrowExpr())
7472 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7475 template<typename Derived>
7477 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7478 ObjCAtSynchronizedStmt *S) {
7479 // Transform the object we are locking.
7480 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7481 if (Object.isInvalid())
7484 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7486 if (Object.isInvalid())
7489 // Transform the body.
7490 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7491 if (Body.isInvalid())
7494 // If nothing change, just retain the current statement.
7495 if (!getDerived().AlwaysRebuild() &&
7496 Object.get() == S->getSynchExpr() &&
7497 Body.get() == S->getSynchBody())
7500 // Build a new statement.
7501 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7502 Object.get(), Body.get());
7505 template<typename Derived>
7507 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7508 ObjCAutoreleasePoolStmt *S) {
7509 // Transform the body.
7510 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7511 if (Body.isInvalid())
7514 // If nothing changed, just retain this statement.
7515 if (!getDerived().AlwaysRebuild() &&
7516 Body.get() == S->getSubStmt())
7519 // Build a new statement.
7520 return getDerived().RebuildObjCAutoreleasePoolStmt(
7521 S->getAtLoc(), Body.get());
7524 template<typename Derived>
7526 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7527 ObjCForCollectionStmt *S) {
7528 // Transform the element statement.
7529 StmtResult Element =
7530 getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7531 if (Element.isInvalid())
7534 // Transform the collection expression.
7535 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7536 if (Collection.isInvalid())
7539 // Transform the body.
7540 StmtResult Body = getDerived().TransformStmt(S->getBody());
7541 if (Body.isInvalid())
7544 // If nothing changed, just retain this statement.
7545 if (!getDerived().AlwaysRebuild() &&
7546 Element.get() == S->getElement() &&
7547 Collection.get() == S->getCollection() &&
7548 Body.get() == S->getBody())
7551 // Build a new statement.
7552 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7559 template <typename Derived>
7560 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7561 // Transform the exception declaration, if any.
7562 VarDecl *Var = nullptr;
7563 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7565 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7569 Var = getDerived().RebuildExceptionDecl(
7570 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7571 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7572 if (!Var || Var->isInvalidDecl())
7576 // Transform the actual exception handler.
7577 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7578 if (Handler.isInvalid())
7581 if (!getDerived().AlwaysRebuild() && !Var &&
7582 Handler.get() == S->getHandlerBlock())
7585 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7588 template <typename Derived>
7589 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7590 // Transform the try block itself.
7591 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7592 if (TryBlock.isInvalid())
7595 // Transform the handlers.
7596 bool HandlerChanged = false;
7597 SmallVector<Stmt *, 8> Handlers;
7598 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7599 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7600 if (Handler.isInvalid())
7603 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7604 Handlers.push_back(Handler.getAs<Stmt>());
7607 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7611 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7615 template<typename Derived>
7617 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7619 S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7620 if (Init.isInvalid())
7623 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7624 if (Range.isInvalid())
7627 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7628 if (Begin.isInvalid())
7630 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7631 if (End.isInvalid())
7634 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7635 if (Cond.isInvalid())
7638 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7639 if (Cond.isInvalid())
7642 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7644 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7645 if (Inc.isInvalid())
7648 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7650 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7651 if (LoopVar.isInvalid())
7654 StmtResult NewStmt = S;
7655 if (getDerived().AlwaysRebuild() ||
7656 Init.get() != S->getInit() ||
7657 Range.get() != S->getRangeStmt() ||
7658 Begin.get() != S->getBeginStmt() ||
7659 End.get() != S->getEndStmt() ||
7660 Cond.get() != S->getCond() ||
7661 Inc.get() != S->getInc() ||
7662 LoopVar.get() != S->getLoopVarStmt()) {
7663 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7664 S->getCoawaitLoc(), Init.get(),
7665 S->getColonLoc(), Range.get(),
7666 Begin.get(), End.get(),
7668 Inc.get(), LoopVar.get(),
7670 if (NewStmt.isInvalid())
7674 StmtResult Body = getDerived().TransformStmt(S->getBody());
7675 if (Body.isInvalid())
7678 // Body has changed but we didn't rebuild the for-range statement. Rebuild
7679 // it now so we have a new statement to attach the body to.
7680 if (Body.get() != S->getBody() && NewStmt.get() == S) {
7681 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7682 S->getCoawaitLoc(), Init.get(),
7683 S->getColonLoc(), Range.get(),
7684 Begin.get(), End.get(),
7686 Inc.get(), LoopVar.get(),
7688 if (NewStmt.isInvalid())
7692 if (NewStmt.get() == S)
7695 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7698 template<typename Derived>
7700 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7701 MSDependentExistsStmt *S) {
7702 // Transform the nested-name-specifier, if any.
7703 NestedNameSpecifierLoc QualifierLoc;
7704 if (S->getQualifierLoc()) {
7706 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7711 // Transform the declaration name.
7712 DeclarationNameInfo NameInfo = S->getNameInfo();
7713 if (NameInfo.getName()) {
7714 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7715 if (!NameInfo.getName())
7719 // Check whether anything changed.
7720 if (!getDerived().AlwaysRebuild() &&
7721 QualifierLoc == S->getQualifierLoc() &&
7722 NameInfo.getName() == S->getNameInfo().getName())
7725 // Determine whether this name exists, if we can.
7727 SS.Adopt(QualifierLoc);
7728 bool Dependent = false;
7729 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7730 case Sema::IER_Exists:
7731 if (S->isIfExists())
7734 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7736 case Sema::IER_DoesNotExist:
7737 if (S->isIfNotExists())
7740 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7742 case Sema::IER_Dependent:
7746 case Sema::IER_Error:
7750 // We need to continue with the instantiation, so do so now.
7751 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7752 if (SubStmt.isInvalid())
7755 // If we have resolved the name, just transform to the substatement.
7759 // The name is still dependent, so build a dependent expression again.
7760 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7767 template<typename Derived>
7769 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7770 NestedNameSpecifierLoc QualifierLoc;
7771 if (E->getQualifierLoc()) {
7773 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7778 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7779 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7783 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7784 if (Base.isInvalid())
7787 return new (SemaRef.getASTContext())
7788 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7789 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7790 QualifierLoc, E->getMemberLoc());
7793 template <typename Derived>
7794 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7795 MSPropertySubscriptExpr *E) {
7796 auto BaseRes = getDerived().TransformExpr(E->getBase());
7797 if (BaseRes.isInvalid())
7799 auto IdxRes = getDerived().TransformExpr(E->getIdx());
7800 if (IdxRes.isInvalid())
7803 if (!getDerived().AlwaysRebuild() &&
7804 BaseRes.get() == E->getBase() &&
7805 IdxRes.get() == E->getIdx())
7808 return getDerived().RebuildArraySubscriptExpr(
7809 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7812 template <typename Derived>
7813 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7814 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7815 if (TryBlock.isInvalid())
7818 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7819 if (Handler.isInvalid())
7822 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7823 Handler.get() == S->getHandler())
7826 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7827 TryBlock.get(), Handler.get());
7830 template <typename Derived>
7831 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7832 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7833 if (Block.isInvalid())
7836 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7839 template <typename Derived>
7840 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7841 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7842 if (FilterExpr.isInvalid())
7845 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7846 if (Block.isInvalid())
7849 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7853 template <typename Derived>
7854 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7855 if (isa<SEHFinallyStmt>(Handler))
7856 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7858 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7861 template<typename Derived>
7863 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7867 //===----------------------------------------------------------------------===//
7868 // OpenMP directive transformation
7869 //===----------------------------------------------------------------------===//
7870 template <typename Derived>
7871 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7872 OMPExecutableDirective *D) {
7874 // Transform the clauses
7875 llvm::SmallVector<OMPClause *, 16> TClauses;
7876 ArrayRef<OMPClause *> Clauses = D->clauses();
7877 TClauses.reserve(Clauses.size());
7878 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7881 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7882 OMPClause *Clause = getDerived().TransformOMPClause(*I);
7883 getDerived().getSema().EndOpenMPClause();
7885 TClauses.push_back(Clause);
7887 TClauses.push_back(nullptr);
7890 StmtResult AssociatedStmt;
7891 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7892 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7893 /*CurScope=*/nullptr);
7896 Sema::CompoundScopeRAII CompoundScope(getSema());
7897 Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
7898 Body = getDerived().TransformStmt(CS);
7901 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7902 if (AssociatedStmt.isInvalid()) {
7906 if (TClauses.size() != Clauses.size()) {
7910 // Transform directive name for 'omp critical' directive.
7911 DeclarationNameInfo DirName;
7912 if (D->getDirectiveKind() == OMPD_critical) {
7913 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7914 DirName = getDerived().TransformDeclarationNameInfo(DirName);
7916 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7917 if (D->getDirectiveKind() == OMPD_cancellation_point) {
7918 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7919 } else if (D->getDirectiveKind() == OMPD_cancel) {
7920 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7923 return getDerived().RebuildOMPExecutableDirective(
7924 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7925 AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
7928 template <typename Derived>
7930 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7931 DeclarationNameInfo DirName;
7932 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7934 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7935 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7939 template <typename Derived>
7941 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7942 DeclarationNameInfo DirName;
7943 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7945 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7946 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7950 template <typename Derived>
7952 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7953 DeclarationNameInfo DirName;
7954 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7956 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7957 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7961 template <typename Derived>
7963 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7964 DeclarationNameInfo DirName;
7965 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7967 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7968 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7972 template <typename Derived>
7974 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7975 DeclarationNameInfo DirName;
7976 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7978 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7979 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7983 template <typename Derived>
7985 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7986 DeclarationNameInfo DirName;
7987 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7989 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7990 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7994 template <typename Derived>
7996 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7997 DeclarationNameInfo DirName;
7998 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8000 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8001 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8005 template <typename Derived>
8007 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8008 DeclarationNameInfo DirName;
8009 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8011 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8012 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8016 template <typename Derived>
8018 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8019 getDerived().getSema().StartOpenMPDSABlock(
8020 OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8021 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8022 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8026 template <typename Derived>
8027 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8028 OMPParallelForDirective *D) {
8029 DeclarationNameInfo DirName;
8030 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8031 nullptr, D->getBeginLoc());
8032 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8033 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8037 template <typename Derived>
8038 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8039 OMPParallelForSimdDirective *D) {
8040 DeclarationNameInfo DirName;
8041 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8042 nullptr, D->getBeginLoc());
8043 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8044 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8048 template <typename Derived>
8049 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8050 OMPParallelSectionsDirective *D) {
8051 DeclarationNameInfo DirName;
8052 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8053 nullptr, D->getBeginLoc());
8054 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8055 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8059 template <typename Derived>
8061 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8062 DeclarationNameInfo DirName;
8063 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8065 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8066 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8070 template <typename Derived>
8071 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8072 OMPTaskyieldDirective *D) {
8073 DeclarationNameInfo DirName;
8074 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8076 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8077 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8081 template <typename Derived>
8083 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8084 DeclarationNameInfo DirName;
8085 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8087 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8088 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8092 template <typename Derived>
8094 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8095 DeclarationNameInfo DirName;
8096 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8098 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8099 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8103 template <typename Derived>
8104 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8105 OMPTaskgroupDirective *D) {
8106 DeclarationNameInfo DirName;
8107 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8109 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8110 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8114 template <typename Derived>
8116 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8117 DeclarationNameInfo DirName;
8118 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8120 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8121 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8125 template <typename Derived>
8127 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8128 DeclarationNameInfo DirName;
8129 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8131 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8132 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8136 template <typename Derived>
8138 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8139 DeclarationNameInfo DirName;
8140 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8142 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8143 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8147 template <typename Derived>
8149 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8150 DeclarationNameInfo DirName;
8151 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8153 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8154 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8158 template <typename Derived>
8159 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8160 OMPTargetDataDirective *D) {
8161 DeclarationNameInfo DirName;
8162 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8164 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8165 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8169 template <typename Derived>
8170 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8171 OMPTargetEnterDataDirective *D) {
8172 DeclarationNameInfo DirName;
8173 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8174 nullptr, D->getBeginLoc());
8175 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8176 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8180 template <typename Derived>
8181 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8182 OMPTargetExitDataDirective *D) {
8183 DeclarationNameInfo DirName;
8184 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8185 nullptr, D->getBeginLoc());
8186 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8187 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8191 template <typename Derived>
8192 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8193 OMPTargetParallelDirective *D) {
8194 DeclarationNameInfo DirName;
8195 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8196 nullptr, D->getBeginLoc());
8197 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8198 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8202 template <typename Derived>
8203 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8204 OMPTargetParallelForDirective *D) {
8205 DeclarationNameInfo DirName;
8206 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8207 nullptr, D->getBeginLoc());
8208 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8209 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8213 template <typename Derived>
8214 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8215 OMPTargetUpdateDirective *D) {
8216 DeclarationNameInfo DirName;
8217 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8218 nullptr, D->getBeginLoc());
8219 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8220 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8224 template <typename Derived>
8226 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8227 DeclarationNameInfo DirName;
8228 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8230 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8231 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8235 template <typename Derived>
8236 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8237 OMPCancellationPointDirective *D) {
8238 DeclarationNameInfo DirName;
8239 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8240 nullptr, D->getBeginLoc());
8241 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8242 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8246 template <typename Derived>
8248 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8249 DeclarationNameInfo DirName;
8250 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8252 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8253 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8257 template <typename Derived>
8259 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8260 DeclarationNameInfo DirName;
8261 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8263 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8264 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8268 template <typename Derived>
8269 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8270 OMPTaskLoopSimdDirective *D) {
8271 DeclarationNameInfo DirName;
8272 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8273 nullptr, D->getBeginLoc());
8274 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8275 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8279 template <typename Derived>
8280 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8281 OMPMasterTaskLoopDirective *D) {
8282 DeclarationNameInfo DirName;
8283 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8284 nullptr, D->getBeginLoc());
8285 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8286 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8290 template <typename Derived>
8291 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
8292 OMPMasterTaskLoopSimdDirective *D) {
8293 DeclarationNameInfo DirName;
8294 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8295 nullptr, D->getBeginLoc());
8296 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8297 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8301 template <typename Derived>
8302 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8303 OMPParallelMasterTaskLoopDirective *D) {
8304 DeclarationNameInfo DirName;
8305 getDerived().getSema().StartOpenMPDSABlock(
8306 OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
8307 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8308 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8312 template <typename Derived>
8313 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8314 OMPDistributeDirective *D) {
8315 DeclarationNameInfo DirName;
8316 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8318 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8319 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8323 template <typename Derived>
8324 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8325 OMPDistributeParallelForDirective *D) {
8326 DeclarationNameInfo DirName;
8327 getDerived().getSema().StartOpenMPDSABlock(
8328 OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8329 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8330 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8334 template <typename Derived>
8336 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8337 OMPDistributeParallelForSimdDirective *D) {
8338 DeclarationNameInfo DirName;
8339 getDerived().getSema().StartOpenMPDSABlock(
8340 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8341 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8342 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8346 template <typename Derived>
8347 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8348 OMPDistributeSimdDirective *D) {
8349 DeclarationNameInfo DirName;
8350 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8351 nullptr, D->getBeginLoc());
8352 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8353 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8357 template <typename Derived>
8358 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8359 OMPTargetParallelForSimdDirective *D) {
8360 DeclarationNameInfo DirName;
8361 getDerived().getSema().StartOpenMPDSABlock(
8362 OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8363 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8364 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8368 template <typename Derived>
8369 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8370 OMPTargetSimdDirective *D) {
8371 DeclarationNameInfo DirName;
8372 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8374 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8375 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8379 template <typename Derived>
8380 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8381 OMPTeamsDistributeDirective *D) {
8382 DeclarationNameInfo DirName;
8383 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8384 nullptr, D->getBeginLoc());
8385 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8386 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8390 template <typename Derived>
8391 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8392 OMPTeamsDistributeSimdDirective *D) {
8393 DeclarationNameInfo DirName;
8394 getDerived().getSema().StartOpenMPDSABlock(
8395 OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8396 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8397 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8401 template <typename Derived>
8402 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8403 OMPTeamsDistributeParallelForSimdDirective *D) {
8404 DeclarationNameInfo DirName;
8405 getDerived().getSema().StartOpenMPDSABlock(
8406 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8408 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8409 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8413 template <typename Derived>
8414 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8415 OMPTeamsDistributeParallelForDirective *D) {
8416 DeclarationNameInfo DirName;
8417 getDerived().getSema().StartOpenMPDSABlock(
8418 OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8419 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8420 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8424 template <typename Derived>
8425 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8426 OMPTargetTeamsDirective *D) {
8427 DeclarationNameInfo DirName;
8428 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8429 nullptr, D->getBeginLoc());
8430 auto Res = getDerived().TransformOMPExecutableDirective(D);
8431 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8435 template <typename Derived>
8436 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8437 OMPTargetTeamsDistributeDirective *D) {
8438 DeclarationNameInfo DirName;
8439 getDerived().getSema().StartOpenMPDSABlock(
8440 OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8441 auto Res = getDerived().TransformOMPExecutableDirective(D);
8442 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8446 template <typename Derived>
8448 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8449 OMPTargetTeamsDistributeParallelForDirective *D) {
8450 DeclarationNameInfo DirName;
8451 getDerived().getSema().StartOpenMPDSABlock(
8452 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8454 auto Res = getDerived().TransformOMPExecutableDirective(D);
8455 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8459 template <typename Derived>
8460 StmtResult TreeTransform<Derived>::
8461 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8462 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8463 DeclarationNameInfo DirName;
8464 getDerived().getSema().StartOpenMPDSABlock(
8465 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8467 auto Res = getDerived().TransformOMPExecutableDirective(D);
8468 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8472 template <typename Derived>
8474 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8475 OMPTargetTeamsDistributeSimdDirective *D) {
8476 DeclarationNameInfo DirName;
8477 getDerived().getSema().StartOpenMPDSABlock(
8478 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8479 auto Res = getDerived().TransformOMPExecutableDirective(D);
8480 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8485 //===----------------------------------------------------------------------===//
8486 // OpenMP clause transformation
8487 //===----------------------------------------------------------------------===//
8488 template <typename Derived>
8489 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8490 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8491 if (Cond.isInvalid())
8493 return getDerived().RebuildOMPIfClause(
8494 C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8495 C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8498 template <typename Derived>
8499 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8500 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8501 if (Cond.isInvalid())
8503 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8504 C->getLParenLoc(), C->getEndLoc());
8507 template <typename Derived>
8509 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8510 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8511 if (NumThreads.isInvalid())
8513 return getDerived().RebuildOMPNumThreadsClause(
8514 NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8517 template <typename Derived>
8519 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8520 ExprResult E = getDerived().TransformExpr(C->getSafelen());
8523 return getDerived().RebuildOMPSafelenClause(
8524 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8527 template <typename Derived>
8529 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8530 ExprResult E = getDerived().TransformExpr(C->getAllocator());
8533 return getDerived().RebuildOMPAllocatorClause(
8534 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8537 template <typename Derived>
8539 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8540 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8543 return getDerived().RebuildOMPSimdlenClause(
8544 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8547 template <typename Derived>
8549 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8550 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8553 return getDerived().RebuildOMPCollapseClause(
8554 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8557 template <typename Derived>
8559 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8560 return getDerived().RebuildOMPDefaultClause(
8561 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8562 C->getLParenLoc(), C->getEndLoc());
8565 template <typename Derived>
8567 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8568 return getDerived().RebuildOMPProcBindClause(
8569 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8570 C->getLParenLoc(), C->getEndLoc());
8573 template <typename Derived>
8575 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8576 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8579 return getDerived().RebuildOMPScheduleClause(
8580 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8581 C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8582 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8583 C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8586 template <typename Derived>
8588 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8590 if (auto *Num = C->getNumForLoops()) {
8591 E = getDerived().TransformExpr(Num);
8595 return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8596 C->getLParenLoc(), E.get());
8599 template <typename Derived>
8601 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8602 // No need to rebuild this clause, no template-dependent parameters.
8606 template <typename Derived>
8608 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8609 // No need to rebuild this clause, no template-dependent parameters.
8613 template <typename Derived>
8615 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8616 // No need to rebuild this clause, no template-dependent parameters.
8620 template <typename Derived>
8621 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8622 // No need to rebuild this clause, no template-dependent parameters.
8626 template <typename Derived>
8627 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8628 // No need to rebuild this clause, no template-dependent parameters.
8632 template <typename Derived>
8634 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8635 // No need to rebuild this clause, no template-dependent parameters.
8639 template <typename Derived>
8641 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8642 // No need to rebuild this clause, no template-dependent parameters.
8646 template <typename Derived>
8648 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8649 // No need to rebuild this clause, no template-dependent parameters.
8653 template <typename Derived>
8655 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8656 // No need to rebuild this clause, no template-dependent parameters.
8660 template <typename Derived>
8661 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8662 // No need to rebuild this clause, no template-dependent parameters.
8666 template <typename Derived>
8668 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8669 // No need to rebuild this clause, no template-dependent parameters.
8673 template <typename Derived>
8674 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8675 OMPUnifiedAddressClause *C) {
8676 llvm_unreachable("unified_address clause cannot appear in dependent context");
8679 template <typename Derived>
8680 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8681 OMPUnifiedSharedMemoryClause *C) {
8683 "unified_shared_memory clause cannot appear in dependent context");
8686 template <typename Derived>
8687 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8688 OMPReverseOffloadClause *C) {
8689 llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8692 template <typename Derived>
8693 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8694 OMPDynamicAllocatorsClause *C) {
8696 "dynamic_allocators clause cannot appear in dependent context");
8699 template <typename Derived>
8700 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8701 OMPAtomicDefaultMemOrderClause *C) {
8703 "atomic_default_mem_order clause cannot appear in dependent context");
8706 template <typename Derived>
8708 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8709 llvm::SmallVector<Expr *, 16> Vars;
8710 Vars.reserve(C->varlist_size());
8711 for (auto *VE : C->varlists()) {
8712 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8713 if (EVar.isInvalid())
8715 Vars.push_back(EVar.get());
8717 return getDerived().RebuildOMPPrivateClause(
8718 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8721 template <typename Derived>
8722 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8723 OMPFirstprivateClause *C) {
8724 llvm::SmallVector<Expr *, 16> Vars;
8725 Vars.reserve(C->varlist_size());
8726 for (auto *VE : C->varlists()) {
8727 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8728 if (EVar.isInvalid())
8730 Vars.push_back(EVar.get());
8732 return getDerived().RebuildOMPFirstprivateClause(
8733 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8736 template <typename Derived>
8738 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8739 llvm::SmallVector<Expr *, 16> Vars;
8740 Vars.reserve(C->varlist_size());
8741 for (auto *VE : C->varlists()) {
8742 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8743 if (EVar.isInvalid())
8745 Vars.push_back(EVar.get());
8747 return getDerived().RebuildOMPLastprivateClause(
8748 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8751 template <typename Derived>
8753 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8754 llvm::SmallVector<Expr *, 16> Vars;
8755 Vars.reserve(C->varlist_size());
8756 for (auto *VE : C->varlists()) {
8757 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8758 if (EVar.isInvalid())
8760 Vars.push_back(EVar.get());
8762 return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8763 C->getLParenLoc(), C->getEndLoc());
8766 template <typename Derived>
8768 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8769 llvm::SmallVector<Expr *, 16> Vars;
8770 Vars.reserve(C->varlist_size());
8771 for (auto *VE : C->varlists()) {
8772 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8773 if (EVar.isInvalid())
8775 Vars.push_back(EVar.get());
8777 CXXScopeSpec ReductionIdScopeSpec;
8778 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8780 DeclarationNameInfo NameInfo = C->getNameInfo();
8781 if (NameInfo.getName()) {
8782 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8783 if (!NameInfo.getName())
8786 // Build a list of all UDR decls with the same names ranged by the Scopes.
8787 // The Scope boundary is a duplication of the previous decl.
8788 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8789 for (auto *E : C->reduction_ops()) {
8790 // Transform all the decls.
8792 auto *ULE = cast<UnresolvedLookupExpr>(E);
8793 UnresolvedSet<8> Decls;
8794 for (auto *D : ULE->decls()) {
8796 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8797 Decls.addDecl(InstD, InstD->getAccess());
8799 UnresolvedReductions.push_back(
8800 UnresolvedLookupExpr::Create(
8801 SemaRef.Context, /*NamingClass=*/nullptr,
8802 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8803 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8804 Decls.begin(), Decls.end()));
8806 UnresolvedReductions.push_back(nullptr);
8808 return getDerived().RebuildOMPReductionClause(
8809 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8810 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8813 template <typename Derived>
8814 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8815 OMPTaskReductionClause *C) {
8816 llvm::SmallVector<Expr *, 16> Vars;
8817 Vars.reserve(C->varlist_size());
8818 for (auto *VE : C->varlists()) {
8819 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8820 if (EVar.isInvalid())
8822 Vars.push_back(EVar.get());
8824 CXXScopeSpec ReductionIdScopeSpec;
8825 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8827 DeclarationNameInfo NameInfo = C->getNameInfo();
8828 if (NameInfo.getName()) {
8829 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8830 if (!NameInfo.getName())
8833 // Build a list of all UDR decls with the same names ranged by the Scopes.
8834 // The Scope boundary is a duplication of the previous decl.
8835 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8836 for (auto *E : C->reduction_ops()) {
8837 // Transform all the decls.
8839 auto *ULE = cast<UnresolvedLookupExpr>(E);
8840 UnresolvedSet<8> Decls;
8841 for (auto *D : ULE->decls()) {
8843 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8844 Decls.addDecl(InstD, InstD->getAccess());
8846 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8847 SemaRef.Context, /*NamingClass=*/nullptr,
8848 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8849 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8851 UnresolvedReductions.push_back(nullptr);
8853 return getDerived().RebuildOMPTaskReductionClause(
8854 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8855 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8858 template <typename Derived>
8860 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8861 llvm::SmallVector<Expr *, 16> Vars;
8862 Vars.reserve(C->varlist_size());
8863 for (auto *VE : C->varlists()) {
8864 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8865 if (EVar.isInvalid())
8867 Vars.push_back(EVar.get());
8869 CXXScopeSpec ReductionIdScopeSpec;
8870 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8872 DeclarationNameInfo NameInfo = C->getNameInfo();
8873 if (NameInfo.getName()) {
8874 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8875 if (!NameInfo.getName())
8878 // Build a list of all UDR decls with the same names ranged by the Scopes.
8879 // The Scope boundary is a duplication of the previous decl.
8880 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8881 for (auto *E : C->reduction_ops()) {
8882 // Transform all the decls.
8884 auto *ULE = cast<UnresolvedLookupExpr>(E);
8885 UnresolvedSet<8> Decls;
8886 for (auto *D : ULE->decls()) {
8888 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8889 Decls.addDecl(InstD, InstD->getAccess());
8891 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8892 SemaRef.Context, /*NamingClass=*/nullptr,
8893 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8894 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8896 UnresolvedReductions.push_back(nullptr);
8898 return getDerived().RebuildOMPInReductionClause(
8899 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8900 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8903 template <typename Derived>
8905 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8906 llvm::SmallVector<Expr *, 16> Vars;
8907 Vars.reserve(C->varlist_size());
8908 for (auto *VE : C->varlists()) {
8909 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8910 if (EVar.isInvalid())
8912 Vars.push_back(EVar.get());
8914 ExprResult Step = getDerived().TransformExpr(C->getStep());
8915 if (Step.isInvalid())
8917 return getDerived().RebuildOMPLinearClause(
8918 Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8919 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8922 template <typename Derived>
8924 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8925 llvm::SmallVector<Expr *, 16> Vars;
8926 Vars.reserve(C->varlist_size());
8927 for (auto *VE : C->varlists()) {
8928 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8929 if (EVar.isInvalid())
8931 Vars.push_back(EVar.get());
8933 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8934 if (Alignment.isInvalid())
8936 return getDerived().RebuildOMPAlignedClause(
8937 Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8938 C->getColonLoc(), C->getEndLoc());
8941 template <typename Derived>
8943 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8944 llvm::SmallVector<Expr *, 16> Vars;
8945 Vars.reserve(C->varlist_size());
8946 for (auto *VE : C->varlists()) {
8947 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8948 if (EVar.isInvalid())
8950 Vars.push_back(EVar.get());
8952 return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8953 C->getLParenLoc(), C->getEndLoc());
8956 template <typename Derived>
8958 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8959 llvm::SmallVector<Expr *, 16> Vars;
8960 Vars.reserve(C->varlist_size());
8961 for (auto *VE : C->varlists()) {
8962 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8963 if (EVar.isInvalid())
8965 Vars.push_back(EVar.get());
8967 return getDerived().RebuildOMPCopyprivateClause(
8968 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8971 template <typename Derived>
8972 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8973 llvm::SmallVector<Expr *, 16> Vars;
8974 Vars.reserve(C->varlist_size());
8975 for (auto *VE : C->varlists()) {
8976 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8977 if (EVar.isInvalid())
8979 Vars.push_back(EVar.get());
8981 return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
8982 C->getLParenLoc(), C->getEndLoc());
8985 template <typename Derived>
8987 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8988 llvm::SmallVector<Expr *, 16> Vars;
8989 Vars.reserve(C->varlist_size());
8990 for (auto *VE : C->varlists()) {
8991 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8992 if (EVar.isInvalid())
8994 Vars.push_back(EVar.get());
8996 return getDerived().RebuildOMPDependClause(
8997 C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8998 C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9001 template <typename Derived>
9003 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9004 ExprResult E = getDerived().TransformExpr(C->getDevice());
9007 return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
9008 C->getLParenLoc(), C->getEndLoc());
9011 template <typename Derived, class T>
9012 bool transformOMPMappableExprListClause(
9013 TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9014 llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9015 DeclarationNameInfo &MapperIdInfo,
9016 llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9017 // Transform expressions in the list.
9018 Vars.reserve(C->varlist_size());
9019 for (auto *VE : C->varlists()) {
9020 ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9021 if (EVar.isInvalid())
9023 Vars.push_back(EVar.get());
9025 // Transform mapper scope specifier and identifier.
9026 NestedNameSpecifierLoc QualifierLoc;
9027 if (C->getMapperQualifierLoc()) {
9028 QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9029 C->getMapperQualifierLoc());
9033 MapperIdScopeSpec.Adopt(QualifierLoc);
9034 MapperIdInfo = C->getMapperIdInfo();
9035 if (MapperIdInfo.getName()) {
9036 MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9037 if (!MapperIdInfo.getName())
9040 // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9041 // the previous user-defined mapper lookup in dependent environment.
9042 for (auto *E : C->mapperlists()) {
9043 // Transform all the decls.
9045 auto *ULE = cast<UnresolvedLookupExpr>(E);
9046 UnresolvedSet<8> Decls;
9047 for (auto *D : ULE->decls()) {
9049 cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9050 Decls.addDecl(InstD, InstD->getAccess());
9052 UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9053 TT.getSema().Context, /*NamingClass=*/nullptr,
9054 MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9055 MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9058 UnresolvedMappers.push_back(nullptr);
9064 template <typename Derived>
9065 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9066 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9067 llvm::SmallVector<Expr *, 16> Vars;
9068 CXXScopeSpec MapperIdScopeSpec;
9069 DeclarationNameInfo MapperIdInfo;
9070 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9071 if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9072 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9074 return getDerived().RebuildOMPMapClause(
9075 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9076 MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9077 C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9080 template <typename Derived>
9082 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9083 Expr *Allocator = C->getAllocator();
9085 ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9086 if (AllocatorRes.isInvalid())
9088 Allocator = AllocatorRes.get();
9090 llvm::SmallVector<Expr *, 16> Vars;
9091 Vars.reserve(C->varlist_size());
9092 for (auto *VE : C->varlists()) {
9093 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9094 if (EVar.isInvalid())
9096 Vars.push_back(EVar.get());
9098 return getDerived().RebuildOMPAllocateClause(
9099 Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9103 template <typename Derived>
9105 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9106 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9109 return getDerived().RebuildOMPNumTeamsClause(
9110 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9113 template <typename Derived>
9115 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9116 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9119 return getDerived().RebuildOMPThreadLimitClause(
9120 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9123 template <typename Derived>
9125 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9126 ExprResult E = getDerived().TransformExpr(C->getPriority());
9129 return getDerived().RebuildOMPPriorityClause(
9130 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9133 template <typename Derived>
9135 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9136 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9139 return getDerived().RebuildOMPGrainsizeClause(
9140 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9143 template <typename Derived>
9145 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9146 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9149 return getDerived().RebuildOMPNumTasksClause(
9150 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9153 template <typename Derived>
9154 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9155 ExprResult E = getDerived().TransformExpr(C->getHint());
9158 return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9159 C->getLParenLoc(), C->getEndLoc());
9162 template <typename Derived>
9163 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9164 OMPDistScheduleClause *C) {
9165 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9168 return getDerived().RebuildOMPDistScheduleClause(
9169 C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9170 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9173 template <typename Derived>
9175 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9179 template <typename Derived>
9180 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9181 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9182 llvm::SmallVector<Expr *, 16> Vars;
9183 CXXScopeSpec MapperIdScopeSpec;
9184 DeclarationNameInfo MapperIdInfo;
9185 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9186 if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9187 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9189 return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9190 Locs, UnresolvedMappers);
9193 template <typename Derived>
9194 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9195 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9196 llvm::SmallVector<Expr *, 16> Vars;
9197 CXXScopeSpec MapperIdScopeSpec;
9198 DeclarationNameInfo MapperIdInfo;
9199 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9200 if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9201 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9203 return getDerived().RebuildOMPFromClause(
9204 Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9207 template <typename Derived>
9208 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9209 OMPUseDevicePtrClause *C) {
9210 llvm::SmallVector<Expr *, 16> Vars;
9211 Vars.reserve(C->varlist_size());
9212 for (auto *VE : C->varlists()) {
9213 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9214 if (EVar.isInvalid())
9216 Vars.push_back(EVar.get());
9218 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9219 return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9222 template <typename Derived>
9224 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9225 llvm::SmallVector<Expr *, 16> Vars;
9226 Vars.reserve(C->varlist_size());
9227 for (auto *VE : C->varlists()) {
9228 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9229 if (EVar.isInvalid())
9231 Vars.push_back(EVar.get());
9233 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9234 return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9237 //===----------------------------------------------------------------------===//
9238 // Expression transformation
9239 //===----------------------------------------------------------------------===//
9240 template<typename Derived>
9242 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9243 return TransformExpr(E->getSubExpr());
9246 template<typename Derived>
9248 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9249 if (!E->isTypeDependent())
9252 return getDerived().RebuildPredefinedExpr(E->getLocation(),
9256 template<typename Derived>
9258 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9259 NestedNameSpecifierLoc QualifierLoc;
9260 if (E->getQualifierLoc()) {
9262 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9268 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9273 NamedDecl *Found = ND;
9274 if (E->getFoundDecl() != E->getDecl()) {
9275 Found = cast_or_null<NamedDecl>(
9276 getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9281 DeclarationNameInfo NameInfo = E->getNameInfo();
9282 if (NameInfo.getName()) {
9283 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9284 if (!NameInfo.getName())
9288 if (!getDerived().AlwaysRebuild() &&
9289 QualifierLoc == E->getQualifierLoc() &&
9290 ND == E->getDecl() &&
9291 Found == E->getFoundDecl() &&
9292 NameInfo.getName() == E->getDecl()->getDeclName() &&
9293 !E->hasExplicitTemplateArgs()) {
9295 // Mark it referenced in the new context regardless.
9296 // FIXME: this is a bit instantiation-specific.
9297 SemaRef.MarkDeclRefReferenced(E);
9302 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9303 if (E->hasExplicitTemplateArgs()) {
9304 TemplateArgs = &TransArgs;
9305 TransArgs.setLAngleLoc(E->getLAngleLoc());
9306 TransArgs.setRAngleLoc(E->getRAngleLoc());
9307 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9308 E->getNumTemplateArgs(),
9313 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9314 Found, TemplateArgs);
9317 template<typename Derived>
9319 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9323 template <typename Derived>
9324 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9325 FixedPointLiteral *E) {
9329 template<typename Derived>
9331 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9335 template<typename Derived>
9337 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9341 template<typename Derived>
9343 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9347 template<typename Derived>
9349 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9353 template<typename Derived>
9355 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9356 if (FunctionDecl *FD = E->getDirectCallee())
9357 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9358 return SemaRef.MaybeBindToTemporary(E);
9361 template<typename Derived>
9363 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9364 ExprResult ControllingExpr =
9365 getDerived().TransformExpr(E->getControllingExpr());
9366 if (ControllingExpr.isInvalid())
9369 SmallVector<Expr *, 4> AssocExprs;
9370 SmallVector<TypeSourceInfo *, 4> AssocTypes;
9371 for (const GenericSelectionExpr::Association &Assoc : E->associations()) {
9372 TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9374 TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9377 AssocTypes.push_back(AssocType);
9379 AssocTypes.push_back(nullptr);
9382 ExprResult AssocExpr =
9383 getDerived().TransformExpr(Assoc.getAssociationExpr());
9384 if (AssocExpr.isInvalid())
9386 AssocExprs.push_back(AssocExpr.get());
9389 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9392 ControllingExpr.get(),
9397 template<typename Derived>
9399 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9400 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9401 if (SubExpr.isInvalid())
9404 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9407 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9411 /// The operand of a unary address-of operator has special rules: it's
9412 /// allowed to refer to a non-static member of a class even if there's no 'this'
9413 /// object available.
9414 template<typename Derived>
9416 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9417 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9418 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9420 return getDerived().TransformExpr(E);
9423 template<typename Derived>
9425 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9427 if (E->getOpcode() == UO_AddrOf)
9428 SubExpr = TransformAddressOfOperand(E->getSubExpr());
9430 SubExpr = TransformExpr(E->getSubExpr());
9431 if (SubExpr.isInvalid())
9434 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9437 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9442 template<typename Derived>
9444 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9445 // Transform the type.
9446 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9450 // Transform all of the components into components similar to what the
9452 // FIXME: It would be slightly more efficient in the non-dependent case to
9453 // just map FieldDecls, rather than requiring the rebuilder to look for
9454 // the fields again. However, __builtin_offsetof is rare enough in
9455 // template code that we don't care.
9456 bool ExprChanged = false;
9457 typedef Sema::OffsetOfComponent Component;
9458 SmallVector<Component, 4> Components;
9459 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9460 const OffsetOfNode &ON = E->getComponent(I);
9462 Comp.isBrackets = true;
9463 Comp.LocStart = ON.getSourceRange().getBegin();
9464 Comp.LocEnd = ON.getSourceRange().getEnd();
9465 switch (ON.getKind()) {
9466 case OffsetOfNode::Array: {
9467 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9468 ExprResult Index = getDerived().TransformExpr(FromIndex);
9469 if (Index.isInvalid())
9472 ExprChanged = ExprChanged || Index.get() != FromIndex;
9473 Comp.isBrackets = true;
9474 Comp.U.E = Index.get();
9478 case OffsetOfNode::Field:
9479 case OffsetOfNode::Identifier:
9480 Comp.isBrackets = false;
9481 Comp.U.IdentInfo = ON.getFieldName();
9482 if (!Comp.U.IdentInfo)
9487 case OffsetOfNode::Base:
9488 // Will be recomputed during the rebuild.
9492 Components.push_back(Comp);
9495 // If nothing changed, retain the existing expression.
9496 if (!getDerived().AlwaysRebuild() &&
9497 Type == E->getTypeSourceInfo() &&
9501 // Build a new offsetof expression.
9502 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9503 Components, E->getRParenLoc());
9506 template<typename Derived>
9508 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9509 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9510 "opaque value expression requires transformation");
9514 template<typename Derived>
9516 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9520 template<typename Derived>
9522 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9523 // Rebuild the syntactic form. The original syntactic form has
9524 // opaque-value expressions in it, so strip those away and rebuild
9525 // the result. This is a really awful way of doing this, but the
9526 // better solution (rebuilding the semantic expressions and
9527 // rebinding OVEs as necessary) doesn't work; we'd need
9528 // TreeTransform to not strip away implicit conversions.
9529 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9530 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9531 if (result.isInvalid()) return ExprError();
9533 // If that gives us a pseudo-object result back, the pseudo-object
9534 // expression must have been an lvalue-to-rvalue conversion which we
9536 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9537 result = SemaRef.checkPseudoObjectRValue(result.get());
9542 template<typename Derived>
9544 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9545 UnaryExprOrTypeTraitExpr *E) {
9546 if (E->isArgumentType()) {
9547 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9549 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9553 if (!getDerived().AlwaysRebuild() && OldT == NewT)
9556 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9558 E->getSourceRange());
9561 // C++0x [expr.sizeof]p1:
9562 // The operand is either an expression, which is an unevaluated operand
9564 EnterExpressionEvaluationContext Unevaluated(
9565 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9566 Sema::ReuseLambdaContextDecl);
9568 // Try to recover if we have something like sizeof(T::X) where X is a type.
9569 // Notably, there must be *exactly* one set of parens if X is a type.
9570 TypeSourceInfo *RecoveryTSI = nullptr;
9572 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9574 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9575 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9576 PE, DRE, false, &RecoveryTSI);
9578 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9581 return getDerived().RebuildUnaryExprOrTypeTrait(
9582 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9583 } else if (SubExpr.isInvalid())
9586 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9589 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9590 E->getOperatorLoc(),
9592 E->getSourceRange());
9595 template<typename Derived>
9597 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9598 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9599 if (LHS.isInvalid())
9602 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9603 if (RHS.isInvalid())
9607 if (!getDerived().AlwaysRebuild() &&
9608 LHS.get() == E->getLHS() &&
9609 RHS.get() == E->getRHS())
9612 return getDerived().RebuildArraySubscriptExpr(
9614 /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9617 template <typename Derived>
9619 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9620 ExprResult Base = getDerived().TransformExpr(E->getBase());
9621 if (Base.isInvalid())
9624 ExprResult LowerBound;
9625 if (E->getLowerBound()) {
9626 LowerBound = getDerived().TransformExpr(E->getLowerBound());
9627 if (LowerBound.isInvalid())
9632 if (E->getLength()) {
9633 Length = getDerived().TransformExpr(E->getLength());
9634 if (Length.isInvalid())
9638 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9639 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9642 return getDerived().RebuildOMPArraySectionExpr(
9643 Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9644 Length.get(), E->getRBracketLoc());
9647 template<typename Derived>
9649 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9650 // Transform the callee.
9651 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9652 if (Callee.isInvalid())
9655 // Transform arguments.
9656 bool ArgChanged = false;
9657 SmallVector<Expr*, 8> Args;
9658 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9662 if (!getDerived().AlwaysRebuild() &&
9663 Callee.get() == E->getCallee() &&
9665 return SemaRef.MaybeBindToTemporary(E);
9667 // FIXME: Wrong source location information for the '('.
9668 SourceLocation FakeLParenLoc
9669 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9670 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9675 template<typename Derived>
9677 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9678 ExprResult Base = getDerived().TransformExpr(E->getBase());
9679 if (Base.isInvalid())
9682 NestedNameSpecifierLoc QualifierLoc;
9683 if (E->hasQualifier()) {
9685 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9690 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9693 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9694 E->getMemberDecl()));
9698 NamedDecl *FoundDecl = E->getFoundDecl();
9699 if (FoundDecl == E->getMemberDecl()) {
9702 FoundDecl = cast_or_null<NamedDecl>(
9703 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9708 if (!getDerived().AlwaysRebuild() &&
9709 Base.get() == E->getBase() &&
9710 QualifierLoc == E->getQualifierLoc() &&
9711 Member == E->getMemberDecl() &&
9712 FoundDecl == E->getFoundDecl() &&
9713 !E->hasExplicitTemplateArgs()) {
9715 // Mark it referenced in the new context regardless.
9716 // FIXME: this is a bit instantiation-specific.
9717 SemaRef.MarkMemberReferenced(E);
9722 TemplateArgumentListInfo TransArgs;
9723 if (E->hasExplicitTemplateArgs()) {
9724 TransArgs.setLAngleLoc(E->getLAngleLoc());
9725 TransArgs.setRAngleLoc(E->getRAngleLoc());
9726 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9727 E->getNumTemplateArgs(),
9732 // FIXME: Bogus source location for the operator
9733 SourceLocation FakeOperatorLoc =
9734 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9736 // FIXME: to do this check properly, we will need to preserve the
9737 // first-qualifier-in-scope here, just in case we had a dependent
9738 // base (and therefore couldn't do the check) and a
9739 // nested-name-qualifier (and therefore could do the lookup).
9740 NamedDecl *FirstQualifierInScope = nullptr;
9741 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9742 if (MemberNameInfo.getName()) {
9743 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9744 if (!MemberNameInfo.getName())
9748 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9755 (E->hasExplicitTemplateArgs()
9756 ? &TransArgs : nullptr),
9757 FirstQualifierInScope);
9760 template<typename Derived>
9762 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9763 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9764 if (LHS.isInvalid())
9767 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9768 if (RHS.isInvalid())
9771 if (!getDerived().AlwaysRebuild() &&
9772 LHS.get() == E->getLHS() &&
9773 RHS.get() == E->getRHS())
9776 Sema::FPContractStateRAII FPContractState(getSema());
9777 getSema().FPFeatures = E->getFPFeatures();
9779 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9780 LHS.get(), RHS.get());
9783 template <typename Derived>
9784 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
9785 CXXRewrittenBinaryOperator *E) {
9786 CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
9788 ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
9789 if (LHS.isInvalid())
9792 ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
9793 if (RHS.isInvalid())
9796 if (!getDerived().AlwaysRebuild() &&
9797 LHS.get() == Decomp.LHS &&
9798 RHS.get() == Decomp.RHS)
9801 // Extract the already-resolved callee declarations so that we can restrict
9802 // ourselves to using them as the unqualified lookup results when rebuilding.
9803 UnresolvedSet<2> UnqualLookups;
9804 Expr *PossibleBinOps[] = {E->getSemanticForm(),
9805 const_cast<Expr *>(Decomp.InnerBinOp)};
9806 for (Expr *PossibleBinOp : PossibleBinOps) {
9807 auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
9810 auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
9811 if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
9814 // Transform the callee in case we built a call to a local extern
9816 NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
9817 E->getOperatorLoc(), Callee->getFoundDecl()));
9820 UnqualLookups.addDecl(Found);
9823 return getDerived().RebuildCXXRewrittenBinaryOperator(
9824 E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
9827 template<typename Derived>
9829 TreeTransform<Derived>::TransformCompoundAssignOperator(
9830 CompoundAssignOperator *E) {
9831 return getDerived().TransformBinaryOperator(E);
9834 template<typename Derived>
9835 ExprResult TreeTransform<Derived>::
9836 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9837 // Just rebuild the common and RHS expressions and see whether we
9840 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9841 if (commonExpr.isInvalid())
9844 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9845 if (rhs.isInvalid())
9848 if (!getDerived().AlwaysRebuild() &&
9849 commonExpr.get() == e->getCommon() &&
9850 rhs.get() == e->getFalseExpr())
9853 return getDerived().RebuildConditionalOperator(commonExpr.get(),
9854 e->getQuestionLoc(),
9860 template<typename Derived>
9862 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9863 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9864 if (Cond.isInvalid())
9867 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9868 if (LHS.isInvalid())
9871 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9872 if (RHS.isInvalid())
9875 if (!getDerived().AlwaysRebuild() &&
9876 Cond.get() == E->getCond() &&
9877 LHS.get() == E->getLHS() &&
9878 RHS.get() == E->getRHS())
9881 return getDerived().RebuildConditionalOperator(Cond.get(),
9882 E->getQuestionLoc(),
9888 template<typename Derived>
9890 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9891 // Implicit casts are eliminated during transformation, since they
9892 // will be recomputed by semantic analysis after transformation.
9893 return getDerived().TransformExpr(E->getSubExprAsWritten());
9896 template<typename Derived>
9898 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9899 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9904 = getDerived().TransformExpr(E->getSubExprAsWritten());
9905 if (SubExpr.isInvalid())
9908 if (!getDerived().AlwaysRebuild() &&
9909 Type == E->getTypeInfoAsWritten() &&
9910 SubExpr.get() == E->getSubExpr())
9913 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9919 template<typename Derived>
9921 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9922 TypeSourceInfo *OldT = E->getTypeSourceInfo();
9923 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9927 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9928 if (Init.isInvalid())
9931 if (!getDerived().AlwaysRebuild() &&
9933 Init.get() == E->getInitializer())
9934 return SemaRef.MaybeBindToTemporary(E);
9936 // Note: the expression type doesn't necessarily match the
9937 // type-as-written, but that's okay, because it should always be
9938 // derivable from the initializer.
9940 return getDerived().RebuildCompoundLiteralExpr(
9941 E->getLParenLoc(), NewT,
9942 /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
9945 template<typename Derived>
9947 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9948 ExprResult Base = getDerived().TransformExpr(E->getBase());
9949 if (Base.isInvalid())
9952 if (!getDerived().AlwaysRebuild() &&
9953 Base.get() == E->getBase())
9956 // FIXME: Bad source location
9957 SourceLocation FakeOperatorLoc =
9958 SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
9959 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9960 E->getAccessorLoc(),
9964 template<typename Derived>
9966 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9967 if (InitListExpr *Syntactic = E->getSyntacticForm())
9970 bool InitChanged = false;
9972 EnterExpressionEvaluationContext Context(
9973 getSema(), EnterExpressionEvaluationContext::InitList);
9975 SmallVector<Expr*, 4> Inits;
9976 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9977 Inits, &InitChanged))
9980 if (!getDerived().AlwaysRebuild() && !InitChanged) {
9981 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9982 // in some cases. We can't reuse it in general, because the syntactic and
9983 // semantic forms are linked, and we can't know that semantic form will
9984 // match even if the syntactic form does.
9987 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9991 template<typename Derived>
9993 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9996 // transform the initializer value
9997 ExprResult Init = getDerived().TransformExpr(E->getInit());
9998 if (Init.isInvalid())
10001 // transform the designators.
10002 SmallVector<Expr*, 4> ArrayExprs;
10003 bool ExprChanged = false;
10004 for (const DesignatedInitExpr::Designator &D : E->designators()) {
10005 if (D.isFieldDesignator()) {
10006 Desig.AddDesignator(Designator::getField(D.getFieldName(),
10009 if (D.getField()) {
10010 FieldDecl *Field = cast_or_null<FieldDecl>(
10011 getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
10012 if (Field != D.getField())
10013 // Rebuild the expression when the transformed FieldDecl is
10014 // different to the already assigned FieldDecl.
10015 ExprChanged = true;
10017 // Ensure that the designator expression is rebuilt when there isn't
10018 // a resolved FieldDecl in the designator as we don't want to assign
10019 // a FieldDecl to a pattern designator that will be instantiated again.
10020 ExprChanged = true;
10025 if (D.isArrayDesignator()) {
10026 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
10027 if (Index.isInvalid())
10028 return ExprError();
10030 Desig.AddDesignator(
10031 Designator::getArray(Index.get(), D.getLBracketLoc()));
10033 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
10034 ArrayExprs.push_back(Index.get());
10038 assert(D.isArrayRangeDesignator() && "New kind of designator?");
10040 = getDerived().TransformExpr(E->getArrayRangeStart(D));
10041 if (Start.isInvalid())
10042 return ExprError();
10044 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
10045 if (End.isInvalid())
10046 return ExprError();
10048 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
10050 D.getLBracketLoc(),
10051 D.getEllipsisLoc()));
10053 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
10054 End.get() != E->getArrayRangeEnd(D);
10056 ArrayExprs.push_back(Start.get());
10057 ArrayExprs.push_back(End.get());
10060 if (!getDerived().AlwaysRebuild() &&
10061 Init.get() == E->getInit() &&
10065 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
10066 E->getEqualOrColonLoc(),
10067 E->usesGNUSyntax(), Init.get());
10070 // Seems that if TransformInitListExpr() only works on the syntactic form of an
10071 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
10072 template<typename Derived>
10074 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
10075 DesignatedInitUpdateExpr *E) {
10076 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
10078 return ExprError();
10081 template<typename Derived>
10083 TreeTransform<Derived>::TransformNoInitExpr(
10085 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
10086 return ExprError();
10089 template<typename Derived>
10091 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
10092 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
10093 return ExprError();
10096 template<typename Derived>
10098 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
10099 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
10100 return ExprError();
10103 template<typename Derived>
10105 TreeTransform<Derived>::TransformImplicitValueInitExpr(
10106 ImplicitValueInitExpr *E) {
10107 TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
10109 // FIXME: Will we ever have proper type location here? Will we actually
10110 // need to transform the type?
10111 QualType T = getDerived().TransformType(E->getType());
10113 return ExprError();
10115 if (!getDerived().AlwaysRebuild() &&
10119 return getDerived().RebuildImplicitValueInitExpr(T);
10122 template<typename Derived>
10124 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10125 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10127 return ExprError();
10129 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10130 if (SubExpr.isInvalid())
10131 return ExprError();
10133 if (!getDerived().AlwaysRebuild() &&
10134 TInfo == E->getWrittenTypeInfo() &&
10135 SubExpr.get() == E->getSubExpr())
10138 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10139 TInfo, E->getRParenLoc());
10142 template<typename Derived>
10144 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10145 bool ArgumentChanged = false;
10146 SmallVector<Expr*, 4> Inits;
10147 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10149 return ExprError();
10151 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10153 E->getRParenLoc());
10156 /// Transform an address-of-label expression.
10158 /// By default, the transformation of an address-of-label expression always
10159 /// rebuilds the expression, so that the label identifier can be resolved to
10160 /// the corresponding label statement by semantic analysis.
10161 template<typename Derived>
10163 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10164 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10167 return ExprError();
10169 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10170 cast<LabelDecl>(LD));
10173 template<typename Derived>
10175 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10176 SemaRef.ActOnStartStmtExpr();
10178 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10179 if (SubStmt.isInvalid()) {
10180 SemaRef.ActOnStmtExprError();
10181 return ExprError();
10184 if (!getDerived().AlwaysRebuild() &&
10185 SubStmt.get() == E->getSubStmt()) {
10186 // Calling this an 'error' is unintuitive, but it does the right thing.
10187 SemaRef.ActOnStmtExprError();
10188 return SemaRef.MaybeBindToTemporary(E);
10191 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
10193 E->getRParenLoc());
10196 template<typename Derived>
10198 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10199 ExprResult Cond = getDerived().TransformExpr(E->getCond());
10200 if (Cond.isInvalid())
10201 return ExprError();
10203 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10204 if (LHS.isInvalid())
10205 return ExprError();
10207 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10208 if (RHS.isInvalid())
10209 return ExprError();
10211 if (!getDerived().AlwaysRebuild() &&
10212 Cond.get() == E->getCond() &&
10213 LHS.get() == E->getLHS() &&
10214 RHS.get() == E->getRHS())
10217 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10218 Cond.get(), LHS.get(), RHS.get(),
10219 E->getRParenLoc());
10222 template<typename Derived>
10224 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10228 template<typename Derived>
10230 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10231 switch (E->getOperator()) {
10235 case OO_Array_Delete:
10236 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
10239 // This is a call to an object's operator().
10240 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
10242 // Transform the object itself.
10243 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10244 if (Object.isInvalid())
10245 return ExprError();
10247 // FIXME: Poor location information
10248 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10249 static_cast<Expr *>(Object.get())->getEndLoc());
10251 // Transform the call arguments.
10252 SmallVector<Expr*, 8> Args;
10253 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10255 return ExprError();
10257 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10261 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10263 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10264 #include "clang/Basic/OperatorKinds.def"
10269 case OO_Conditional:
10270 llvm_unreachable("conditional operator is not actually overloadable");
10273 case NUM_OVERLOADED_OPERATORS:
10274 llvm_unreachable("not an overloaded operator?");
10277 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10278 if (Callee.isInvalid())
10279 return ExprError();
10282 if (E->getOperator() == OO_Amp)
10283 First = getDerived().TransformAddressOfOperand(E->getArg(0));
10285 First = getDerived().TransformExpr(E->getArg(0));
10286 if (First.isInvalid())
10287 return ExprError();
10290 if (E->getNumArgs() == 2) {
10291 Second = getDerived().TransformExpr(E->getArg(1));
10292 if (Second.isInvalid())
10293 return ExprError();
10296 if (!getDerived().AlwaysRebuild() &&
10297 Callee.get() == E->getCallee() &&
10298 First.get() == E->getArg(0) &&
10299 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10300 return SemaRef.MaybeBindToTemporary(E);
10302 Sema::FPContractStateRAII FPContractState(getSema());
10303 getSema().FPFeatures = E->getFPFeatures();
10305 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10306 E->getOperatorLoc(),
10312 template<typename Derived>
10314 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10315 return getDerived().TransformCallExpr(E);
10318 template <typename Derived>
10319 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10320 bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10321 getSema().CurContext != E->getParentContext();
10323 if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10326 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10328 getSema().CurContext);
10331 template<typename Derived>
10333 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10334 // Transform the callee.
10335 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10336 if (Callee.isInvalid())
10337 return ExprError();
10339 // Transform exec config.
10340 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10341 if (EC.isInvalid())
10342 return ExprError();
10344 // Transform arguments.
10345 bool ArgChanged = false;
10346 SmallVector<Expr*, 8> Args;
10347 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10349 return ExprError();
10351 if (!getDerived().AlwaysRebuild() &&
10352 Callee.get() == E->getCallee() &&
10354 return SemaRef.MaybeBindToTemporary(E);
10356 // FIXME: Wrong source location information for the '('.
10357 SourceLocation FakeLParenLoc
10358 = ((Expr *)Callee.get())->getSourceRange().getBegin();
10359 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10361 E->getRParenLoc(), EC.get());
10364 template<typename Derived>
10366 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10367 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10369 return ExprError();
10372 = getDerived().TransformExpr(E->getSubExprAsWritten());
10373 if (SubExpr.isInvalid())
10374 return ExprError();
10376 if (!getDerived().AlwaysRebuild() &&
10377 Type == E->getTypeInfoAsWritten() &&
10378 SubExpr.get() == E->getSubExpr())
10380 return getDerived().RebuildCXXNamedCastExpr(
10381 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10382 Type, E->getAngleBrackets().getEnd(),
10383 // FIXME. this should be '(' location
10384 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10387 template<typename Derived>
10389 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10390 TypeSourceInfo *TSI =
10391 getDerived().TransformType(BCE->getTypeInfoAsWritten());
10393 return ExprError();
10395 ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10396 if (Sub.isInvalid())
10397 return ExprError();
10399 return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10400 Sub.get(), BCE->getEndLoc());
10403 template<typename Derived>
10405 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10406 return getDerived().TransformCXXNamedCastExpr(E);
10409 template<typename Derived>
10411 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10412 return getDerived().TransformCXXNamedCastExpr(E);
10415 template<typename Derived>
10417 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10418 CXXReinterpretCastExpr *E) {
10419 return getDerived().TransformCXXNamedCastExpr(E);
10422 template<typename Derived>
10424 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10425 return getDerived().TransformCXXNamedCastExpr(E);
10428 template<typename Derived>
10430 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10431 CXXFunctionalCastExpr *E) {
10432 TypeSourceInfo *Type =
10433 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10435 return ExprError();
10438 = getDerived().TransformExpr(E->getSubExprAsWritten());
10439 if (SubExpr.isInvalid())
10440 return ExprError();
10442 if (!getDerived().AlwaysRebuild() &&
10443 Type == E->getTypeInfoAsWritten() &&
10444 SubExpr.get() == E->getSubExpr())
10447 return getDerived().RebuildCXXFunctionalCastExpr(Type,
10451 E->isListInitialization());
10454 template<typename Derived>
10456 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10457 if (E->isTypeOperand()) {
10458 TypeSourceInfo *TInfo
10459 = getDerived().TransformType(E->getTypeOperandSourceInfo());
10461 return ExprError();
10463 if (!getDerived().AlwaysRebuild() &&
10464 TInfo == E->getTypeOperandSourceInfo())
10467 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10468 TInfo, E->getEndLoc());
10471 // We don't know whether the subexpression is potentially evaluated until
10472 // after we perform semantic analysis. We speculatively assume it is
10473 // unevaluated; it will get fixed later if the subexpression is in fact
10474 // potentially evaluated.
10475 EnterExpressionEvaluationContext Unevaluated(
10476 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10477 Sema::ReuseLambdaContextDecl);
10479 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10480 if (SubExpr.isInvalid())
10481 return ExprError();
10483 if (!getDerived().AlwaysRebuild() &&
10484 SubExpr.get() == E->getExprOperand())
10487 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10488 SubExpr.get(), E->getEndLoc());
10491 template<typename Derived>
10493 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10494 if (E->isTypeOperand()) {
10495 TypeSourceInfo *TInfo
10496 = getDerived().TransformType(E->getTypeOperandSourceInfo());
10498 return ExprError();
10500 if (!getDerived().AlwaysRebuild() &&
10501 TInfo == E->getTypeOperandSourceInfo())
10504 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10505 TInfo, E->getEndLoc());
10508 EnterExpressionEvaluationContext Unevaluated(
10509 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10511 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10512 if (SubExpr.isInvalid())
10513 return ExprError();
10515 if (!getDerived().AlwaysRebuild() &&
10516 SubExpr.get() == E->getExprOperand())
10519 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10520 SubExpr.get(), E->getEndLoc());
10523 template<typename Derived>
10525 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10529 template<typename Derived>
10531 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10532 CXXNullPtrLiteralExpr *E) {
10536 template<typename Derived>
10538 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10539 QualType T = getSema().getCurrentThisType();
10541 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10542 // Mark it referenced in the new context regardless.
10543 // FIXME: this is a bit instantiation-specific.
10544 getSema().MarkThisReferenced(E);
10548 return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10551 template<typename Derived>
10553 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10554 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10555 if (SubExpr.isInvalid())
10556 return ExprError();
10558 if (!getDerived().AlwaysRebuild() &&
10559 SubExpr.get() == E->getSubExpr())
10562 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10563 E->isThrownVariableInScope());
10566 template<typename Derived>
10568 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10569 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10570 getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10572 return ExprError();
10574 if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10575 E->getUsedContext() == SemaRef.CurContext)
10578 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10581 template<typename Derived>
10583 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10584 FieldDecl *Field = cast_or_null<FieldDecl>(
10585 getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10587 return ExprError();
10589 if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10590 E->getUsedContext() == SemaRef.CurContext)
10593 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10596 template<typename Derived>
10598 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10599 CXXScalarValueInitExpr *E) {
10600 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10602 return ExprError();
10604 if (!getDerived().AlwaysRebuild() &&
10605 T == E->getTypeSourceInfo())
10608 return getDerived().RebuildCXXScalarValueInitExpr(T,
10609 /*FIXME:*/T->getTypeLoc().getEndLoc(),
10610 E->getRParenLoc());
10613 template<typename Derived>
10615 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10616 // Transform the type that we're allocating
10617 TypeSourceInfo *AllocTypeInfo =
10618 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10619 if (!AllocTypeInfo)
10620 return ExprError();
10622 // Transform the size of the array we're allocating (if any).
10623 Optional<Expr *> ArraySize;
10624 if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10625 ExprResult NewArraySize;
10626 if (*OldArraySize) {
10627 NewArraySize = getDerived().TransformExpr(*OldArraySize);
10628 if (NewArraySize.isInvalid())
10629 return ExprError();
10631 ArraySize = NewArraySize.get();
10634 // Transform the placement arguments (if any).
10635 bool ArgumentChanged = false;
10636 SmallVector<Expr*, 8> PlacementArgs;
10637 if (getDerived().TransformExprs(E->getPlacementArgs(),
10638 E->getNumPlacementArgs(), true,
10639 PlacementArgs, &ArgumentChanged))
10640 return ExprError();
10642 // Transform the initializer (if any).
10643 Expr *OldInit = E->getInitializer();
10644 ExprResult NewInit;
10646 NewInit = getDerived().TransformInitializer(OldInit, true);
10647 if (NewInit.isInvalid())
10648 return ExprError();
10650 // Transform new operator and delete operator.
10651 FunctionDecl *OperatorNew = nullptr;
10652 if (E->getOperatorNew()) {
10653 OperatorNew = cast_or_null<FunctionDecl>(
10654 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10656 return ExprError();
10659 FunctionDecl *OperatorDelete = nullptr;
10660 if (E->getOperatorDelete()) {
10661 OperatorDelete = cast_or_null<FunctionDecl>(
10662 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10663 if (!OperatorDelete)
10664 return ExprError();
10667 if (!getDerived().AlwaysRebuild() &&
10668 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10669 ArraySize == E->getArraySize() &&
10670 NewInit.get() == OldInit &&
10671 OperatorNew == E->getOperatorNew() &&
10672 OperatorDelete == E->getOperatorDelete() &&
10673 !ArgumentChanged) {
10674 // Mark any declarations we need as referenced.
10675 // FIXME: instantiation-specific.
10677 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10678 if (OperatorDelete)
10679 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10681 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10682 QualType ElementType
10683 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10684 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10685 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10686 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10687 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10695 QualType AllocType = AllocTypeInfo->getType();
10697 // If no array size was specified, but the new expression was
10698 // instantiated with an array type (e.g., "new T" where T is
10699 // instantiated with "int[4]"), extract the outer bound from the
10700 // array type as our array size. We do this with constant and
10701 // dependently-sized array types.
10702 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10705 } else if (const ConstantArrayType *ConsArrayT
10706 = dyn_cast<ConstantArrayType>(ArrayT)) {
10707 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10708 SemaRef.Context.getSizeType(),
10709 /*FIXME:*/ E->getBeginLoc());
10710 AllocType = ConsArrayT->getElementType();
10711 } else if (const DependentSizedArrayType *DepArrayT
10712 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10713 if (DepArrayT->getSizeExpr()) {
10714 ArraySize = DepArrayT->getSizeExpr();
10715 AllocType = DepArrayT->getElementType();
10720 return getDerived().RebuildCXXNewExpr(
10721 E->getBeginLoc(), E->isGlobalNew(),
10722 /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10723 /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10724 AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10727 template<typename Derived>
10729 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10730 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10731 if (Operand.isInvalid())
10732 return ExprError();
10734 // Transform the delete operator, if known.
10735 FunctionDecl *OperatorDelete = nullptr;
10736 if (E->getOperatorDelete()) {
10737 OperatorDelete = cast_or_null<FunctionDecl>(
10738 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10739 if (!OperatorDelete)
10740 return ExprError();
10743 if (!getDerived().AlwaysRebuild() &&
10744 Operand.get() == E->getArgument() &&
10745 OperatorDelete == E->getOperatorDelete()) {
10746 // Mark any declarations we need as referenced.
10747 // FIXME: instantiation-specific.
10748 if (OperatorDelete)
10749 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10751 if (!E->getArgument()->isTypeDependent()) {
10752 QualType Destroyed = SemaRef.Context.getBaseElementType(
10753 E->getDestroyedType());
10754 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10755 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10756 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10757 SemaRef.LookupDestructor(Record));
10764 return getDerived().RebuildCXXDeleteExpr(
10765 E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10768 template<typename Derived>
10770 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10771 CXXPseudoDestructorExpr *E) {
10772 ExprResult Base = getDerived().TransformExpr(E->getBase());
10773 if (Base.isInvalid())
10774 return ExprError();
10776 ParsedType ObjectTypePtr;
10777 bool MayBePseudoDestructor = false;
10778 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10779 E->getOperatorLoc(),
10780 E->isArrow()? tok::arrow : tok::period,
10782 MayBePseudoDestructor);
10783 if (Base.isInvalid())
10784 return ExprError();
10786 QualType ObjectType = ObjectTypePtr.get();
10787 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10788 if (QualifierLoc) {
10790 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10792 return ExprError();
10795 SS.Adopt(QualifierLoc);
10797 PseudoDestructorTypeStorage Destroyed;
10798 if (E->getDestroyedTypeInfo()) {
10799 TypeSourceInfo *DestroyedTypeInfo
10800 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10801 ObjectType, nullptr, SS);
10802 if (!DestroyedTypeInfo)
10803 return ExprError();
10804 Destroyed = DestroyedTypeInfo;
10805 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10806 // We aren't likely to be able to resolve the identifier down to a type
10807 // now anyway, so just retain the identifier.
10808 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10809 E->getDestroyedTypeLoc());
10811 // Look for a destructor known with the given name.
10812 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10813 *E->getDestroyedTypeIdentifier(),
10814 E->getDestroyedTypeLoc(),
10819 return ExprError();
10822 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10823 E->getDestroyedTypeLoc());
10826 TypeSourceInfo *ScopeTypeInfo = nullptr;
10827 if (E->getScopeTypeInfo()) {
10828 CXXScopeSpec EmptySS;
10829 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10830 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10831 if (!ScopeTypeInfo)
10832 return ExprError();
10835 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10836 E->getOperatorLoc(),
10840 E->getColonColonLoc(),
10845 template <typename Derived>
10846 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10849 // Transform all the decls.
10850 bool AllEmptyPacks = true;
10851 for (auto *OldD : Old->decls()) {
10852 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10854 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10855 // This can happen because of dependent hiding.
10856 if (isa<UsingShadowDecl>(OldD))
10864 // Expand using pack declarations.
10865 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10866 ArrayRef<NamedDecl*> Decls = SingleDecl;
10867 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10868 Decls = UPD->expansions();
10870 // Expand using declarations.
10871 for (auto *D : Decls) {
10872 if (auto *UD = dyn_cast<UsingDecl>(D)) {
10873 for (auto *SD : UD->shadows())
10880 AllEmptyPacks &= Decls.empty();
10883 // C++ [temp.res]/8.4.2:
10884 // The program is ill-formed, no diagnostic required, if [...] lookup for
10885 // a name in the template definition found a using-declaration, but the
10886 // lookup in the corresponding scope in the instantiation odoes not find
10887 // any declarations because the using-declaration was a pack expansion and
10888 // the corresponding pack is empty
10889 if (AllEmptyPacks && !RequiresADL) {
10890 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10891 << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10895 // Resolve a kind, but don't do any further analysis. If it's
10896 // ambiguous, the callee needs to deal with it.
10901 template<typename Derived>
10903 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10904 UnresolvedLookupExpr *Old) {
10905 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10906 Sema::LookupOrdinaryName);
10908 // Transform the declaration set.
10909 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10910 return ExprError();
10912 // Rebuild the nested-name qualifier, if present.
10914 if (Old->getQualifierLoc()) {
10915 NestedNameSpecifierLoc QualifierLoc
10916 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10918 return ExprError();
10920 SS.Adopt(QualifierLoc);
10923 if (Old->getNamingClass()) {
10924 CXXRecordDecl *NamingClass
10925 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10927 Old->getNamingClass()));
10928 if (!NamingClass) {
10930 return ExprError();
10933 R.setNamingClass(NamingClass);
10936 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10938 // If we have neither explicit template arguments, nor the template keyword,
10939 // it's a normal declaration name or member reference.
10940 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10941 NamedDecl *D = R.getAsSingle<NamedDecl>();
10942 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10943 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10944 // give a good diagnostic.
10945 if (D && D->isCXXInstanceMember()) {
10946 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10947 /*TemplateArgs=*/nullptr,
10948 /*Scope=*/nullptr);
10951 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10954 // If we have template arguments, rebuild them, then rebuild the
10955 // templateid expression.
10956 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10957 if (Old->hasExplicitTemplateArgs() &&
10958 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10959 Old->getNumTemplateArgs(),
10962 return ExprError();
10965 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10966 Old->requiresADL(), &TransArgs);
10969 template<typename Derived>
10971 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10972 bool ArgChanged = false;
10973 SmallVector<TypeSourceInfo *, 4> Args;
10974 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10975 TypeSourceInfo *From = E->getArg(I);
10976 TypeLoc FromTL = From->getTypeLoc();
10977 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10978 TypeLocBuilder TLB;
10979 TLB.reserve(FromTL.getFullDataSize());
10980 QualType To = getDerived().TransformType(TLB, FromTL);
10982 return ExprError();
10984 if (To == From->getType())
10985 Args.push_back(From);
10987 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10995 // We have a pack expansion. Instantiate it.
10996 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10997 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10998 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10999 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
11001 // Determine whether the set of unexpanded parameter packs can and should
11003 bool Expand = true;
11004 bool RetainExpansion = false;
11005 Optional<unsigned> OrigNumExpansions =
11006 ExpansionTL.getTypePtr()->getNumExpansions();
11007 Optional<unsigned> NumExpansions = OrigNumExpansions;
11008 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
11009 PatternTL.getSourceRange(),
11011 Expand, RetainExpansion,
11013 return ExprError();
11016 // The transform has determined that we should perform a simple
11017 // transformation on the pack expansion, producing another pack
11019 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11021 TypeLocBuilder TLB;
11022 TLB.reserve(From->getTypeLoc().getFullDataSize());
11024 QualType To = getDerived().TransformType(TLB, PatternTL);
11026 return ExprError();
11028 To = getDerived().RebuildPackExpansionType(To,
11029 PatternTL.getSourceRange(),
11030 ExpansionTL.getEllipsisLoc(),
11033 return ExprError();
11035 PackExpansionTypeLoc ToExpansionTL
11036 = TLB.push<PackExpansionTypeLoc>(To);
11037 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11038 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11042 // Expand the pack expansion by substituting for each argument in the
11044 for (unsigned I = 0; I != *NumExpansions; ++I) {
11045 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
11046 TypeLocBuilder TLB;
11047 TLB.reserve(PatternTL.getFullDataSize());
11048 QualType To = getDerived().TransformType(TLB, PatternTL);
11050 return ExprError();
11052 if (To->containsUnexpandedParameterPack()) {
11053 To = getDerived().RebuildPackExpansionType(To,
11054 PatternTL.getSourceRange(),
11055 ExpansionTL.getEllipsisLoc(),
11058 return ExprError();
11060 PackExpansionTypeLoc ToExpansionTL
11061 = TLB.push<PackExpansionTypeLoc>(To);
11062 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11065 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11068 if (!RetainExpansion)
11071 // If we're supposed to retain a pack expansion, do so by temporarily
11072 // forgetting the partially-substituted parameter pack.
11073 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11075 TypeLocBuilder TLB;
11076 TLB.reserve(From->getTypeLoc().getFullDataSize());
11078 QualType To = getDerived().TransformType(TLB, PatternTL);
11080 return ExprError();
11082 To = getDerived().RebuildPackExpansionType(To,
11083 PatternTL.getSourceRange(),
11084 ExpansionTL.getEllipsisLoc(),
11087 return ExprError();
11089 PackExpansionTypeLoc ToExpansionTL
11090 = TLB.push<PackExpansionTypeLoc>(To);
11091 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11092 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11095 if (!getDerived().AlwaysRebuild() && !ArgChanged)
11098 return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
11102 template<typename Derived>
11104 TreeTransform<Derived>::TransformConceptSpecializationExpr(
11105 ConceptSpecializationExpr *E) {
11106 const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
11107 TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
11108 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11109 Old->NumTemplateArgs, TransArgs))
11110 return ExprError();
11112 return getDerived().RebuildConceptSpecializationExpr(
11113 E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
11114 E->getConceptNameLoc(), E->getFoundDecl(), E->getNamedConcept(),
11119 template<typename Derived>
11121 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
11122 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
11124 return ExprError();
11126 if (!getDerived().AlwaysRebuild() &&
11127 T == E->getQueriedTypeSourceInfo())
11130 ExprResult SubExpr;
11132 EnterExpressionEvaluationContext Unevaluated(
11133 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11134 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
11135 if (SubExpr.isInvalid())
11136 return ExprError();
11138 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11142 return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11143 SubExpr.get(), E->getEndLoc());
11146 template<typename Derived>
11148 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11149 ExprResult SubExpr;
11151 EnterExpressionEvaluationContext Unevaluated(
11152 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11153 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11154 if (SubExpr.isInvalid())
11155 return ExprError();
11157 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11161 return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11162 SubExpr.get(), E->getEndLoc());
11165 template <typename Derived>
11166 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11167 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11168 TypeSourceInfo **RecoveryTSI) {
11169 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11170 DRE, AddrTaken, RecoveryTSI);
11172 // Propagate both errors and recovered types, which return ExprEmpty.
11173 if (!NewDRE.isUsable())
11176 // We got an expr, wrap it up in parens.
11177 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11179 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11183 template <typename Derived>
11184 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11185 DependentScopeDeclRefExpr *E) {
11186 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11190 template<typename Derived>
11192 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11193 DependentScopeDeclRefExpr *E,
11194 bool IsAddressOfOperand,
11195 TypeSourceInfo **RecoveryTSI) {
11196 assert(E->getQualifierLoc());
11197 NestedNameSpecifierLoc QualifierLoc
11198 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11200 return ExprError();
11201 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11203 // TODO: If this is a conversion-function-id, verify that the
11204 // destination type name (if present) resolves the same way after
11205 // instantiation as it did in the local scope.
11207 DeclarationNameInfo NameInfo
11208 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11209 if (!NameInfo.getName())
11210 return ExprError();
11212 if (!E->hasExplicitTemplateArgs()) {
11213 if (!getDerived().AlwaysRebuild() &&
11214 QualifierLoc == E->getQualifierLoc() &&
11215 // Note: it is sufficient to compare the Name component of NameInfo:
11216 // if name has not changed, DNLoc has not changed either.
11217 NameInfo.getName() == E->getDeclName())
11220 return getDerived().RebuildDependentScopeDeclRefExpr(
11221 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11222 IsAddressOfOperand, RecoveryTSI);
11225 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11226 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11227 E->getNumTemplateArgs(),
11229 return ExprError();
11231 return getDerived().RebuildDependentScopeDeclRefExpr(
11232 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11236 template<typename Derived>
11238 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11239 // CXXConstructExprs other than for list-initialization and
11240 // CXXTemporaryObjectExpr are always implicit, so when we have
11241 // a 1-argument construction we just transform that argument.
11242 if ((E->getNumArgs() == 1 ||
11243 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11244 (!getDerived().DropCallArgument(E->getArg(0))) &&
11245 !E->isListInitialization())
11246 return getDerived().TransformExpr(E->getArg(0));
11248 TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11250 QualType T = getDerived().TransformType(E->getType());
11252 return ExprError();
11254 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11255 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11257 return ExprError();
11259 bool ArgumentChanged = false;
11260 SmallVector<Expr*, 8> Args;
11262 EnterExpressionEvaluationContext Context(
11263 getSema(), EnterExpressionEvaluationContext::InitList,
11264 E->isListInitialization());
11265 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11267 return ExprError();
11270 if (!getDerived().AlwaysRebuild() &&
11271 T == E->getType() &&
11272 Constructor == E->getConstructor() &&
11273 !ArgumentChanged) {
11274 // Mark the constructor as referenced.
11275 // FIXME: Instantiation-specific
11276 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11280 return getDerived().RebuildCXXConstructExpr(
11281 T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11282 E->hadMultipleCandidates(), E->isListInitialization(),
11283 E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11284 E->getConstructionKind(), E->getParenOrBraceRange());
11287 template<typename Derived>
11288 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11289 CXXInheritedCtorInitExpr *E) {
11290 QualType T = getDerived().TransformType(E->getType());
11292 return ExprError();
11294 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11295 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11297 return ExprError();
11299 if (!getDerived().AlwaysRebuild() &&
11300 T == E->getType() &&
11301 Constructor == E->getConstructor()) {
11302 // Mark the constructor as referenced.
11303 // FIXME: Instantiation-specific
11304 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11308 return getDerived().RebuildCXXInheritedCtorInitExpr(
11309 T, E->getLocation(), Constructor,
11310 E->constructsVBase(), E->inheritedFromVBase());
11313 /// Transform a C++ temporary-binding expression.
11315 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11316 /// transform the subexpression and return that.
11317 template<typename Derived>
11319 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11320 return getDerived().TransformExpr(E->getSubExpr());
11323 /// Transform a C++ expression that contains cleanups that should
11324 /// be run after the expression is evaluated.
11326 /// Since ExprWithCleanups nodes are implicitly generated, we
11327 /// just transform the subexpression and return that.
11328 template<typename Derived>
11330 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11331 return getDerived().TransformExpr(E->getSubExpr());
11334 template<typename Derived>
11336 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11337 CXXTemporaryObjectExpr *E) {
11338 TypeSourceInfo *T =
11339 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11341 return ExprError();
11343 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11344 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11346 return ExprError();
11348 bool ArgumentChanged = false;
11349 SmallVector<Expr*, 8> Args;
11350 Args.reserve(E->getNumArgs());
11352 EnterExpressionEvaluationContext Context(
11353 getSema(), EnterExpressionEvaluationContext::InitList,
11354 E->isListInitialization());
11355 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11357 return ExprError();
11360 if (!getDerived().AlwaysRebuild() &&
11361 T == E->getTypeSourceInfo() &&
11362 Constructor == E->getConstructor() &&
11363 !ArgumentChanged) {
11364 // FIXME: Instantiation-specific
11365 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11366 return SemaRef.MaybeBindToTemporary(E);
11369 // FIXME: We should just pass E->isListInitialization(), but we're not
11370 // prepared to handle list-initialization without a child InitListExpr.
11371 SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11372 return getDerived().RebuildCXXTemporaryObjectExpr(
11373 T, LParenLoc, Args, E->getEndLoc(),
11374 /*ListInitialization=*/LParenLoc.isInvalid());
11377 template<typename Derived>
11379 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11380 // Transform any init-capture expressions before entering the scope of the
11381 // lambda body, because they are not semantically within that scope.
11382 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11383 struct TransformedInitCapture {
11384 // The location of the ... if the result is retaining a pack expansion.
11385 SourceLocation EllipsisLoc;
11386 // Zero or more expansions of the init-capture.
11387 SmallVector<InitCaptureInfoTy, 4> Expansions;
11389 SmallVector<TransformedInitCapture, 4> InitCaptures;
11390 InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11391 for (LambdaExpr::capture_iterator C = E->capture_begin(),
11392 CEnd = E->capture_end();
11394 if (!E->isInitCapture(C))
11397 TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11398 VarDecl *OldVD = C->getCapturedVar();
11400 auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11401 Optional<unsigned> NumExpansions) {
11402 ExprResult NewExprInitResult = getDerived().TransformInitializer(
11403 OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11405 if (NewExprInitResult.isInvalid()) {
11406 Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11409 Expr *NewExprInit = NewExprInitResult.get();
11411 QualType NewInitCaptureType =
11412 getSema().buildLambdaInitCaptureInitialization(
11413 C->getLocation(), OldVD->getType()->isReferenceType(),
11414 EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11415 C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11417 Result.Expansions.push_back(
11418 InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11421 // If this is an init-capture pack, consider expanding the pack now.
11422 if (OldVD->isParameterPack()) {
11423 PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11425 .castAs<PackExpansionTypeLoc>();
11426 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11427 SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11429 // Determine whether the set of unexpanded parameter packs can and should
11431 bool Expand = true;
11432 bool RetainExpansion = false;
11433 Optional<unsigned> OrigNumExpansions =
11434 ExpansionTL.getTypePtr()->getNumExpansions();
11435 Optional<unsigned> NumExpansions = OrigNumExpansions;
11436 if (getDerived().TryExpandParameterPacks(
11437 ExpansionTL.getEllipsisLoc(),
11438 OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11439 RetainExpansion, NumExpansions))
11440 return ExprError();
11442 for (unsigned I = 0; I != *NumExpansions; ++I) {
11443 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11444 SubstInitCapture(SourceLocation(), None);
11447 if (!Expand || RetainExpansion) {
11448 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11449 SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11450 Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11453 SubstInitCapture(SourceLocation(), None);
11457 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11458 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11460 // Transform the template parameters, and add them to the current
11461 // instantiation scope. The null case is handled correctly.
11462 auto TPL = getDerived().TransformTemplateParameterList(
11463 E->getTemplateParameterList());
11464 LSI->GLTemplateParameterList = TPL;
11466 // Transform the type of the original lambda's call operator.
11467 // The transformation MUST be done in the CurrentInstantiationScope since
11468 // it introduces a mapping of the original to the newly created
11469 // transformed parameters.
11470 TypeSourceInfo *NewCallOpTSI = nullptr;
11472 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11473 FunctionProtoTypeLoc OldCallOpFPTL =
11474 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11476 TypeLocBuilder NewCallOpTLBuilder;
11477 SmallVector<QualType, 4> ExceptionStorage;
11478 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11479 QualType NewCallOpType = TransformFunctionProtoType(
11480 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11481 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11482 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11483 ExceptionStorage, Changed);
11485 if (NewCallOpType.isNull())
11486 return ExprError();
11487 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11491 // Create the local class that will describe the lambda.
11492 CXXRecordDecl *OldClass = E->getLambdaClass();
11493 CXXRecordDecl *Class
11494 = getSema().createLambdaClosureType(E->getIntroducerRange(),
11496 /*KnownDependent=*/false,
11497 E->getCaptureDefault());
11498 getDerived().transformedLocalDecl(OldClass, {Class});
11500 Optional<std::tuple<unsigned, bool, Decl *>> Mangling;
11501 if (getDerived().ReplacingOriginal())
11502 Mangling = std::make_tuple(OldClass->getLambdaManglingNumber(),
11503 OldClass->hasKnownLambdaInternalLinkage(),
11504 OldClass->getLambdaContextDecl());
11506 // Build the call operator.
11507 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11508 Class, E->getIntroducerRange(), NewCallOpTSI,
11509 E->getCallOperator()->getEndLoc(),
11510 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11511 E->getCallOperator()->getConstexprKind());
11513 LSI->CallOperator = NewCallOperator;
11515 for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11516 I != NumParams; ++I) {
11517 auto *P = NewCallOperator->getParamDecl(I);
11518 if (P->hasUninstantiatedDefaultArg()) {
11519 EnterExpressionEvaluationContext Eval(
11521 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11522 ExprResult R = getDerived().TransformExpr(
11523 E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11524 P->setDefaultArg(R.get());
11528 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11529 getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11531 // Number the lambda for linkage purposes if necessary.
11532 getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
11534 // Introduce the context of the call operator.
11535 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11536 /*NewThisContext*/false);
11538 // Enter the scope of the lambda.
11539 getSema().buildLambdaScope(LSI, NewCallOperator,
11540 E->getIntroducerRange(),
11541 E->getCaptureDefault(),
11542 E->getCaptureDefaultLoc(),
11543 E->hasExplicitParameters(),
11544 E->hasExplicitResultType(),
11547 bool Invalid = false;
11549 // Transform captures.
11550 for (LambdaExpr::capture_iterator C = E->capture_begin(),
11551 CEnd = E->capture_end();
11553 // When we hit the first implicit capture, tell Sema that we've finished
11554 // the list of explicit captures.
11555 if (C->isImplicit())
11558 // Capturing 'this' is trivial.
11559 if (C->capturesThis()) {
11560 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11561 /*BuildAndDiagnose*/ true, nullptr,
11562 C->getCaptureKind() == LCK_StarThis);
11565 // Captured expression will be recaptured during captured variables
11567 if (C->capturesVLAType())
11570 // Rebuild init-captures, including the implied field declaration.
11571 if (E->isInitCapture(C)) {
11572 TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11574 VarDecl *OldVD = C->getCapturedVar();
11575 llvm::SmallVector<Decl*, 4> NewVDs;
11577 for (InitCaptureInfoTy &Info : NewC.Expansions) {
11578 ExprResult Init = Info.first;
11579 QualType InitQualType = Info.second;
11580 if (Init.isInvalid() || InitQualType.isNull()) {
11584 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11585 OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11586 OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11591 NewVDs.push_back(NewVD);
11592 getSema().addInitCapture(LSI, NewVD);
11598 getDerived().transformedLocalDecl(OldVD, NewVDs);
11602 assert(C->capturesVariable() && "unexpected kind of lambda capture");
11604 // Determine the capture kind for Sema.
11605 Sema::TryCaptureKind Kind
11606 = C->isImplicit()? Sema::TryCapture_Implicit
11607 : C->getCaptureKind() == LCK_ByCopy
11608 ? Sema::TryCapture_ExplicitByVal
11609 : Sema::TryCapture_ExplicitByRef;
11610 SourceLocation EllipsisLoc;
11611 if (C->isPackExpansion()) {
11612 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11613 bool ShouldExpand = false;
11614 bool RetainExpansion = false;
11615 Optional<unsigned> NumExpansions;
11616 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11619 ShouldExpand, RetainExpansion,
11625 if (ShouldExpand) {
11626 // The transform has determined that we should perform an expansion;
11627 // transform and capture each of the arguments.
11628 // expansion of the pattern. Do so.
11629 VarDecl *Pack = C->getCapturedVar();
11630 for (unsigned I = 0; I != *NumExpansions; ++I) {
11631 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11632 VarDecl *CapturedVar
11633 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11635 if (!CapturedVar) {
11640 // Capture the transformed variable.
11641 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11644 // FIXME: Retain a pack expansion if RetainExpansion is true.
11649 EllipsisLoc = C->getEllipsisLoc();
11652 // Transform the captured variable.
11653 VarDecl *CapturedVar
11654 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11655 C->getCapturedVar()));
11656 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11661 // Capture the transformed variable.
11662 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11665 getSema().finishLambdaExplicitCaptures(LSI);
11667 // FIXME: Sema's lambda-building mechanism expects us to push an expression
11668 // evaluation context even if we're not transforming the function body.
11669 getSema().PushExpressionEvaluationContext(
11670 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11672 // Instantiate the body of the lambda expression.
11674 Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
11676 // ActOnLambda* will pop the function scope for us.
11677 FuncScopeCleanup.disable();
11679 if (Body.isInvalid()) {
11680 SavedContext.pop();
11681 getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11682 /*IsInstantiation=*/true);
11683 return ExprError();
11686 // Copy the LSI before ActOnFinishFunctionBody removes it.
11687 // FIXME: This is dumb. Store the lambda information somewhere that outlives
11688 // the call operator.
11689 auto LSICopy = *LSI;
11690 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11691 /*IsInstantiation*/ true);
11692 SavedContext.pop();
11694 return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11698 template<typename Derived>
11700 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
11701 return TransformStmt(S);
11704 template<typename Derived>
11706 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
11707 // Transform captures.
11708 for (LambdaExpr::capture_iterator C = E->capture_begin(),
11709 CEnd = E->capture_end();
11711 // When we hit the first implicit capture, tell Sema that we've finished
11712 // the list of explicit captures.
11713 if (!C->isImplicit())
11716 // Capturing 'this' is trivial.
11717 if (C->capturesThis()) {
11718 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11719 /*BuildAndDiagnose*/ true, nullptr,
11720 C->getCaptureKind() == LCK_StarThis);
11723 // Captured expression will be recaptured during captured variables
11725 if (C->capturesVLAType())
11728 assert(C->capturesVariable() && "unexpected kind of lambda capture");
11729 assert(!E->isInitCapture(C) && "implicit init-capture?");
11731 // Transform the captured variable.
11732 VarDecl *CapturedVar = cast_or_null<VarDecl>(
11733 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
11734 if (!CapturedVar || CapturedVar->isInvalidDecl())
11735 return StmtError();
11737 // Capture the transformed variable.
11738 getSema().tryCaptureVariable(CapturedVar, C->getLocation());
11744 template<typename Derived>
11746 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11747 CXXUnresolvedConstructExpr *E) {
11748 TypeSourceInfo *T =
11749 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11751 return ExprError();
11753 bool ArgumentChanged = false;
11754 SmallVector<Expr*, 8> Args;
11755 Args.reserve(E->arg_size());
11757 EnterExpressionEvaluationContext Context(
11758 getSema(), EnterExpressionEvaluationContext::InitList,
11759 E->isListInitialization());
11760 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11762 return ExprError();
11765 if (!getDerived().AlwaysRebuild() &&
11766 T == E->getTypeSourceInfo() &&
11770 // FIXME: we're faking the locations of the commas
11771 return getDerived().RebuildCXXUnresolvedConstructExpr(
11772 T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11775 template<typename Derived>
11777 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11778 CXXDependentScopeMemberExpr *E) {
11779 // Transform the base of the expression.
11780 ExprResult Base((Expr*) nullptr);
11783 QualType ObjectType;
11784 if (!E->isImplicitAccess()) {
11785 OldBase = E->getBase();
11786 Base = getDerived().TransformExpr(OldBase);
11787 if (Base.isInvalid())
11788 return ExprError();
11790 // Start the member reference and compute the object's type.
11791 ParsedType ObjectTy;
11792 bool MayBePseudoDestructor = false;
11793 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11794 E->getOperatorLoc(),
11795 E->isArrow()? tok::arrow : tok::period,
11797 MayBePseudoDestructor);
11798 if (Base.isInvalid())
11799 return ExprError();
11801 ObjectType = ObjectTy.get();
11802 BaseType = ((Expr*) Base.get())->getType();
11805 BaseType = getDerived().TransformType(E->getBaseType());
11806 ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
11809 // Transform the first part of the nested-name-specifier that qualifies
11810 // the member name.
11811 NamedDecl *FirstQualifierInScope
11812 = getDerived().TransformFirstQualifierInScope(
11813 E->getFirstQualifierFoundInScope(),
11814 E->getQualifierLoc().getBeginLoc());
11816 NestedNameSpecifierLoc QualifierLoc;
11817 if (E->getQualifier()) {
11819 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11821 FirstQualifierInScope);
11823 return ExprError();
11826 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11828 // TODO: If this is a conversion-function-id, verify that the
11829 // destination type name (if present) resolves the same way after
11830 // instantiation as it did in the local scope.
11832 DeclarationNameInfo NameInfo
11833 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11834 if (!NameInfo.getName())
11835 return ExprError();
11837 if (!E->hasExplicitTemplateArgs()) {
11838 // This is a reference to a member without an explicitly-specified
11839 // template argument list. Optimize for this common case.
11840 if (!getDerived().AlwaysRebuild() &&
11841 Base.get() == OldBase &&
11842 BaseType == E->getBaseType() &&
11843 QualifierLoc == E->getQualifierLoc() &&
11844 NameInfo.getName() == E->getMember() &&
11845 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11848 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11851 E->getOperatorLoc(),
11854 FirstQualifierInScope,
11856 /*TemplateArgs*/nullptr);
11859 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11860 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11861 E->getNumTemplateArgs(),
11863 return ExprError();
11865 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11868 E->getOperatorLoc(),
11871 FirstQualifierInScope,
11876 template<typename Derived>
11878 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11879 // Transform the base of the expression.
11880 ExprResult Base((Expr*) nullptr);
11882 if (!Old->isImplicitAccess()) {
11883 Base = getDerived().TransformExpr(Old->getBase());
11884 if (Base.isInvalid())
11885 return ExprError();
11886 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11888 if (Base.isInvalid())
11889 return ExprError();
11890 BaseType = Base.get()->getType();
11892 BaseType = getDerived().TransformType(Old->getBaseType());
11895 NestedNameSpecifierLoc QualifierLoc;
11896 if (Old->getQualifierLoc()) {
11898 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11900 return ExprError();
11903 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11905 LookupResult R(SemaRef, Old->getMemberNameInfo(),
11906 Sema::LookupOrdinaryName);
11908 // Transform the declaration set.
11909 if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11910 return ExprError();
11912 // Determine the naming class.
11913 if (Old->getNamingClass()) {
11914 CXXRecordDecl *NamingClass
11915 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11916 Old->getMemberLoc(),
11917 Old->getNamingClass()));
11919 return ExprError();
11921 R.setNamingClass(NamingClass);
11924 TemplateArgumentListInfo TransArgs;
11925 if (Old->hasExplicitTemplateArgs()) {
11926 TransArgs.setLAngleLoc(Old->getLAngleLoc());
11927 TransArgs.setRAngleLoc(Old->getRAngleLoc());
11928 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11929 Old->getNumTemplateArgs(),
11931 return ExprError();
11934 // FIXME: to do this check properly, we will need to preserve the
11935 // first-qualifier-in-scope here, just in case we had a dependent
11936 // base (and therefore couldn't do the check) and a
11937 // nested-name-qualifier (and therefore could do the lookup).
11938 NamedDecl *FirstQualifierInScope = nullptr;
11940 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11942 Old->getOperatorLoc(),
11946 FirstQualifierInScope,
11948 (Old->hasExplicitTemplateArgs()
11949 ? &TransArgs : nullptr));
11952 template<typename Derived>
11954 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11955 EnterExpressionEvaluationContext Unevaluated(
11956 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11957 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11958 if (SubExpr.isInvalid())
11959 return ExprError();
11961 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11964 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11967 template<typename Derived>
11969 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11970 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11971 if (Pattern.isInvalid())
11972 return ExprError();
11974 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11977 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11978 E->getNumExpansions());
11981 template<typename Derived>
11983 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11984 // If E is not value-dependent, then nothing will change when we transform it.
11985 // Note: This is an instantiation-centric view.
11986 if (!E->isValueDependent())
11989 EnterExpressionEvaluationContext Unevaluated(
11990 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11992 ArrayRef<TemplateArgument> PackArgs;
11993 TemplateArgument ArgStorage;
11995 // Find the argument list to transform.
11996 if (E->isPartiallySubstituted()) {
11997 PackArgs = E->getPartialArguments();
11998 } else if (E->isValueDependent()) {
11999 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
12000 bool ShouldExpand = false;
12001 bool RetainExpansion = false;
12002 Optional<unsigned> NumExpansions;
12003 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
12005 ShouldExpand, RetainExpansion,
12007 return ExprError();
12009 // If we need to expand the pack, build a template argument from it and
12011 if (ShouldExpand) {
12012 auto *Pack = E->getPack();
12013 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
12014 ArgStorage = getSema().Context.getPackExpansionType(
12015 getSema().Context.getTypeDeclType(TTPD), None);
12016 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
12017 ArgStorage = TemplateArgument(TemplateName(TTPD), None);
12019 auto *VD = cast<ValueDecl>(Pack);
12020 ExprResult DRE = getSema().BuildDeclRefExpr(
12021 VD, VD->getType().getNonLValueExprType(getSema().Context),
12022 VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
12024 if (DRE.isInvalid())
12025 return ExprError();
12026 ArgStorage = new (getSema().Context) PackExpansionExpr(
12027 getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
12029 PackArgs = ArgStorage;
12033 // If we're not expanding the pack, just transform the decl.
12034 if (!PackArgs.size()) {
12035 auto *Pack = cast_or_null<NamedDecl>(
12036 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
12038 return ExprError();
12039 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
12041 E->getRParenLoc(), None, None);
12044 // Try to compute the result without performing a partial substitution.
12045 Optional<unsigned> Result = 0;
12046 for (const TemplateArgument &Arg : PackArgs) {
12047 if (!Arg.isPackExpansion()) {
12048 Result = *Result + 1;
12052 TemplateArgumentLoc ArgLoc;
12053 InventTemplateArgumentLoc(Arg, ArgLoc);
12055 // Find the pattern of the pack expansion.
12056 SourceLocation Ellipsis;
12057 Optional<unsigned> OrigNumExpansions;
12058 TemplateArgumentLoc Pattern =
12059 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
12060 OrigNumExpansions);
12062 // Substitute under the pack expansion. Do not expand the pack (yet).
12063 TemplateArgumentLoc OutPattern;
12064 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12065 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
12069 // See if we can determine the number of arguments from the result.
12070 Optional<unsigned> NumExpansions =
12071 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
12072 if (!NumExpansions) {
12073 // No: we must be in an alias template expansion, and we're going to need
12074 // to actually expand the packs.
12079 Result = *Result + *NumExpansions;
12082 // Common case: we could determine the number of expansions without
12085 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12087 E->getRParenLoc(), *Result, None);
12089 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
12092 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
12093 typedef TemplateArgumentLocInventIterator<
12094 Derived, const TemplateArgument*> PackLocIterator;
12095 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
12096 PackLocIterator(*this, PackArgs.end()),
12097 TransformedPackArgs, /*Uneval*/true))
12098 return ExprError();
12101 // Check whether we managed to fully-expand the pack.
12102 // FIXME: Is it possible for us to do so and not hit the early exit path?
12103 SmallVector<TemplateArgument, 8> Args;
12104 bool PartialSubstitution = false;
12105 for (auto &Loc : TransformedPackArgs.arguments()) {
12106 Args.push_back(Loc.getArgument());
12107 if (Loc.getArgument().isPackExpansion())
12108 PartialSubstitution = true;
12111 if (PartialSubstitution)
12112 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12114 E->getRParenLoc(), None, Args);
12116 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12117 E->getPackLoc(), E->getRParenLoc(),
12118 Args.size(), None);
12121 template<typename Derived>
12123 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
12124 SubstNonTypeTemplateParmPackExpr *E) {
12125 // Default behavior is to do nothing with this transformation.
12129 template<typename Derived>
12131 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
12132 SubstNonTypeTemplateParmExpr *E) {
12133 // Default behavior is to do nothing with this transformation.
12137 template<typename Derived>
12139 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12140 // Default behavior is to do nothing with this transformation.
12144 template<typename Derived>
12146 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12147 MaterializeTemporaryExpr *E) {
12148 return getDerived().TransformExpr(E->GetTemporaryExpr());
12151 template<typename Derived>
12153 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12154 Expr *Pattern = E->getPattern();
12156 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12157 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12158 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12160 // Determine whether the set of unexpanded parameter packs can and should
12162 bool Expand = true;
12163 bool RetainExpansion = false;
12164 Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12165 NumExpansions = OrigNumExpansions;
12166 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12167 Pattern->getSourceRange(),
12169 Expand, RetainExpansion,
12174 // Do not expand any packs here, just transform and rebuild a fold
12176 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12179 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12180 if (LHS.isInvalid())
12184 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12185 if (RHS.isInvalid())
12188 if (!getDerived().AlwaysRebuild() &&
12189 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12192 return getDerived().RebuildCXXFoldExpr(
12193 E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12194 RHS.get(), E->getEndLoc(), NumExpansions);
12197 // The transform has determined that we should perform an elementwise
12198 // expansion of the pattern. Do so.
12199 ExprResult Result = getDerived().TransformExpr(E->getInit());
12200 if (Result.isInvalid())
12202 bool LeftFold = E->isLeftFold();
12204 // If we're retaining an expansion for a right fold, it is the innermost
12205 // component and takes the init (if any).
12206 if (!LeftFold && RetainExpansion) {
12207 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12209 ExprResult Out = getDerived().TransformExpr(Pattern);
12210 if (Out.isInvalid())
12213 Result = getDerived().RebuildCXXFoldExpr(
12214 E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12215 Result.get(), E->getEndLoc(), OrigNumExpansions);
12216 if (Result.isInvalid())
12220 for (unsigned I = 0; I != *NumExpansions; ++I) {
12221 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12222 getSema(), LeftFold ? I : *NumExpansions - I - 1);
12223 ExprResult Out = getDerived().TransformExpr(Pattern);
12224 if (Out.isInvalid())
12227 if (Out.get()->containsUnexpandedParameterPack()) {
12228 // We still have a pack; retain a pack expansion for this slice.
12229 Result = getDerived().RebuildCXXFoldExpr(
12230 E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12231 E->getOperator(), E->getEllipsisLoc(),
12232 LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12233 OrigNumExpansions);
12234 } else if (Result.isUsable()) {
12235 // We've got down to a single element; build a binary operator.
12236 Result = getDerived().RebuildBinaryOperator(
12237 E->getEllipsisLoc(), E->getOperator(),
12238 LeftFold ? Result.get() : Out.get(),
12239 LeftFold ? Out.get() : Result.get());
12243 if (Result.isInvalid())
12247 // If we're retaining an expansion for a left fold, it is the outermost
12248 // component and takes the complete expansion so far as its init (if any).
12249 if (LeftFold && RetainExpansion) {
12250 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12252 ExprResult Out = getDerived().TransformExpr(Pattern);
12253 if (Out.isInvalid())
12256 Result = getDerived().RebuildCXXFoldExpr(
12257 E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12258 Out.get(), E->getEndLoc(), OrigNumExpansions);
12259 if (Result.isInvalid())
12263 // If we had no init and an empty pack, and we're not retaining an expansion,
12264 // then produce a fallback value or error.
12265 if (Result.isUnset())
12266 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12272 template<typename Derived>
12274 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12275 CXXStdInitializerListExpr *E) {
12276 return getDerived().TransformExpr(E->getSubExpr());
12279 template<typename Derived>
12281 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12282 return SemaRef.MaybeBindToTemporary(E);
12285 template<typename Derived>
12287 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12291 template<typename Derived>
12293 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12294 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12295 if (SubExpr.isInvalid())
12296 return ExprError();
12298 if (!getDerived().AlwaysRebuild() &&
12299 SubExpr.get() == E->getSubExpr())
12302 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12305 template<typename Derived>
12307 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12308 // Transform each of the elements.
12309 SmallVector<Expr *, 8> Elements;
12310 bool ArgChanged = false;
12311 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12312 /*IsCall=*/false, Elements, &ArgChanged))
12313 return ExprError();
12315 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12316 return SemaRef.MaybeBindToTemporary(E);
12318 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12323 template<typename Derived>
12325 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12326 ObjCDictionaryLiteral *E) {
12327 // Transform each of the elements.
12328 SmallVector<ObjCDictionaryElement, 8> Elements;
12329 bool ArgChanged = false;
12330 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12331 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12333 if (OrigElement.isPackExpansion()) {
12334 // This key/value element is a pack expansion.
12335 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12336 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12337 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12338 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12340 // Determine whether the set of unexpanded parameter packs can
12341 // and should be expanded.
12342 bool Expand = true;
12343 bool RetainExpansion = false;
12344 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12345 Optional<unsigned> NumExpansions = OrigNumExpansions;
12346 SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12347 OrigElement.Value->getEndLoc());
12348 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12349 PatternRange, Unexpanded, Expand,
12350 RetainExpansion, NumExpansions))
12351 return ExprError();
12354 // The transform has determined that we should perform a simple
12355 // transformation on the pack expansion, producing another pack
12357 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12358 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12359 if (Key.isInvalid())
12360 return ExprError();
12362 if (Key.get() != OrigElement.Key)
12365 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12366 if (Value.isInvalid())
12367 return ExprError();
12369 if (Value.get() != OrigElement.Value)
12372 ObjCDictionaryElement Expansion = {
12373 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12375 Elements.push_back(Expansion);
12379 // Record right away that the argument was changed. This needs
12380 // to happen even if the array expands to nothing.
12383 // The transform has determined that we should perform an elementwise
12384 // expansion of the pattern. Do so.
12385 for (unsigned I = 0; I != *NumExpansions; ++I) {
12386 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12387 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12388 if (Key.isInvalid())
12389 return ExprError();
12391 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12392 if (Value.isInvalid())
12393 return ExprError();
12395 ObjCDictionaryElement Element = {
12396 Key.get(), Value.get(), SourceLocation(), NumExpansions
12399 // If any unexpanded parameter packs remain, we still have a
12401 // FIXME: Can this really happen?
12402 if (Key.get()->containsUnexpandedParameterPack() ||
12403 Value.get()->containsUnexpandedParameterPack())
12404 Element.EllipsisLoc = OrigElement.EllipsisLoc;
12406 Elements.push_back(Element);
12409 // FIXME: Retain a pack expansion if RetainExpansion is true.
12411 // We've finished with this pack expansion.
12415 // Transform and check key.
12416 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12417 if (Key.isInvalid())
12418 return ExprError();
12420 if (Key.get() != OrigElement.Key)
12423 // Transform and check value.
12425 = getDerived().TransformExpr(OrigElement.Value);
12426 if (Value.isInvalid())
12427 return ExprError();
12429 if (Value.get() != OrigElement.Value)
12432 ObjCDictionaryElement Element = {
12433 Key.get(), Value.get(), SourceLocation(), None
12435 Elements.push_back(Element);
12438 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12439 return SemaRef.MaybeBindToTemporary(E);
12441 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12445 template<typename Derived>
12447 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12448 TypeSourceInfo *EncodedTypeInfo
12449 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12450 if (!EncodedTypeInfo)
12451 return ExprError();
12453 if (!getDerived().AlwaysRebuild() &&
12454 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12457 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12459 E->getRParenLoc());
12462 template<typename Derived>
12463 ExprResult TreeTransform<Derived>::
12464 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12465 // This is a kind of implicit conversion, and it needs to get dropped
12466 // and recomputed for the same general reasons that ImplicitCastExprs
12467 // do, as well a more specific one: this expression is only valid when
12468 // it appears *immediately* as an argument expression.
12469 return getDerived().TransformExpr(E->getSubExpr());
12472 template<typename Derived>
12473 ExprResult TreeTransform<Derived>::
12474 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12475 TypeSourceInfo *TSInfo
12476 = getDerived().TransformType(E->getTypeInfoAsWritten());
12478 return ExprError();
12480 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12481 if (Result.isInvalid())
12482 return ExprError();
12484 if (!getDerived().AlwaysRebuild() &&
12485 TSInfo == E->getTypeInfoAsWritten() &&
12486 Result.get() == E->getSubExpr())
12489 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12490 E->getBridgeKeywordLoc(), TSInfo,
12494 template <typename Derived>
12495 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12496 ObjCAvailabilityCheckExpr *E) {
12500 template<typename Derived>
12502 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12503 // Transform arguments.
12504 bool ArgChanged = false;
12505 SmallVector<Expr*, 8> Args;
12506 Args.reserve(E->getNumArgs());
12507 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12509 return ExprError();
12511 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12512 // Class message: transform the receiver type.
12513 TypeSourceInfo *ReceiverTypeInfo
12514 = getDerived().TransformType(E->getClassReceiverTypeInfo());
12515 if (!ReceiverTypeInfo)
12516 return ExprError();
12518 // If nothing changed, just retain the existing message send.
12519 if (!getDerived().AlwaysRebuild() &&
12520 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12521 return SemaRef.MaybeBindToTemporary(E);
12523 // Build a new class message send.
12524 SmallVector<SourceLocation, 16> SelLocs;
12525 E->getSelectorLocs(SelLocs);
12526 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12529 E->getMethodDecl(),
12534 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12535 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12536 if (!E->getMethodDecl())
12537 return ExprError();
12539 // Build a new class message send to 'super'.
12540 SmallVector<SourceLocation, 16> SelLocs;
12541 E->getSelectorLocs(SelLocs);
12542 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12545 E->getReceiverType(),
12546 E->getMethodDecl(),
12552 // Instance message: transform the receiver
12553 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12554 "Only class and instance messages may be instantiated");
12555 ExprResult Receiver
12556 = getDerived().TransformExpr(E->getInstanceReceiver());
12557 if (Receiver.isInvalid())
12558 return ExprError();
12560 // If nothing changed, just retain the existing message send.
12561 if (!getDerived().AlwaysRebuild() &&
12562 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12563 return SemaRef.MaybeBindToTemporary(E);
12565 // Build a new instance message send.
12566 SmallVector<SourceLocation, 16> SelLocs;
12567 E->getSelectorLocs(SelLocs);
12568 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12571 E->getMethodDecl(),
12577 template<typename Derived>
12579 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12583 template<typename Derived>
12585 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12589 template<typename Derived>
12591 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12592 // Transform the base expression.
12593 ExprResult Base = getDerived().TransformExpr(E->getBase());
12594 if (Base.isInvalid())
12595 return ExprError();
12597 // We don't need to transform the ivar; it will never change.
12599 // If nothing changed, just retain the existing expression.
12600 if (!getDerived().AlwaysRebuild() &&
12601 Base.get() == E->getBase())
12604 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12606 E->isArrow(), E->isFreeIvar());
12609 template<typename Derived>
12611 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12612 // 'super' and types never change. Property never changes. Just
12613 // retain the existing expression.
12614 if (!E->isObjectReceiver())
12617 // Transform the base expression.
12618 ExprResult Base = getDerived().TransformExpr(E->getBase());
12619 if (Base.isInvalid())
12620 return ExprError();
12622 // We don't need to transform the property; it will never change.
12624 // If nothing changed, just retain the existing expression.
12625 if (!getDerived().AlwaysRebuild() &&
12626 Base.get() == E->getBase())
12629 if (E->isExplicitProperty())
12630 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12631 E->getExplicitProperty(),
12634 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12635 SemaRef.Context.PseudoObjectTy,
12636 E->getImplicitPropertyGetter(),
12637 E->getImplicitPropertySetter(),
12641 template<typename Derived>
12643 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12644 // Transform the base expression.
12645 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12646 if (Base.isInvalid())
12647 return ExprError();
12649 // Transform the key expression.
12650 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12651 if (Key.isInvalid())
12652 return ExprError();
12654 // If nothing changed, just retain the existing expression.
12655 if (!getDerived().AlwaysRebuild() &&
12656 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12659 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12660 Base.get(), Key.get(),
12661 E->getAtIndexMethodDecl(),
12662 E->setAtIndexMethodDecl());
12665 template<typename Derived>
12667 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12668 // Transform the base expression.
12669 ExprResult Base = getDerived().TransformExpr(E->getBase());
12670 if (Base.isInvalid())
12671 return ExprError();
12673 // If nothing changed, just retain the existing expression.
12674 if (!getDerived().AlwaysRebuild() &&
12675 Base.get() == E->getBase())
12678 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12683 template<typename Derived>
12685 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12686 bool ArgumentChanged = false;
12687 SmallVector<Expr*, 8> SubExprs;
12688 SubExprs.reserve(E->getNumSubExprs());
12689 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12690 SubExprs, &ArgumentChanged))
12691 return ExprError();
12693 if (!getDerived().AlwaysRebuild() &&
12697 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12699 E->getRParenLoc());
12702 template<typename Derived>
12704 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12705 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12706 if (SrcExpr.isInvalid())
12707 return ExprError();
12709 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12711 return ExprError();
12713 if (!getDerived().AlwaysRebuild() &&
12714 Type == E->getTypeSourceInfo() &&
12715 SrcExpr.get() == E->getSrcExpr())
12718 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12719 SrcExpr.get(), Type,
12720 E->getRParenLoc());
12723 template<typename Derived>
12725 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12726 BlockDecl *oldBlock = E->getBlockDecl();
12728 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12729 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12731 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12732 blockScope->TheDecl->setBlockMissingReturnType(
12733 oldBlock->blockMissingReturnType());
12735 SmallVector<ParmVarDecl*, 4> params;
12736 SmallVector<QualType, 4> paramTypes;
12738 const FunctionProtoType *exprFunctionType = E->getFunctionType();
12740 // Parameter substitution.
12741 Sema::ExtParameterInfoBuilder extParamInfos;
12742 if (getDerived().TransformFunctionTypeParams(
12743 E->getCaretLocation(), oldBlock->parameters(), nullptr,
12744 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, ¶ms,
12746 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12747 return ExprError();
12750 QualType exprResultType =
12751 getDerived().TransformType(exprFunctionType->getReturnType());
12753 auto epi = exprFunctionType->getExtProtoInfo();
12754 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12756 QualType functionType =
12757 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12758 blockScope->FunctionType = functionType;
12760 // Set the parameters on the block decl.
12761 if (!params.empty())
12762 blockScope->TheDecl->setParams(params);
12764 if (!oldBlock->blockMissingReturnType()) {
12765 blockScope->HasImplicitReturnType = false;
12766 blockScope->ReturnType = exprResultType;
12769 // Transform the body
12770 StmtResult body = getDerived().TransformStmt(E->getBody());
12771 if (body.isInvalid()) {
12772 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12773 return ExprError();
12777 // In builds with assertions, make sure that we captured everything we
12778 // captured before.
12779 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12780 for (const auto &I : oldBlock->captures()) {
12781 VarDecl *oldCapture = I.getVariable();
12783 // Ignore parameter packs.
12784 if (oldCapture->isParameterPack())
12787 VarDecl *newCapture =
12788 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12790 assert(blockScope->CaptureMap.count(newCapture));
12792 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12796 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12797 /*Scope=*/nullptr);
12800 template<typename Derived>
12802 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12803 llvm_unreachable("Cannot transform asType expressions yet");
12806 template<typename Derived>
12808 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12809 bool ArgumentChanged = false;
12810 SmallVector<Expr*, 8> SubExprs;
12811 SubExprs.reserve(E->getNumSubExprs());
12812 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12813 SubExprs, &ArgumentChanged))
12814 return ExprError();
12816 if (!getDerived().AlwaysRebuild() &&
12820 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12821 E->getOp(), E->getRParenLoc());
12824 //===----------------------------------------------------------------------===//
12825 // Type reconstruction
12826 //===----------------------------------------------------------------------===//
12828 template<typename Derived>
12829 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12830 SourceLocation Star) {
12831 return SemaRef.BuildPointerType(PointeeType, Star,
12832 getDerived().getBaseEntity());
12835 template<typename Derived>
12836 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12837 SourceLocation Star) {
12838 return SemaRef.BuildBlockPointerType(PointeeType, Star,
12839 getDerived().getBaseEntity());
12842 template<typename Derived>
12844 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12845 bool WrittenAsLValue,
12846 SourceLocation Sigil) {
12847 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12848 Sigil, getDerived().getBaseEntity());
12851 template<typename Derived>
12853 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12854 QualType ClassType,
12855 SourceLocation Sigil) {
12856 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12857 getDerived().getBaseEntity());
12860 template<typename Derived>
12861 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12862 const ObjCTypeParamDecl *Decl,
12863 SourceLocation ProtocolLAngleLoc,
12864 ArrayRef<ObjCProtocolDecl *> Protocols,
12865 ArrayRef<SourceLocation> ProtocolLocs,
12866 SourceLocation ProtocolRAngleLoc) {
12867 return SemaRef.BuildObjCTypeParamType(Decl,
12868 ProtocolLAngleLoc, Protocols,
12869 ProtocolLocs, ProtocolRAngleLoc,
12870 /*FailOnError=*/true);
12873 template<typename Derived>
12874 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12876 SourceLocation Loc,
12877 SourceLocation TypeArgsLAngleLoc,
12878 ArrayRef<TypeSourceInfo *> TypeArgs,
12879 SourceLocation TypeArgsRAngleLoc,
12880 SourceLocation ProtocolLAngleLoc,
12881 ArrayRef<ObjCProtocolDecl *> Protocols,
12882 ArrayRef<SourceLocation> ProtocolLocs,
12883 SourceLocation ProtocolRAngleLoc) {
12884 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12885 TypeArgs, TypeArgsRAngleLoc,
12886 ProtocolLAngleLoc, Protocols, ProtocolLocs,
12888 /*FailOnError=*/true);
12891 template<typename Derived>
12892 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12893 QualType PointeeType,
12894 SourceLocation Star) {
12895 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12898 template<typename Derived>
12900 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12901 ArrayType::ArraySizeModifier SizeMod,
12902 const llvm::APInt *Size,
12904 unsigned IndexTypeQuals,
12905 SourceRange BracketsRange) {
12906 if (SizeExpr || !Size)
12907 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12908 IndexTypeQuals, BracketsRange,
12909 getDerived().getBaseEntity());
12911 QualType Types[] = {
12912 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12913 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12914 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12916 const unsigned NumTypes = llvm::array_lengthof(Types);
12918 for (unsigned I = 0; I != NumTypes; ++I)
12919 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12920 SizeType = Types[I];
12924 // Note that we can return a VariableArrayType here in the case where
12925 // the element type was a dependent VariableArrayType.
12926 IntegerLiteral *ArraySize
12927 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12928 /*FIXME*/BracketsRange.getBegin());
12929 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12930 IndexTypeQuals, BracketsRange,
12931 getDerived().getBaseEntity());
12934 template<typename Derived>
12936 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12937 ArrayType::ArraySizeModifier SizeMod,
12938 const llvm::APInt &Size,
12940 unsigned IndexTypeQuals,
12941 SourceRange BracketsRange) {
12942 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
12943 IndexTypeQuals, BracketsRange);
12946 template<typename Derived>
12948 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12949 ArrayType::ArraySizeModifier SizeMod,
12950 unsigned IndexTypeQuals,
12951 SourceRange BracketsRange) {
12952 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12953 IndexTypeQuals, BracketsRange);
12956 template<typename Derived>
12958 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12959 ArrayType::ArraySizeModifier SizeMod,
12961 unsigned IndexTypeQuals,
12962 SourceRange BracketsRange) {
12963 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12965 IndexTypeQuals, BracketsRange);
12968 template<typename Derived>
12970 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12971 ArrayType::ArraySizeModifier SizeMod,
12973 unsigned IndexTypeQuals,
12974 SourceRange BracketsRange) {
12975 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12977 IndexTypeQuals, BracketsRange);
12980 template <typename Derived>
12981 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
12982 QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
12983 return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
12987 template <typename Derived>
12989 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12990 unsigned NumElements,
12991 VectorType::VectorKind VecKind) {
12992 // FIXME: semantic checking!
12993 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12996 template <typename Derived>
12997 QualType TreeTransform<Derived>::RebuildDependentVectorType(
12998 QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
12999 VectorType::VectorKind VecKind) {
13000 return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
13003 template<typename Derived>
13004 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
13005 unsigned NumElements,
13006 SourceLocation AttributeLoc) {
13007 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
13008 NumElements, true);
13009 IntegerLiteral *VectorSize
13010 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
13012 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
13015 template<typename Derived>
13017 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
13019 SourceLocation AttributeLoc) {
13020 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
13023 template<typename Derived>
13024 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
13026 MutableArrayRef<QualType> ParamTypes,
13027 const FunctionProtoType::ExtProtoInfo &EPI) {
13028 return SemaRef.BuildFunctionType(T, ParamTypes,
13029 getDerived().getBaseLocation(),
13030 getDerived().getBaseEntity(),
13034 template<typename Derived>
13035 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
13036 return SemaRef.Context.getFunctionNoProtoType(T);
13039 template<typename Derived>
13040 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
13042 assert(D && "no decl found");
13043 if (D->isInvalidDecl()) return QualType();
13045 // FIXME: Doesn't account for ObjCInterfaceDecl!
13047 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
13048 // A valid resolved using typename pack expansion decl can have multiple
13049 // UsingDecls, but they must each have exactly one type, and it must be
13050 // the same type in every case. But we must have at least one expansion!
13051 if (UPD->expansions().empty()) {
13052 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
13053 << UPD->isCXXClassMember() << UPD;
13057 // We might still have some unresolved types. Try to pick a resolved type
13058 // if we can. The final instantiation will check that the remaining
13059 // unresolved types instantiate to the type we pick.
13060 QualType FallbackT;
13062 for (auto *E : UPD->expansions()) {
13063 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
13064 if (ThisT.isNull())
13066 else if (ThisT->getAs<UnresolvedUsingType>())
13068 else if (T.isNull())
13071 assert(getSema().Context.hasSameType(ThisT, T) &&
13072 "mismatched resolved types in using pack expansion");
13074 return T.isNull() ? FallbackT : T;
13075 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
13076 assert(Using->hasTypename() &&
13077 "UnresolvedUsingTypenameDecl transformed to non-typename using");
13079 // A valid resolved using typename decl points to exactly one type decl.
13080 assert(++Using->shadow_begin() == Using->shadow_end());
13081 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
13083 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
13084 "UnresolvedUsingTypenameDecl transformed to non-using decl");
13085 Ty = cast<UnresolvedUsingTypenameDecl>(D);
13088 return SemaRef.Context.getTypeDeclType(Ty);
13091 template<typename Derived>
13092 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
13093 SourceLocation Loc) {
13094 return SemaRef.BuildTypeofExprType(E, Loc);
13097 template<typename Derived>
13098 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
13099 return SemaRef.Context.getTypeOfType(Underlying);
13102 template<typename Derived>
13103 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
13104 SourceLocation Loc) {
13105 return SemaRef.BuildDecltypeType(E, Loc);
13108 template<typename Derived>
13109 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
13110 UnaryTransformType::UTTKind UKind,
13111 SourceLocation Loc) {
13112 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
13115 template<typename Derived>
13116 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
13117 TemplateName Template,
13118 SourceLocation TemplateNameLoc,
13119 TemplateArgumentListInfo &TemplateArgs) {
13120 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
13123 template<typename Derived>
13124 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
13125 SourceLocation KWLoc) {
13126 return SemaRef.BuildAtomicType(ValueType, KWLoc);
13129 template<typename Derived>
13130 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
13131 SourceLocation KWLoc,
13133 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
13134 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
13137 template<typename Derived>
13139 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13141 TemplateDecl *Template) {
13142 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13146 template<typename Derived>
13148 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13149 SourceLocation TemplateKWLoc,
13150 const IdentifierInfo &Name,
13151 SourceLocation NameLoc,
13152 QualType ObjectType,
13153 NamedDecl *FirstQualifierInScope,
13154 bool AllowInjectedClassName) {
13155 UnqualifiedId TemplateName;
13156 TemplateName.setIdentifier(&Name, NameLoc);
13157 Sema::TemplateTy Template;
13158 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13159 SS, TemplateKWLoc, TemplateName,
13160 ParsedType::make(ObjectType),
13161 /*EnteringContext=*/false,
13162 Template, AllowInjectedClassName);
13163 return Template.get();
13166 template<typename Derived>
13168 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13169 SourceLocation TemplateKWLoc,
13170 OverloadedOperatorKind Operator,
13171 SourceLocation NameLoc,
13172 QualType ObjectType,
13173 bool AllowInjectedClassName) {
13174 UnqualifiedId Name;
13175 // FIXME: Bogus location information.
13176 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13177 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13178 Sema::TemplateTy Template;
13179 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13180 SS, TemplateKWLoc, Name,
13181 ParsedType::make(ObjectType),
13182 /*EnteringContext=*/false,
13183 Template, AllowInjectedClassName);
13184 return Template.get();
13187 template<typename Derived>
13189 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13190 SourceLocation OpLoc,
13194 Expr *Callee = OrigCallee->IgnoreParenCasts();
13195 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13197 if (First->getObjectKind() == OK_ObjCProperty) {
13198 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13199 if (BinaryOperator::isAssignmentOp(Opc))
13200 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13202 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13203 if (Result.isInvalid())
13204 return ExprError();
13205 First = Result.get();
13208 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13209 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13210 if (Result.isInvalid())
13211 return ExprError();
13212 Second = Result.get();
13215 // Determine whether this should be a builtin operation.
13216 if (Op == OO_Subscript) {
13217 if (!First->getType()->isOverloadableType() &&
13218 !Second->getType()->isOverloadableType())
13219 return getSema().CreateBuiltinArraySubscriptExpr(
13220 First, Callee->getBeginLoc(), Second, OpLoc);
13221 } else if (Op == OO_Arrow) {
13222 // -> is never a builtin operation.
13223 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13224 } else if (Second == nullptr || isPostIncDec) {
13225 if (!First->getType()->isOverloadableType() ||
13226 (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13227 // The argument is not of overloadable type, or this is an expression
13228 // of the form &Class::member, so try to create a built-in unary
13230 UnaryOperatorKind Opc
13231 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13233 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13236 if (!First->getType()->isOverloadableType() &&
13237 !Second->getType()->isOverloadableType()) {
13238 // Neither of the arguments is an overloadable type, so try to
13239 // create a built-in binary operation.
13240 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13242 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13243 if (Result.isInvalid())
13244 return ExprError();
13250 // Compute the transformed set of functions (and function templates) to be
13251 // used during overload resolution.
13252 UnresolvedSet<16> Functions;
13255 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13256 Functions.append(ULE->decls_begin(), ULE->decls_end());
13257 // If the overload could not be resolved in the template definition
13258 // (because we had a dependent argument), ADL is performed as part of
13259 // template instantiation.
13260 RequiresADL = ULE->requiresADL();
13262 // If we've resolved this to a particular non-member function, just call
13263 // that function. If we resolved it to a member function,
13264 // CreateOverloaded* will find that function for us.
13265 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13266 if (!isa<CXXMethodDecl>(ND))
13267 Functions.addDecl(ND);
13268 RequiresADL = false;
13271 // Add any functions found via argument-dependent lookup.
13272 Expr *Args[2] = { First, Second };
13273 unsigned NumArgs = 1 + (Second != nullptr);
13275 // Create the overloaded operator invocation for unary operators.
13276 if (NumArgs == 1 || isPostIncDec) {
13277 UnaryOperatorKind Opc
13278 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13279 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13283 if (Op == OO_Subscript) {
13284 SourceLocation LBrace;
13285 SourceLocation RBrace;
13287 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13288 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13289 LBrace = SourceLocation::getFromRawEncoding(
13290 NameLoc.CXXOperatorName.BeginOpNameLoc);
13291 RBrace = SourceLocation::getFromRawEncoding(
13292 NameLoc.CXXOperatorName.EndOpNameLoc);
13294 LBrace = Callee->getBeginLoc();
13298 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13302 // Create the overloaded operator invocation for binary operators.
13303 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13304 ExprResult Result = SemaRef.CreateOverloadedBinOp(
13305 OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13306 if (Result.isInvalid())
13307 return ExprError();
13312 template<typename Derived>
13314 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13315 SourceLocation OperatorLoc,
13318 TypeSourceInfo *ScopeType,
13319 SourceLocation CCLoc,
13320 SourceLocation TildeLoc,
13321 PseudoDestructorTypeStorage Destroyed) {
13322 QualType BaseType = Base->getType();
13323 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13324 (!isArrow && !BaseType->getAs<RecordType>()) ||
13325 (isArrow && BaseType->getAs<PointerType>() &&
13326 !BaseType->castAs<PointerType>()->getPointeeType()
13327 ->template getAs<RecordType>())){
13328 // This pseudo-destructor expression is still a pseudo-destructor.
13329 return SemaRef.BuildPseudoDestructorExpr(
13330 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13331 CCLoc, TildeLoc, Destroyed);
13334 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13335 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13336 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13337 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13338 NameInfo.setNamedTypeInfo(DestroyedType);
13340 // The scope type is now known to be a valid nested name specifier
13341 // component. Tack it on to the end of the nested name specifier.
13343 if (!ScopeType->getType()->getAs<TagType>()) {
13344 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13345 diag::err_expected_class_or_namespace)
13346 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13347 return ExprError();
13349 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13353 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13354 return getSema().BuildMemberReferenceExpr(Base, BaseType,
13355 OperatorLoc, isArrow,
13357 /*FIXME: FirstQualifier*/ nullptr,
13359 /*TemplateArgs*/ nullptr,
13363 template<typename Derived>
13365 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13366 SourceLocation Loc = S->getBeginLoc();
13367 CapturedDecl *CD = S->getCapturedDecl();
13368 unsigned NumParams = CD->getNumParams();
13369 unsigned ContextParamPos = CD->getContextParamPosition();
13370 SmallVector<Sema::CapturedParamNameType, 4> Params;
13371 for (unsigned I = 0; I < NumParams; ++I) {
13372 if (I != ContextParamPos) {
13375 CD->getParam(I)->getName(),
13376 getDerived().TransformType(CD->getParam(I)->getType())));
13378 Params.push_back(std::make_pair(StringRef(), QualType()));
13381 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13382 S->getCapturedRegionKind(), Params);
13385 Sema::CompoundScopeRAII CompoundScope(getSema());
13386 Body = getDerived().TransformStmt(S->getCapturedStmt());
13389 if (Body.isInvalid()) {
13390 getSema().ActOnCapturedRegionError();
13391 return StmtError();
13394 return getSema().ActOnCapturedRegionEnd(Body.get());
13397 } // end namespace clang
13399 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H