1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file implements a semantic tree transformation that takes a given
10 // AST and rebuilds it, possibly transforming some nodes in the process.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
17 #include "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/Stmt.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/AST/StmtOpenMP.h"
28 #include "clang/Sema/Designator.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/Ownership.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaDiagnostic.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/Support/ErrorHandling.h"
42 /// \brief A semantic tree transformation that allows one to transform one
43 /// abstract syntax tree into another.
45 /// A new tree transformation is defined by creating a new subclass \c X of
46 /// \c TreeTransform<X> and then overriding certain operations to provide
47 /// behavior specific to that transformation. For example, template
48 /// instantiation is implemented as a tree transformation where the
49 /// transformation of TemplateTypeParmType nodes involves substituting the
50 /// template arguments for their corresponding template parameters; a similar
51 /// transformation is performed for non-type template parameters and
52 /// template template parameters.
54 /// This tree-transformation template uses static polymorphism to allow
55 /// subclasses to customize any of its operations. Thus, a subclass can
56 /// override any of the transformation or rebuild operators by providing an
57 /// operation with the same signature as the default implementation. The
58 /// overridding function should not be virtual.
60 /// Semantic tree transformations are split into two stages, either of which
61 /// can be replaced by a subclass. The "transform" step transforms an AST node
62 /// or the parts of an AST node using the various transformation functions,
63 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
64 /// node of the appropriate kind from the pieces. The default transformation
65 /// routines recursively transform the operands to composite AST nodes (e.g.,
66 /// the pointee type of a PointerType node) and, if any of those operand nodes
67 /// were changed by the transformation, invokes the rebuild operation to create
70 /// Subclasses can customize the transformation at various levels. The
71 /// most coarse-grained transformations involve replacing TransformType(),
72 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
73 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
74 /// new implementations.
76 /// For more fine-grained transformations, subclasses can replace any of the
77 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
78 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
79 /// replacing TransformTemplateTypeParmType() allows template instantiation
80 /// to substitute template arguments for their corresponding template
81 /// parameters. Additionally, subclasses can override the \c RebuildXXX
82 /// functions to control how AST nodes are rebuilt when their operands change.
83 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
84 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
85 /// be able to use more efficient rebuild steps.
87 /// There are a handful of other functions that can be overridden, allowing one
88 /// to avoid traversing nodes that don't need any transformation
89 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
90 /// operands have not changed (\c AlwaysRebuild()), and customize the
91 /// default locations and entity names used for type-checking
92 /// (\c getBaseLocation(), \c getBaseEntity()).
93 template<typename Derived>
95 /// \brief Private RAII object that helps us forget and then re-remember
96 /// the template argument corresponding to a partially-substituted parameter
98 class ForgetPartiallySubstitutedPackRAII {
100 TemplateArgument Old;
103 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
104 Old = Self.ForgetPartiallySubstitutedPack();
107 ~ForgetPartiallySubstitutedPackRAII() {
108 Self.RememberPartiallySubstitutedPack(Old);
115 /// \brief The set of local declarations that have been transformed, for
116 /// cases where we are forced to build new declarations within the transformer
117 /// rather than in the subclass (e.g., lambda closure types).
118 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
121 /// \brief Initializes a new tree transformer.
122 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
124 /// \brief Retrieves a reference to the derived class.
125 Derived &getDerived() { return static_cast<Derived&>(*this); }
127 /// \brief Retrieves a reference to the derived class.
128 const Derived &getDerived() const {
129 return static_cast<const Derived&>(*this);
132 static inline ExprResult Owned(Expr *E) { return E; }
133 static inline StmtResult Owned(Stmt *S) { return S; }
135 /// \brief Retrieves a reference to the semantic analysis object used for
136 /// this tree transform.
137 Sema &getSema() const { return SemaRef; }
139 /// \brief Whether the transformation should always rebuild AST nodes, even
140 /// if none of the children have changed.
142 /// Subclasses may override this function to specify when the transformation
143 /// should rebuild all AST nodes.
145 /// We must always rebuild all AST nodes when performing variadic template
146 /// pack expansion, in order to avoid violating the AST invariant that each
147 /// statement node appears at most once in its containing declaration.
148 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
150 /// \brief Returns the location of the entity being transformed, if that
151 /// information was not available elsewhere in the AST.
153 /// By default, returns no source-location information. Subclasses can
154 /// provide an alternative implementation that provides better location
156 SourceLocation getBaseLocation() { return SourceLocation(); }
158 /// \brief Returns the name of the entity being transformed, if that
159 /// information was not available elsewhere in the AST.
161 /// By default, returns an empty name. Subclasses can provide an alternative
162 /// implementation with a more precise name.
163 DeclarationName getBaseEntity() { return DeclarationName(); }
165 /// \brief Sets the "base" location and entity when that
166 /// information is known based on another transformation.
168 /// By default, the source location and entity are ignored. Subclasses can
169 /// override this function to provide a customized implementation.
170 void setBase(SourceLocation Loc, DeclarationName Entity) { }
172 /// \brief RAII object that temporarily sets the base location and entity
173 /// used for reporting diagnostics in types.
174 class TemporaryBase {
176 SourceLocation OldLocation;
177 DeclarationName OldEntity;
180 TemporaryBase(TreeTransform &Self, SourceLocation Location,
181 DeclarationName Entity) : Self(Self) {
182 OldLocation = Self.getDerived().getBaseLocation();
183 OldEntity = Self.getDerived().getBaseEntity();
185 if (Location.isValid())
186 Self.getDerived().setBase(Location, Entity);
190 Self.getDerived().setBase(OldLocation, OldEntity);
194 /// \brief Determine whether the given type \p T has already been
197 /// Subclasses can provide an alternative implementation of this routine
198 /// to short-circuit evaluation when it is known that a given type will
199 /// not change. For example, template instantiation need not traverse
200 /// non-dependent types.
201 bool AlreadyTransformed(QualType T) {
205 /// \brief Determine whether the given call argument should be dropped, e.g.,
206 /// because it is a default argument.
208 /// Subclasses can provide an alternative implementation of this routine to
209 /// determine which kinds of call arguments get dropped. By default,
210 /// CXXDefaultArgument nodes are dropped (prior to transformation).
211 bool DropCallArgument(Expr *E) {
212 return E->isDefaultArgument();
215 /// \brief Determine whether we should expand a pack expansion with the
216 /// given set of parameter packs into separate arguments by repeatedly
217 /// transforming the pattern.
219 /// By default, the transformer never tries to expand pack expansions.
220 /// Subclasses can override this routine to provide different behavior.
222 /// \param EllipsisLoc The location of the ellipsis that identifies the
225 /// \param PatternRange The source range that covers the entire pattern of
226 /// the pack expansion.
228 /// \param Unexpanded The set of unexpanded parameter packs within the
231 /// \param ShouldExpand Will be set to \c true if the transformer should
232 /// expand the corresponding pack expansions into separate arguments. When
233 /// set, \c NumExpansions must also be set.
235 /// \param RetainExpansion Whether the caller should add an unexpanded
236 /// pack expansion after all of the expanded arguments. This is used
237 /// when extending explicitly-specified template argument packs per
238 /// C++0x [temp.arg.explicit]p9.
240 /// \param NumExpansions The number of separate arguments that will be in
241 /// the expanded form of the corresponding pack expansion. This is both an
242 /// input and an output parameter, which can be set by the caller if the
243 /// number of expansions is known a priori (e.g., due to a prior substitution)
244 /// and will be set by the callee when the number of expansions is known.
245 /// The callee must set this value when \c ShouldExpand is \c true; it may
246 /// set this value in other cases.
248 /// \returns true if an error occurred (e.g., because the parameter packs
249 /// are to be instantiated with arguments of different lengths), false
250 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
252 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
253 SourceRange PatternRange,
254 ArrayRef<UnexpandedParameterPack> Unexpanded,
256 bool &RetainExpansion,
257 Optional<unsigned> &NumExpansions) {
258 ShouldExpand = false;
262 /// \brief "Forget" about the partially-substituted pack template argument,
263 /// when performing an instantiation that must preserve the parameter pack
266 /// This routine is meant to be overridden by the template instantiator.
267 TemplateArgument ForgetPartiallySubstitutedPack() {
268 return TemplateArgument();
271 /// \brief "Remember" the partially-substituted pack template argument
272 /// after performing an instantiation that must preserve the parameter pack
275 /// This routine is meant to be overridden by the template instantiator.
276 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
278 /// \brief Note to the derived class when a function parameter pack is
280 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
282 /// \brief Transforms the given type into another type.
284 /// By default, this routine transforms a type by creating a
285 /// TypeSourceInfo for it and delegating to the appropriate
286 /// function. This is expensive, but we don't mind, because
287 /// this method is deprecated anyway; all users should be
288 /// switched to storing TypeSourceInfos.
290 /// \returns the transformed type.
291 QualType TransformType(QualType T);
293 /// \brief Transforms the given type-with-location into a new
294 /// type-with-location.
296 /// By default, this routine transforms a type by delegating to the
297 /// appropriate TransformXXXType to build a new type. Subclasses
298 /// may override this function (to take over all type
299 /// transformations) or some set of the TransformXXXType functions
300 /// to alter the transformation.
301 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
303 /// \brief Transform the given type-with-location into a new
304 /// type, collecting location information in the given builder
307 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
309 /// \brief Transform the given statement.
311 /// By default, this routine transforms a statement by delegating to the
312 /// appropriate TransformXXXStmt function to transform a specific kind of
313 /// statement or the TransformExpr() function to transform an expression.
314 /// Subclasses may override this function to transform statements using some
317 /// \returns the transformed statement.
318 StmtResult TransformStmt(Stmt *S);
320 /// \brief Transform the given statement.
322 /// By default, this routine transforms a statement by delegating to the
323 /// appropriate TransformOMPXXXClause function to transform a specific kind
324 /// of clause. Subclasses may override this function to transform statements
325 /// using some other mechanism.
327 /// \returns the transformed OpenMP clause.
328 OMPClause *TransformOMPClause(OMPClause *S);
330 /// \brief Transform the given attribute.
332 /// By default, this routine transforms a statement by delegating to the
333 /// appropriate TransformXXXAttr function to transform a specific kind
334 /// of attribute. Subclasses may override this function to transform
335 /// attributed statements using some other mechanism.
337 /// \returns the transformed attribute
338 const Attr *TransformAttr(const Attr *S);
340 /// \brief Transform the specified attribute.
342 /// Subclasses should override the transformation of attributes with a pragma
343 /// spelling to transform expressions stored within the attribute.
345 /// \returns the transformed attribute.
347 #define PRAGMA_SPELLING_ATTR(X) \
348 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
349 #include "clang/Basic/AttrList.inc"
351 /// \brief Transform the given expression.
353 /// By default, this routine transforms an expression by delegating to the
354 /// appropriate TransformXXXExpr function to build a new expression.
355 /// Subclasses may override this function to transform expressions using some
358 /// \returns the transformed expression.
359 ExprResult TransformExpr(Expr *E);
361 /// \brief Transform the given initializer.
363 /// By default, this routine transforms an initializer by stripping off the
364 /// semantic nodes added by initialization, then passing the result to
365 /// TransformExpr or TransformExprs.
367 /// \returns the transformed initializer.
368 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
370 /// \brief Transform the given list of expressions.
372 /// This routine transforms a list of expressions by invoking
373 /// \c TransformExpr() for each subexpression. However, it also provides
374 /// support for variadic templates by expanding any pack expansions (if the
375 /// derived class permits such expansion) along the way. When pack expansions
376 /// are present, the number of outputs may not equal the number of inputs.
378 /// \param Inputs The set of expressions to be transformed.
380 /// \param NumInputs The number of expressions in \c Inputs.
382 /// \param IsCall If \c true, then this transform is being performed on
383 /// function-call arguments, and any arguments that should be dropped, will
386 /// \param Outputs The transformed input expressions will be added to this
389 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
390 /// due to transformation.
392 /// \returns true if an error occurred, false otherwise.
393 bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
394 SmallVectorImpl<Expr *> &Outputs,
395 bool *ArgChanged = nullptr);
397 /// \brief Transform the given declaration, which is referenced from a type
400 /// By default, acts as the identity function on declarations, unless the
401 /// transformer has had to transform the declaration itself. Subclasses
402 /// may override this function to provide alternate behavior.
403 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
404 llvm::DenseMap<Decl *, Decl *>::iterator Known
405 = TransformedLocalDecls.find(D);
406 if (Known != TransformedLocalDecls.end())
407 return Known->second;
412 /// \brief Transform the attributes associated with the given declaration and
413 /// place them on the new declaration.
415 /// By default, this operation does nothing. Subclasses may override this
416 /// behavior to transform attributes.
417 void transformAttrs(Decl *Old, Decl *New) { }
419 /// \brief Note that a local declaration has been transformed by this
422 /// Local declarations are typically transformed via a call to
423 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
424 /// the transformer itself has to transform the declarations. This routine
425 /// can be overridden by a subclass that keeps track of such mappings.
426 void transformedLocalDecl(Decl *Old, Decl *New) {
427 TransformedLocalDecls[Old] = New;
430 /// \brief Transform the definition of the given declaration.
432 /// By default, invokes TransformDecl() to transform the declaration.
433 /// Subclasses may override this function to provide alternate behavior.
434 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
435 return getDerived().TransformDecl(Loc, D);
438 /// \brief Transform the given declaration, which was the first part of a
439 /// nested-name-specifier in a member access expression.
441 /// This specific declaration transformation only applies to the first
442 /// identifier in a nested-name-specifier of a member access expression, e.g.,
443 /// the \c T in \c x->T::member
445 /// By default, invokes TransformDecl() to transform the declaration.
446 /// Subclasses may override this function to provide alternate behavior.
447 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
448 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
451 /// \brief Transform the given nested-name-specifier with source-location
454 /// By default, transforms all of the types and declarations within the
455 /// nested-name-specifier. Subclasses may override this function to provide
456 /// alternate behavior.
457 NestedNameSpecifierLoc
458 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
459 QualType ObjectType = QualType(),
460 NamedDecl *FirstQualifierInScope = nullptr);
462 /// \brief Transform the given declaration name.
464 /// By default, transforms the types of conversion function, constructor,
465 /// and destructor names and then (if needed) rebuilds the declaration name.
466 /// Identifiers and selectors are returned unmodified. Sublcasses may
467 /// override this function to provide alternate behavior.
469 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
471 /// \brief Transform the given template name.
473 /// \param SS The nested-name-specifier that qualifies the template
474 /// name. This nested-name-specifier must already have been transformed.
476 /// \param Name The template name to transform.
478 /// \param NameLoc The source location of the template name.
480 /// \param ObjectType If we're translating a template name within a member
481 /// access expression, this is the type of the object whose member template
482 /// is being referenced.
484 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
485 /// also refers to a name within the current (lexical) scope, this is the
486 /// declaration it refers to.
488 /// By default, transforms the template name by transforming the declarations
489 /// and nested-name-specifiers that occur within the template name.
490 /// Subclasses may override this function to provide alternate behavior.
492 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
493 SourceLocation NameLoc,
494 QualType ObjectType = QualType(),
495 NamedDecl *FirstQualifierInScope = nullptr);
497 /// \brief Transform the given template argument.
499 /// By default, this operation transforms the type, expression, or
500 /// declaration stored within the template argument and constructs a
501 /// new template argument from the transformed result. Subclasses may
502 /// override this function to provide alternate behavior.
504 /// Returns true if there was an error.
505 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
506 TemplateArgumentLoc &Output);
508 /// \brief Transform the given set of template arguments.
510 /// By default, this operation transforms all of the template arguments
511 /// in the input set using \c TransformTemplateArgument(), and appends
512 /// the transformed arguments to the output list.
514 /// Note that this overload of \c TransformTemplateArguments() is merely
515 /// a convenience function. Subclasses that wish to override this behavior
516 /// should override the iterator-based member template version.
518 /// \param Inputs The set of template arguments to be transformed.
520 /// \param NumInputs The number of template arguments in \p Inputs.
522 /// \param Outputs The set of transformed template arguments output by this
525 /// Returns true if an error occurred.
526 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
528 TemplateArgumentListInfo &Outputs) {
529 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
532 /// \brief Transform the given set of template arguments.
534 /// By default, this operation transforms all of the template arguments
535 /// in the input set using \c TransformTemplateArgument(), and appends
536 /// the transformed arguments to the output list.
538 /// \param First An iterator to the first template argument.
540 /// \param Last An iterator one step past the last template argument.
542 /// \param Outputs The set of transformed template arguments output by this
545 /// Returns true if an error occurred.
546 template<typename InputIterator>
547 bool TransformTemplateArguments(InputIterator First,
549 TemplateArgumentListInfo &Outputs);
551 /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
552 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
553 TemplateArgumentLoc &ArgLoc);
555 /// \brief Fakes up a TypeSourceInfo for a type.
556 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
557 return SemaRef.Context.getTrivialTypeSourceInfo(T,
558 getDerived().getBaseLocation());
561 #define ABSTRACT_TYPELOC(CLASS, PARENT)
562 #define TYPELOC(CLASS, PARENT) \
563 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
564 #include "clang/AST/TypeLocNodes.def"
566 template<typename Fn>
567 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
568 FunctionProtoTypeLoc TL,
569 CXXRecordDecl *ThisContext,
570 unsigned ThisTypeQuals,
571 Fn TransformExceptionSpec);
573 bool TransformExceptionSpec(SourceLocation Loc,
574 FunctionProtoType::ExceptionSpecInfo &ESI,
575 SmallVectorImpl<QualType> &Exceptions,
578 StmtResult TransformSEHHandler(Stmt *Handler);
581 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
582 TemplateSpecializationTypeLoc TL,
583 TemplateName Template);
586 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
587 DependentTemplateSpecializationTypeLoc TL,
588 TemplateName Template,
591 QualType TransformDependentTemplateSpecializationType(
592 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
593 NestedNameSpecifierLoc QualifierLoc);
595 /// \brief Transforms the parameters of a function type into the
598 /// The result vectors should be kept in sync; null entries in the
599 /// variables vector are acceptable.
601 /// Return true on error.
602 bool TransformFunctionTypeParams(SourceLocation Loc,
603 ParmVarDecl **Params, unsigned NumParams,
604 const QualType *ParamTypes,
605 SmallVectorImpl<QualType> &PTypes,
606 SmallVectorImpl<ParmVarDecl*> *PVars);
608 /// \brief Transforms a single function-type parameter. Return null
611 /// \param indexAdjustment - A number to add to the parameter's
612 /// scope index; can be negative
613 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
615 Optional<unsigned> NumExpansions,
616 bool ExpectParameterPack);
618 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
620 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
621 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
623 TemplateParameterList *TransformTemplateParameterList(
624 TemplateParameterList *TPL) {
628 ExprResult TransformAddressOfOperand(Expr *E);
630 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
631 bool IsAddressOfOperand,
632 TypeSourceInfo **RecoveryTSI);
634 ExprResult TransformParenDependentScopeDeclRefExpr(
635 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
636 TypeSourceInfo **RecoveryTSI);
638 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
640 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
641 // amount of stack usage with clang.
642 #define STMT(Node, Parent) \
643 LLVM_ATTRIBUTE_NOINLINE \
644 StmtResult Transform##Node(Node *S);
645 #define EXPR(Node, Parent) \
646 LLVM_ATTRIBUTE_NOINLINE \
647 ExprResult Transform##Node(Node *E);
648 #define ABSTRACT_STMT(Stmt)
649 #include "clang/AST/StmtNodes.inc"
651 #define OPENMP_CLAUSE(Name, Class) \
652 LLVM_ATTRIBUTE_NOINLINE \
653 OMPClause *Transform ## Class(Class *S);
654 #include "clang/Basic/OpenMPKinds.def"
656 /// \brief Build a new pointer type given its pointee type.
658 /// By default, performs semantic analysis when building the pointer type.
659 /// Subclasses may override this routine to provide different behavior.
660 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
662 /// \brief Build a new block pointer type given its pointee type.
664 /// By default, performs semantic analysis when building the block pointer
665 /// type. Subclasses may override this routine to provide different behavior.
666 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
668 /// \brief Build a new reference type given the type it references.
670 /// By default, performs semantic analysis when building the
671 /// reference type. Subclasses may override this routine to provide
672 /// different behavior.
674 /// \param LValue whether the type was written with an lvalue sigil
675 /// or an rvalue sigil.
676 QualType RebuildReferenceType(QualType ReferentType,
678 SourceLocation Sigil);
680 /// \brief Build a new member pointer type given the pointee type and the
681 /// class type it refers into.
683 /// By default, performs semantic analysis when building the member pointer
684 /// type. Subclasses may override this routine to provide different behavior.
685 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
686 SourceLocation Sigil);
688 /// \brief Build a new array type given the element type, size
689 /// modifier, size of the array (if known), size expression, and index type
692 /// By default, performs semantic analysis when building the array type.
693 /// Subclasses may override this routine to provide different behavior.
694 /// Also by default, all of the other Rebuild*Array
695 QualType RebuildArrayType(QualType ElementType,
696 ArrayType::ArraySizeModifier SizeMod,
697 const llvm::APInt *Size,
699 unsigned IndexTypeQuals,
700 SourceRange BracketsRange);
702 /// \brief Build a new constant array type given the element type, size
703 /// modifier, (known) size of the array, and index type qualifiers.
705 /// By default, performs semantic analysis when building the array type.
706 /// Subclasses may override this routine to provide different behavior.
707 QualType RebuildConstantArrayType(QualType ElementType,
708 ArrayType::ArraySizeModifier SizeMod,
709 const llvm::APInt &Size,
710 unsigned IndexTypeQuals,
711 SourceRange BracketsRange);
713 /// \brief Build a new incomplete array type given the element type, size
714 /// modifier, and index type qualifiers.
716 /// By default, performs semantic analysis when building the array type.
717 /// Subclasses may override this routine to provide different behavior.
718 QualType RebuildIncompleteArrayType(QualType ElementType,
719 ArrayType::ArraySizeModifier SizeMod,
720 unsigned IndexTypeQuals,
721 SourceRange BracketsRange);
723 /// \brief Build a new variable-length array type given the element type,
724 /// size modifier, size expression, and index type qualifiers.
726 /// By default, performs semantic analysis when building the array type.
727 /// Subclasses may override this routine to provide different behavior.
728 QualType RebuildVariableArrayType(QualType ElementType,
729 ArrayType::ArraySizeModifier SizeMod,
731 unsigned IndexTypeQuals,
732 SourceRange BracketsRange);
734 /// \brief Build a new dependent-sized array type given the element type,
735 /// size modifier, size expression, and index type qualifiers.
737 /// By default, performs semantic analysis when building the array type.
738 /// Subclasses may override this routine to provide different behavior.
739 QualType RebuildDependentSizedArrayType(QualType ElementType,
740 ArrayType::ArraySizeModifier SizeMod,
742 unsigned IndexTypeQuals,
743 SourceRange BracketsRange);
745 /// \brief Build a new vector type given the element type and
746 /// number of elements.
748 /// By default, performs semantic analysis when building the vector type.
749 /// Subclasses may override this routine to provide different behavior.
750 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
751 VectorType::VectorKind VecKind);
753 /// \brief Build a new extended vector type given the element type and
754 /// number of elements.
756 /// By default, performs semantic analysis when building the vector type.
757 /// Subclasses may override this routine to provide different behavior.
758 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
759 SourceLocation AttributeLoc);
761 /// \brief Build a new potentially dependently-sized extended vector type
762 /// given the element type and number of elements.
764 /// By default, performs semantic analysis when building the vector type.
765 /// Subclasses may override this routine to provide different behavior.
766 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
768 SourceLocation AttributeLoc);
770 /// \brief Build a new function type.
772 /// By default, performs semantic analysis when building the function type.
773 /// Subclasses may override this routine to provide different behavior.
774 QualType RebuildFunctionProtoType(QualType T,
775 MutableArrayRef<QualType> ParamTypes,
776 const FunctionProtoType::ExtProtoInfo &EPI);
778 /// \brief Build a new unprototyped function type.
779 QualType RebuildFunctionNoProtoType(QualType ResultType);
781 /// \brief Rebuild an unresolved typename type, given the decl that
782 /// the UnresolvedUsingTypenameDecl was transformed to.
783 QualType RebuildUnresolvedUsingType(Decl *D);
785 /// \brief Build a new typedef type.
786 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
787 return SemaRef.Context.getTypeDeclType(Typedef);
790 /// \brief Build a new class/struct/union type.
791 QualType RebuildRecordType(RecordDecl *Record) {
792 return SemaRef.Context.getTypeDeclType(Record);
795 /// \brief Build a new Enum type.
796 QualType RebuildEnumType(EnumDecl *Enum) {
797 return SemaRef.Context.getTypeDeclType(Enum);
800 /// \brief Build a new typeof(expr) type.
802 /// By default, performs semantic analysis when building the typeof type.
803 /// Subclasses may override this routine to provide different behavior.
804 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
806 /// \brief Build a new typeof(type) type.
808 /// By default, builds a new TypeOfType with the given underlying type.
809 QualType RebuildTypeOfType(QualType Underlying);
811 /// \brief Build a new unary transform type.
812 QualType RebuildUnaryTransformType(QualType BaseType,
813 UnaryTransformType::UTTKind UKind,
816 /// \brief Build a new C++11 decltype type.
818 /// By default, performs semantic analysis when building the decltype type.
819 /// Subclasses may override this routine to provide different behavior.
820 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
822 /// \brief Build a new C++11 auto type.
824 /// By default, builds a new AutoType with the given deduced type.
825 QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
826 // Note, IsDependent is always false here: we implicitly convert an 'auto'
827 // which has been deduced to a dependent type into an undeduced 'auto', so
828 // that we'll retry deduction after the transformation.
829 return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto,
830 /*IsDependent*/ false);
833 /// \brief Build a new template specialization type.
835 /// By default, performs semantic analysis when building the template
836 /// specialization type. Subclasses may override this routine to provide
837 /// different behavior.
838 QualType RebuildTemplateSpecializationType(TemplateName Template,
839 SourceLocation TemplateLoc,
840 TemplateArgumentListInfo &Args);
842 /// \brief Build a new parenthesized type.
844 /// By default, builds a new ParenType type from the inner type.
845 /// Subclasses may override this routine to provide different behavior.
846 QualType RebuildParenType(QualType InnerType) {
847 return SemaRef.Context.getParenType(InnerType);
850 /// \brief Build a new qualified name type.
852 /// By default, builds a new ElaboratedType type from the keyword,
853 /// the nested-name-specifier and the named type.
854 /// Subclasses may override this routine to provide different behavior.
855 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
856 ElaboratedTypeKeyword Keyword,
857 NestedNameSpecifierLoc QualifierLoc,
859 return SemaRef.Context.getElaboratedType(Keyword,
860 QualifierLoc.getNestedNameSpecifier(),
864 /// \brief Build a new typename type that refers to a template-id.
866 /// By default, builds a new DependentNameType type from the
867 /// nested-name-specifier and the given type. Subclasses may override
868 /// this routine to provide different behavior.
869 QualType RebuildDependentTemplateSpecializationType(
870 ElaboratedTypeKeyword Keyword,
871 NestedNameSpecifierLoc QualifierLoc,
872 const IdentifierInfo *Name,
873 SourceLocation NameLoc,
874 TemplateArgumentListInfo &Args) {
875 // Rebuild the template name.
876 // TODO: avoid TemplateName abstraction
878 SS.Adopt(QualifierLoc);
879 TemplateName InstName
880 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
883 if (InstName.isNull())
886 // If it's still dependent, make a dependent specialization.
887 if (InstName.getAsDependentTemplateName())
888 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
889 QualifierLoc.getNestedNameSpecifier(),
893 // Otherwise, make an elaborated type wrapping a non-dependent
896 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
897 if (T.isNull()) return QualType();
899 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
902 return SemaRef.Context.getElaboratedType(Keyword,
903 QualifierLoc.getNestedNameSpecifier(),
907 /// \brief Build a new typename type that refers to an identifier.
909 /// By default, performs semantic analysis when building the typename type
910 /// (or elaborated type). Subclasses may override this routine to provide
911 /// different behavior.
912 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
913 SourceLocation KeywordLoc,
914 NestedNameSpecifierLoc QualifierLoc,
915 const IdentifierInfo *Id,
916 SourceLocation IdLoc) {
918 SS.Adopt(QualifierLoc);
920 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
921 // If the name is still dependent, just build a new dependent name type.
922 if (!SemaRef.computeDeclContext(SS))
923 return SemaRef.Context.getDependentNameType(Keyword,
924 QualifierLoc.getNestedNameSpecifier(),
928 if (Keyword == ETK_None || Keyword == ETK_Typename)
929 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
932 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
934 // We had a dependent elaborated-type-specifier that has been transformed
935 // into a non-dependent elaborated-type-specifier. Find the tag we're
937 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
938 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
942 if (SemaRef.RequireCompleteDeclContext(SS, DC))
945 TagDecl *Tag = nullptr;
946 SemaRef.LookupQualifiedName(Result, DC);
947 switch (Result.getResultKind()) {
948 case LookupResult::NotFound:
949 case LookupResult::NotFoundInCurrentInstantiation:
952 case LookupResult::Found:
953 Tag = Result.getAsSingle<TagDecl>();
956 case LookupResult::FoundOverloaded:
957 case LookupResult::FoundUnresolvedValue:
958 llvm_unreachable("Tag lookup cannot find non-tags");
960 case LookupResult::Ambiguous:
961 // Let the LookupResult structure handle ambiguities.
966 // Check where the name exists but isn't a tag type and use that to emit
967 // better diagnostics.
968 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
969 SemaRef.LookupQualifiedName(Result, DC);
970 switch (Result.getResultKind()) {
971 case LookupResult::Found:
972 case LookupResult::FoundOverloaded:
973 case LookupResult::FoundUnresolvedValue: {
974 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
976 if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
977 else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
978 else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
979 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
980 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
984 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
985 << Kind << Id << DC << QualifierLoc.getSourceRange();
991 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
993 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
994 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
998 // Build the elaborated-type-specifier type.
999 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1000 return SemaRef.Context.getElaboratedType(Keyword,
1001 QualifierLoc.getNestedNameSpecifier(),
1005 /// \brief Build a new pack expansion type.
1007 /// By default, builds a new PackExpansionType type from the given pattern.
1008 /// Subclasses may override this routine to provide different behavior.
1009 QualType RebuildPackExpansionType(QualType Pattern,
1010 SourceRange PatternRange,
1011 SourceLocation EllipsisLoc,
1012 Optional<unsigned> NumExpansions) {
1013 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1017 /// \brief Build a new atomic type given its value type.
1019 /// By default, performs semantic analysis when building the atomic type.
1020 /// Subclasses may override this routine to provide different behavior.
1021 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1023 /// \brief Build a new template name given a nested name specifier, a flag
1024 /// indicating whether the "template" keyword was provided, and the template
1025 /// that the template name refers to.
1027 /// By default, builds the new template name directly. Subclasses may override
1028 /// this routine to provide different behavior.
1029 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1031 TemplateDecl *Template);
1033 /// \brief Build a new template name given a nested name specifier and the
1034 /// name that is referred to as a template.
1036 /// By default, performs semantic analysis to determine whether the name can
1037 /// be resolved to a specific template, then builds the appropriate kind of
1038 /// template name. Subclasses may override this routine to provide different
1040 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1041 const IdentifierInfo &Name,
1042 SourceLocation NameLoc,
1043 QualType ObjectType,
1044 NamedDecl *FirstQualifierInScope);
1046 /// \brief Build a new template name given a nested name specifier and the
1047 /// overloaded operator name that is referred to as a template.
1049 /// By default, performs semantic analysis to determine whether the name can
1050 /// be resolved to a specific template, then builds the appropriate kind of
1051 /// template name. Subclasses may override this routine to provide different
1053 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1054 OverloadedOperatorKind Operator,
1055 SourceLocation NameLoc,
1056 QualType ObjectType);
1058 /// \brief Build a new template name given a template template parameter pack
1061 /// By default, performs semantic analysis to determine whether the name can
1062 /// be resolved to a specific template, then builds the appropriate kind of
1063 /// template name. Subclasses may override this routine to provide different
1065 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1066 const TemplateArgument &ArgPack) {
1067 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1070 /// \brief Build a new compound statement.
1072 /// By default, performs semantic analysis to build the new statement.
1073 /// Subclasses may override this routine to provide different behavior.
1074 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1075 MultiStmtArg Statements,
1076 SourceLocation RBraceLoc,
1078 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1082 /// \brief Build a new case statement.
1084 /// By default, performs semantic analysis to build the new statement.
1085 /// Subclasses may override this routine to provide different behavior.
1086 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1088 SourceLocation EllipsisLoc,
1090 SourceLocation ColonLoc) {
1091 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1095 /// \brief Attach the body to a new case statement.
1097 /// By default, performs semantic analysis to build the new statement.
1098 /// Subclasses may override this routine to provide different behavior.
1099 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1100 getSema().ActOnCaseStmtBody(S, Body);
1104 /// \brief Build a new default statement.
1106 /// By default, performs semantic analysis to build the new statement.
1107 /// Subclasses may override this routine to provide different behavior.
1108 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1109 SourceLocation ColonLoc,
1111 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1112 /*CurScope=*/nullptr);
1115 /// \brief Build a new label statement.
1117 /// By default, performs semantic analysis to build the new statement.
1118 /// Subclasses may override this routine to provide different behavior.
1119 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1120 SourceLocation ColonLoc, Stmt *SubStmt) {
1121 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1124 /// \brief Build a new label statement.
1126 /// By default, performs semantic analysis to build the new statement.
1127 /// Subclasses may override this routine to provide different behavior.
1128 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1129 ArrayRef<const Attr*> Attrs,
1131 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1134 /// \brief Build a new "if" statement.
1136 /// By default, performs semantic analysis to build the new statement.
1137 /// Subclasses may override this routine to provide different behavior.
1138 StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
1139 VarDecl *CondVar, Stmt *Then,
1140 SourceLocation ElseLoc, Stmt *Else) {
1141 return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
1144 /// \brief Start building a new switch statement.
1146 /// By default, performs semantic analysis to build the new statement.
1147 /// Subclasses may override this routine to provide different behavior.
1148 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1149 Expr *Cond, VarDecl *CondVar) {
1150 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
1154 /// \brief Attach the body to the switch statement.
1156 /// By default, performs semantic analysis to build the new statement.
1157 /// Subclasses may override this routine to provide different behavior.
1158 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1159 Stmt *Switch, Stmt *Body) {
1160 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1163 /// \brief Build a new while statement.
1165 /// By default, performs semantic analysis to build the new statement.
1166 /// Subclasses may override this routine to provide different behavior.
1167 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
1168 VarDecl *CondVar, Stmt *Body) {
1169 return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
1172 /// \brief Build a new do-while statement.
1174 /// By default, performs semantic analysis to build the new statement.
1175 /// Subclasses may override this routine to provide different behavior.
1176 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1177 SourceLocation WhileLoc, SourceLocation LParenLoc,
1178 Expr *Cond, SourceLocation RParenLoc) {
1179 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1183 /// \brief Build a new for statement.
1185 /// By default, performs semantic analysis to build the new statement.
1186 /// Subclasses may override this routine to provide different behavior.
1187 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1188 Stmt *Init, Sema::FullExprArg Cond,
1189 VarDecl *CondVar, Sema::FullExprArg Inc,
1190 SourceLocation RParenLoc, Stmt *Body) {
1191 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1192 CondVar, Inc, RParenLoc, Body);
1195 /// \brief Build a new goto statement.
1197 /// By default, performs semantic analysis to build the new statement.
1198 /// Subclasses may override this routine to provide different behavior.
1199 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1201 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1204 /// \brief Build a new indirect goto statement.
1206 /// By default, performs semantic analysis to build the new statement.
1207 /// Subclasses may override this routine to provide different behavior.
1208 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1209 SourceLocation StarLoc,
1211 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1214 /// \brief Build a new return statement.
1216 /// By default, performs semantic analysis to build the new statement.
1217 /// Subclasses may override this routine to provide different behavior.
1218 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1219 return getSema().BuildReturnStmt(ReturnLoc, Result);
1222 /// \brief Build a new declaration statement.
1224 /// By default, performs semantic analysis to build the new statement.
1225 /// Subclasses may override this routine to provide different behavior.
1226 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1227 SourceLocation StartLoc, SourceLocation EndLoc) {
1228 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1229 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1232 /// \brief Build a new inline asm statement.
1234 /// By default, performs semantic analysis to build the new statement.
1235 /// Subclasses may override this routine to provide different behavior.
1236 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1237 bool IsVolatile, unsigned NumOutputs,
1238 unsigned NumInputs, IdentifierInfo **Names,
1239 MultiExprArg Constraints, MultiExprArg Exprs,
1240 Expr *AsmString, MultiExprArg Clobbers,
1241 SourceLocation RParenLoc) {
1242 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1243 NumInputs, Names, Constraints, Exprs,
1244 AsmString, Clobbers, RParenLoc);
1247 /// \brief Build a new MS style inline asm statement.
1249 /// By default, performs semantic analysis to build the new statement.
1250 /// Subclasses may override this routine to provide different behavior.
1251 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1252 ArrayRef<Token> AsmToks,
1253 StringRef AsmString,
1254 unsigned NumOutputs, unsigned NumInputs,
1255 ArrayRef<StringRef> Constraints,
1256 ArrayRef<StringRef> Clobbers,
1257 ArrayRef<Expr*> Exprs,
1258 SourceLocation EndLoc) {
1259 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1260 NumOutputs, NumInputs,
1261 Constraints, Clobbers, Exprs, EndLoc);
1264 /// \brief Build a new Objective-C \@try statement.
1266 /// By default, performs semantic analysis to build the new statement.
1267 /// Subclasses may override this routine to provide different behavior.
1268 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1270 MultiStmtArg CatchStmts,
1272 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1276 /// \brief Rebuild an Objective-C exception declaration.
1278 /// By default, performs semantic analysis to build the new declaration.
1279 /// Subclasses may override this routine to provide different behavior.
1280 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1281 TypeSourceInfo *TInfo, QualType T) {
1282 return getSema().BuildObjCExceptionDecl(TInfo, T,
1283 ExceptionDecl->getInnerLocStart(),
1284 ExceptionDecl->getLocation(),
1285 ExceptionDecl->getIdentifier());
1288 /// \brief Build a new Objective-C \@catch statement.
1290 /// By default, performs semantic analysis to build the new statement.
1291 /// Subclasses may override this routine to provide different behavior.
1292 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1293 SourceLocation RParenLoc,
1296 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1300 /// \brief Build a new Objective-C \@finally statement.
1302 /// By default, performs semantic analysis to build the new statement.
1303 /// Subclasses may override this routine to provide different behavior.
1304 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1306 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1309 /// \brief Build a new Objective-C \@throw statement.
1311 /// By default, performs semantic analysis to build the new statement.
1312 /// Subclasses may override this routine to provide different behavior.
1313 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1315 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1318 /// \brief Build a new OpenMP executable directive.
1320 /// By default, performs semantic analysis to build the new statement.
1321 /// Subclasses may override this routine to provide different behavior.
1322 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1323 DeclarationNameInfo DirName,
1324 OpenMPDirectiveKind CancelRegion,
1325 ArrayRef<OMPClause *> Clauses,
1326 Stmt *AStmt, SourceLocation StartLoc,
1327 SourceLocation EndLoc) {
1328 return getSema().ActOnOpenMPExecutableDirective(
1329 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1332 /// \brief Build a new OpenMP 'if' clause.
1334 /// By default, performs semantic analysis to build the new OpenMP clause.
1335 /// Subclasses may override this routine to provide different behavior.
1336 OMPClause *RebuildOMPIfClause(Expr *Condition,
1337 SourceLocation StartLoc,
1338 SourceLocation LParenLoc,
1339 SourceLocation EndLoc) {
1340 return getSema().ActOnOpenMPIfClause(Condition, StartLoc,
1344 /// \brief Build a new OpenMP 'final' clause.
1346 /// By default, performs semantic analysis to build the new OpenMP clause.
1347 /// Subclasses may override this routine to provide different behavior.
1348 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1349 SourceLocation LParenLoc,
1350 SourceLocation EndLoc) {
1351 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1355 /// \brief Build a new OpenMP 'num_threads' clause.
1357 /// By default, performs semantic analysis to build the new OpenMP clause.
1358 /// Subclasses may override this routine to provide different behavior.
1359 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1360 SourceLocation StartLoc,
1361 SourceLocation LParenLoc,
1362 SourceLocation EndLoc) {
1363 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1367 /// \brief Build a new OpenMP 'safelen' clause.
1369 /// By default, performs semantic analysis to build the new OpenMP clause.
1370 /// Subclasses may override this routine to provide different behavior.
1371 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1372 SourceLocation LParenLoc,
1373 SourceLocation EndLoc) {
1374 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1377 /// \brief Build a new OpenMP 'collapse' clause.
1379 /// By default, performs semantic analysis to build the new OpenMP clause.
1380 /// Subclasses may override this routine to provide different behavior.
1381 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1382 SourceLocation LParenLoc,
1383 SourceLocation EndLoc) {
1384 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1388 /// \brief Build a new OpenMP 'default' clause.
1390 /// By default, performs semantic analysis to build the new OpenMP clause.
1391 /// Subclasses may override this routine to provide different behavior.
1392 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1393 SourceLocation KindKwLoc,
1394 SourceLocation StartLoc,
1395 SourceLocation LParenLoc,
1396 SourceLocation EndLoc) {
1397 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1398 StartLoc, LParenLoc, EndLoc);
1401 /// \brief Build a new OpenMP 'proc_bind' clause.
1403 /// By default, performs semantic analysis to build the new OpenMP clause.
1404 /// Subclasses may override this routine to provide different behavior.
1405 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1406 SourceLocation KindKwLoc,
1407 SourceLocation StartLoc,
1408 SourceLocation LParenLoc,
1409 SourceLocation EndLoc) {
1410 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1411 StartLoc, LParenLoc, EndLoc);
1414 /// \brief Build a new OpenMP 'schedule' clause.
1416 /// By default, performs semantic analysis to build the new OpenMP clause.
1417 /// Subclasses may override this routine to provide different behavior.
1418 OMPClause *RebuildOMPScheduleClause(OpenMPScheduleClauseKind Kind,
1420 SourceLocation StartLoc,
1421 SourceLocation LParenLoc,
1422 SourceLocation KindLoc,
1423 SourceLocation CommaLoc,
1424 SourceLocation EndLoc) {
1425 return getSema().ActOnOpenMPScheduleClause(
1426 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1429 /// \brief Build a new OpenMP 'private' clause.
1431 /// By default, performs semantic analysis to build the new OpenMP clause.
1432 /// Subclasses may override this routine to provide different behavior.
1433 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1434 SourceLocation StartLoc,
1435 SourceLocation LParenLoc,
1436 SourceLocation EndLoc) {
1437 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1441 /// \brief Build a new OpenMP 'firstprivate' clause.
1443 /// By default, performs semantic analysis to build the new OpenMP clause.
1444 /// Subclasses may override this routine to provide different behavior.
1445 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1446 SourceLocation StartLoc,
1447 SourceLocation LParenLoc,
1448 SourceLocation EndLoc) {
1449 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1453 /// \brief Build a new OpenMP 'lastprivate' clause.
1455 /// By default, performs semantic analysis to build the new OpenMP clause.
1456 /// Subclasses may override this routine to provide different behavior.
1457 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1458 SourceLocation StartLoc,
1459 SourceLocation LParenLoc,
1460 SourceLocation EndLoc) {
1461 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1465 /// \brief Build a new OpenMP 'shared' clause.
1467 /// By default, performs semantic analysis to build the new OpenMP clause.
1468 /// Subclasses may override this routine to provide different behavior.
1469 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1470 SourceLocation StartLoc,
1471 SourceLocation LParenLoc,
1472 SourceLocation EndLoc) {
1473 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1477 /// \brief Build a new OpenMP 'reduction' clause.
1479 /// By default, performs semantic analysis to build the new statement.
1480 /// Subclasses may override this routine to provide different behavior.
1481 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1482 SourceLocation StartLoc,
1483 SourceLocation LParenLoc,
1484 SourceLocation ColonLoc,
1485 SourceLocation EndLoc,
1486 CXXScopeSpec &ReductionIdScopeSpec,
1487 const DeclarationNameInfo &ReductionId) {
1488 return getSema().ActOnOpenMPReductionClause(
1489 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1493 /// \brief Build a new OpenMP 'linear' clause.
1495 /// By default, performs semantic analysis to build the new OpenMP clause.
1496 /// Subclasses may override this routine to provide different behavior.
1497 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1498 SourceLocation StartLoc,
1499 SourceLocation LParenLoc,
1500 SourceLocation ColonLoc,
1501 SourceLocation EndLoc) {
1502 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1506 /// \brief Build a new OpenMP 'aligned' clause.
1508 /// By default, performs semantic analysis to build the new OpenMP clause.
1509 /// Subclasses may override this routine to provide different behavior.
1510 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1511 SourceLocation StartLoc,
1512 SourceLocation LParenLoc,
1513 SourceLocation ColonLoc,
1514 SourceLocation EndLoc) {
1515 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1516 LParenLoc, ColonLoc, EndLoc);
1519 /// \brief Build a new OpenMP 'copyin' clause.
1521 /// By default, performs semantic analysis to build the new OpenMP clause.
1522 /// Subclasses may override this routine to provide different behavior.
1523 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1524 SourceLocation StartLoc,
1525 SourceLocation LParenLoc,
1526 SourceLocation EndLoc) {
1527 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1531 /// \brief Build a new OpenMP 'copyprivate' clause.
1533 /// By default, performs semantic analysis to build the new OpenMP clause.
1534 /// Subclasses may override this routine to provide different behavior.
1535 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1536 SourceLocation StartLoc,
1537 SourceLocation LParenLoc,
1538 SourceLocation EndLoc) {
1539 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1543 /// \brief Build a new OpenMP 'flush' pseudo clause.
1545 /// By default, performs semantic analysis to build the new OpenMP clause.
1546 /// Subclasses may override this routine to provide different behavior.
1547 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1548 SourceLocation StartLoc,
1549 SourceLocation LParenLoc,
1550 SourceLocation EndLoc) {
1551 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1555 /// \brief Build a new OpenMP 'depend' pseudo clause.
1557 /// By default, performs semantic analysis to build the new OpenMP clause.
1558 /// Subclasses may override this routine to provide different behavior.
1560 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1561 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1562 SourceLocation StartLoc, SourceLocation LParenLoc,
1563 SourceLocation EndLoc) {
1564 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1565 StartLoc, LParenLoc, EndLoc);
1568 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1570 /// By default, performs semantic analysis to build the new statement.
1571 /// Subclasses may override this routine to provide different behavior.
1572 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1574 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1577 /// \brief Build a new Objective-C \@synchronized statement.
1579 /// By default, performs semantic analysis to build the new statement.
1580 /// Subclasses may override this routine to provide different behavior.
1581 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1582 Expr *Object, Stmt *Body) {
1583 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1586 /// \brief Build a new Objective-C \@autoreleasepool statement.
1588 /// By default, performs semantic analysis to build the new statement.
1589 /// Subclasses may override this routine to provide different behavior.
1590 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1592 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1595 /// \brief Build a new Objective-C fast enumeration statement.
1597 /// By default, performs semantic analysis to build the new statement.
1598 /// Subclasses may override this routine to provide different behavior.
1599 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1602 SourceLocation RParenLoc,
1604 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1608 if (ForEachStmt.isInvalid())
1611 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1614 /// \brief Build a new C++ exception declaration.
1616 /// By default, performs semantic analysis to build the new decaration.
1617 /// Subclasses may override this routine to provide different behavior.
1618 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1619 TypeSourceInfo *Declarator,
1620 SourceLocation StartLoc,
1621 SourceLocation IdLoc,
1622 IdentifierInfo *Id) {
1623 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1624 StartLoc, IdLoc, Id);
1626 getSema().CurContext->addDecl(Var);
1630 /// \brief Build a new C++ catch statement.
1632 /// By default, performs semantic analysis to build the new statement.
1633 /// Subclasses may override this routine to provide different behavior.
1634 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1635 VarDecl *ExceptionDecl,
1637 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1641 /// \brief Build a new C++ try statement.
1643 /// By default, performs semantic analysis to build the new statement.
1644 /// Subclasses may override this routine to provide different behavior.
1645 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
1646 ArrayRef<Stmt *> Handlers) {
1647 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
1650 /// \brief Build a new C++0x range-based for statement.
1652 /// By default, performs semantic analysis to build the new statement.
1653 /// Subclasses may override this routine to provide different behavior.
1654 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
1655 SourceLocation ColonLoc,
1656 Stmt *Range, Stmt *BeginEnd,
1657 Expr *Cond, Expr *Inc,
1659 SourceLocation RParenLoc) {
1660 // If we've just learned that the range is actually an Objective-C
1661 // collection, treat this as an Objective-C fast enumeration loop.
1662 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
1663 if (RangeStmt->isSingleDecl()) {
1664 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
1665 if (RangeVar->isInvalidDecl())
1668 Expr *RangeExpr = RangeVar->getInit();
1669 if (!RangeExpr->isTypeDependent() &&
1670 RangeExpr->getType()->isObjCObjectPointerType())
1671 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
1677 return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
1678 Cond, Inc, LoopVar, RParenLoc,
1679 Sema::BFRK_Rebuild);
1682 /// \brief Build a new C++0x range-based for statement.
1684 /// By default, performs semantic analysis to build the new statement.
1685 /// Subclasses may override this routine to provide different behavior.
1686 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
1688 NestedNameSpecifierLoc QualifierLoc,
1689 DeclarationNameInfo NameInfo,
1691 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
1692 QualifierLoc, NameInfo, Nested);
1695 /// \brief Attach body to a C++0x range-based for statement.
1697 /// By default, performs semantic analysis to finish the new statement.
1698 /// Subclasses may override this routine to provide different behavior.
1699 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
1700 return getSema().FinishCXXForRangeStmt(ForRange, Body);
1703 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
1704 Stmt *TryBlock, Stmt *Handler) {
1705 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
1708 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
1710 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
1713 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
1714 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
1717 /// \brief Build a new predefined expression.
1719 /// By default, performs semantic analysis to build the new expression.
1720 /// Subclasses may override this routine to provide different behavior.
1721 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
1722 PredefinedExpr::IdentType IT) {
1723 return getSema().BuildPredefinedExpr(Loc, IT);
1726 /// \brief Build a new expression that references a declaration.
1728 /// By default, performs semantic analysis to build the new expression.
1729 /// Subclasses may override this routine to provide different behavior.
1730 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
1733 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
1737 /// \brief Build a new expression that references a declaration.
1739 /// By default, performs semantic analysis to build the new expression.
1740 /// Subclasses may override this routine to provide different behavior.
1741 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
1743 const DeclarationNameInfo &NameInfo,
1744 TemplateArgumentListInfo *TemplateArgs) {
1746 SS.Adopt(QualifierLoc);
1748 // FIXME: loses template args.
1750 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
1753 /// \brief Build a new expression in parentheses.
1755 /// By default, performs semantic analysis to build the new expression.
1756 /// Subclasses may override this routine to provide different behavior.
1757 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
1758 SourceLocation RParen) {
1759 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
1762 /// \brief Build a new pseudo-destructor expression.
1764 /// By default, performs semantic analysis to build the new expression.
1765 /// Subclasses may override this routine to provide different behavior.
1766 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
1767 SourceLocation OperatorLoc,
1770 TypeSourceInfo *ScopeType,
1771 SourceLocation CCLoc,
1772 SourceLocation TildeLoc,
1773 PseudoDestructorTypeStorage Destroyed);
1775 /// \brief Build a new unary operator expression.
1777 /// By default, performs semantic analysis to build the new expression.
1778 /// Subclasses may override this routine to provide different behavior.
1779 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
1780 UnaryOperatorKind Opc,
1782 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
1785 /// \brief Build a new builtin offsetof expression.
1787 /// By default, performs semantic analysis to build the new expression.
1788 /// Subclasses may override this routine to provide different behavior.
1789 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
1790 TypeSourceInfo *Type,
1791 Sema::OffsetOfComponent *Components,
1792 unsigned NumComponents,
1793 SourceLocation RParenLoc) {
1794 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
1795 NumComponents, RParenLoc);
1798 /// \brief Build a new sizeof, alignof or vec_step expression with a
1801 /// By default, performs semantic analysis to build the new expression.
1802 /// Subclasses may override this routine to provide different behavior.
1803 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
1804 SourceLocation OpLoc,
1805 UnaryExprOrTypeTrait ExprKind,
1807 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
1810 /// \brief Build a new sizeof, alignof or vec step expression with an
1811 /// expression argument.
1813 /// By default, performs semantic analysis to build the new expression.
1814 /// Subclasses may override this routine to provide different behavior.
1815 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
1816 UnaryExprOrTypeTrait ExprKind,
1819 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
1820 if (Result.isInvalid())
1826 /// \brief Build a new array subscript expression.
1828 /// By default, performs semantic analysis to build the new expression.
1829 /// Subclasses may override this routine to provide different behavior.
1830 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
1831 SourceLocation LBracketLoc,
1833 SourceLocation RBracketLoc) {
1834 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
1839 /// \brief Build a new call expression.
1841 /// By default, performs semantic analysis to build the new expression.
1842 /// Subclasses may override this routine to provide different behavior.
1843 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
1845 SourceLocation RParenLoc,
1846 Expr *ExecConfig = nullptr) {
1847 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
1848 Args, RParenLoc, ExecConfig);
1851 /// \brief Build a new member access expression.
1853 /// By default, performs semantic analysis to build the new expression.
1854 /// Subclasses may override this routine to provide different behavior.
1855 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
1857 NestedNameSpecifierLoc QualifierLoc,
1858 SourceLocation TemplateKWLoc,
1859 const DeclarationNameInfo &MemberNameInfo,
1861 NamedDecl *FoundDecl,
1862 const TemplateArgumentListInfo *ExplicitTemplateArgs,
1863 NamedDecl *FirstQualifierInScope) {
1864 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
1866 if (!Member->getDeclName()) {
1867 // We have a reference to an unnamed field. This is always the
1868 // base of an anonymous struct/union member access, i.e. the
1869 // field is always of record type.
1870 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
1871 assert(Member->getType()->isRecordType() &&
1872 "unnamed member not of record type?");
1875 getSema().PerformObjectMemberConversion(BaseResult.get(),
1876 QualifierLoc.getNestedNameSpecifier(),
1878 if (BaseResult.isInvalid())
1880 Base = BaseResult.get();
1881 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
1882 MemberExpr *ME = new (getSema().Context)
1883 MemberExpr(Base, isArrow, OpLoc, Member, MemberNameInfo,
1884 cast<FieldDecl>(Member)->getType(), VK, OK_Ordinary);
1889 SS.Adopt(QualifierLoc);
1891 Base = BaseResult.get();
1892 QualType BaseType = Base->getType();
1894 // FIXME: this involves duplicating earlier analysis in a lot of
1895 // cases; we should avoid this when possible.
1896 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
1897 R.addDecl(FoundDecl);
1900 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
1902 FirstQualifierInScope,
1903 R, ExplicitTemplateArgs);
1906 /// \brief Build a new binary operator expression.
1908 /// By default, performs semantic analysis to build the new expression.
1909 /// Subclasses may override this routine to provide different behavior.
1910 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
1911 BinaryOperatorKind Opc,
1912 Expr *LHS, Expr *RHS) {
1913 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
1916 /// \brief Build a new conditional operator expression.
1918 /// By default, performs semantic analysis to build the new expression.
1919 /// Subclasses may override this routine to provide different behavior.
1920 ExprResult RebuildConditionalOperator(Expr *Cond,
1921 SourceLocation QuestionLoc,
1923 SourceLocation ColonLoc,
1925 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
1929 /// \brief Build a new C-style cast expression.
1931 /// By default, performs semantic analysis to build the new expression.
1932 /// Subclasses may override this routine to provide different behavior.
1933 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
1934 TypeSourceInfo *TInfo,
1935 SourceLocation RParenLoc,
1937 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
1941 /// \brief Build a new compound literal expression.
1943 /// By default, performs semantic analysis to build the new expression.
1944 /// Subclasses may override this routine to provide different behavior.
1945 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
1946 TypeSourceInfo *TInfo,
1947 SourceLocation RParenLoc,
1949 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
1953 /// \brief Build a new extended vector element access expression.
1955 /// By default, performs semantic analysis to build the new expression.
1956 /// Subclasses may override this routine to provide different behavior.
1957 ExprResult RebuildExtVectorElementExpr(Expr *Base,
1958 SourceLocation OpLoc,
1959 SourceLocation AccessorLoc,
1960 IdentifierInfo &Accessor) {
1963 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
1964 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
1965 OpLoc, /*IsArrow*/ false,
1966 SS, SourceLocation(),
1967 /*FirstQualifierInScope*/ nullptr,
1969 /* TemplateArgs */ nullptr);
1972 /// \brief Build a new initializer list expression.
1974 /// By default, performs semantic analysis to build the new expression.
1975 /// Subclasses may override this routine to provide different behavior.
1976 ExprResult RebuildInitList(SourceLocation LBraceLoc,
1978 SourceLocation RBraceLoc,
1979 QualType ResultTy) {
1981 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
1982 if (Result.isInvalid() || ResultTy->isDependentType())
1985 // Patch in the result type we were given, which may have been computed
1986 // when the initial InitListExpr was built.
1987 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
1988 ILE->setType(ResultTy);
1992 /// \brief Build a new designated initializer expression.
1994 /// By default, performs semantic analysis to build the new expression.
1995 /// Subclasses may override this routine to provide different behavior.
1996 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
1997 MultiExprArg ArrayExprs,
1998 SourceLocation EqualOrColonLoc,
2002 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2004 if (Result.isInvalid())
2010 /// \brief Build a new value-initialized expression.
2012 /// By default, builds the implicit value initialization without performing
2013 /// any semantic analysis. Subclasses may override this routine to provide
2014 /// different behavior.
2015 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2016 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2019 /// \brief Build a new \c va_arg expression.
2021 /// By default, performs semantic analysis to build the new expression.
2022 /// Subclasses may override this routine to provide different behavior.
2023 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2024 Expr *SubExpr, TypeSourceInfo *TInfo,
2025 SourceLocation RParenLoc) {
2026 return getSema().BuildVAArgExpr(BuiltinLoc,
2031 /// \brief Build a new expression list in parentheses.
2033 /// By default, performs semantic analysis to build the new expression.
2034 /// Subclasses may override this routine to provide different behavior.
2035 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2036 MultiExprArg SubExprs,
2037 SourceLocation RParenLoc) {
2038 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2041 /// \brief Build a new address-of-label expression.
2043 /// By default, performs semantic analysis, using the name of the label
2044 /// rather than attempting to map the label statement itself.
2045 /// Subclasses may override this routine to provide different behavior.
2046 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2047 SourceLocation LabelLoc, LabelDecl *Label) {
2048 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2051 /// \brief Build a new GNU statement expression.
2053 /// By default, performs semantic analysis to build the new expression.
2054 /// Subclasses may override this routine to provide different behavior.
2055 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2057 SourceLocation RParenLoc) {
2058 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2061 /// \brief Build a new __builtin_choose_expr expression.
2063 /// By default, performs semantic analysis to build the new expression.
2064 /// Subclasses may override this routine to provide different behavior.
2065 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2066 Expr *Cond, Expr *LHS, Expr *RHS,
2067 SourceLocation RParenLoc) {
2068 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2073 /// \brief Build a new generic selection expression.
2075 /// By default, performs semantic analysis to build the new expression.
2076 /// Subclasses may override this routine to provide different behavior.
2077 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2078 SourceLocation DefaultLoc,
2079 SourceLocation RParenLoc,
2080 Expr *ControllingExpr,
2081 ArrayRef<TypeSourceInfo *> Types,
2082 ArrayRef<Expr *> Exprs) {
2083 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2084 ControllingExpr, Types, Exprs);
2087 /// \brief Build a new overloaded operator call expression.
2089 /// By default, performs semantic analysis to build the new expression.
2090 /// The semantic analysis provides the behavior of template instantiation,
2091 /// copying with transformations that turn what looks like an overloaded
2092 /// operator call into a use of a builtin operator, performing
2093 /// argument-dependent lookup, etc. Subclasses may override this routine to
2094 /// provide different behavior.
2095 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2096 SourceLocation OpLoc,
2101 /// \brief Build a new C++ "named" cast expression, such as static_cast or
2102 /// reinterpret_cast.
2104 /// By default, this routine dispatches to one of the more-specific routines
2105 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2106 /// Subclasses may override this routine to provide different behavior.
2107 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2108 Stmt::StmtClass Class,
2109 SourceLocation LAngleLoc,
2110 TypeSourceInfo *TInfo,
2111 SourceLocation RAngleLoc,
2112 SourceLocation LParenLoc,
2114 SourceLocation RParenLoc) {
2116 case Stmt::CXXStaticCastExprClass:
2117 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2118 RAngleLoc, LParenLoc,
2119 SubExpr, RParenLoc);
2121 case Stmt::CXXDynamicCastExprClass:
2122 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2123 RAngleLoc, LParenLoc,
2124 SubExpr, RParenLoc);
2126 case Stmt::CXXReinterpretCastExprClass:
2127 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2128 RAngleLoc, LParenLoc,
2132 case Stmt::CXXConstCastExprClass:
2133 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2134 RAngleLoc, LParenLoc,
2135 SubExpr, RParenLoc);
2138 llvm_unreachable("Invalid C++ named cast");
2142 /// \brief Build a new C++ static_cast expression.
2144 /// By default, performs semantic analysis to build the new expression.
2145 /// Subclasses may override this routine to provide different behavior.
2146 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2147 SourceLocation LAngleLoc,
2148 TypeSourceInfo *TInfo,
2149 SourceLocation RAngleLoc,
2150 SourceLocation LParenLoc,
2152 SourceLocation RParenLoc) {
2153 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2155 SourceRange(LAngleLoc, RAngleLoc),
2156 SourceRange(LParenLoc, RParenLoc));
2159 /// \brief Build a new C++ dynamic_cast expression.
2161 /// By default, performs semantic analysis to build the new expression.
2162 /// Subclasses may override this routine to provide different behavior.
2163 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2164 SourceLocation LAngleLoc,
2165 TypeSourceInfo *TInfo,
2166 SourceLocation RAngleLoc,
2167 SourceLocation LParenLoc,
2169 SourceLocation RParenLoc) {
2170 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2172 SourceRange(LAngleLoc, RAngleLoc),
2173 SourceRange(LParenLoc, RParenLoc));
2176 /// \brief Build a new C++ reinterpret_cast expression.
2178 /// By default, performs semantic analysis to build the new expression.
2179 /// Subclasses may override this routine to provide different behavior.
2180 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2181 SourceLocation LAngleLoc,
2182 TypeSourceInfo *TInfo,
2183 SourceLocation RAngleLoc,
2184 SourceLocation LParenLoc,
2186 SourceLocation RParenLoc) {
2187 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2189 SourceRange(LAngleLoc, RAngleLoc),
2190 SourceRange(LParenLoc, RParenLoc));
2193 /// \brief Build a new C++ const_cast expression.
2195 /// By default, performs semantic analysis to build the new expression.
2196 /// Subclasses may override this routine to provide different behavior.
2197 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2198 SourceLocation LAngleLoc,
2199 TypeSourceInfo *TInfo,
2200 SourceLocation RAngleLoc,
2201 SourceLocation LParenLoc,
2203 SourceLocation RParenLoc) {
2204 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2206 SourceRange(LAngleLoc, RAngleLoc),
2207 SourceRange(LParenLoc, RParenLoc));
2210 /// \brief Build a new C++ functional-style cast expression.
2212 /// By default, performs semantic analysis to build the new expression.
2213 /// Subclasses may override this routine to provide different behavior.
2214 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2215 SourceLocation LParenLoc,
2217 SourceLocation RParenLoc) {
2218 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2219 MultiExprArg(&Sub, 1),
2223 /// \brief Build a new C++ typeid(type) expression.
2225 /// By default, performs semantic analysis to build the new expression.
2226 /// Subclasses may override this routine to provide different behavior.
2227 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2228 SourceLocation TypeidLoc,
2229 TypeSourceInfo *Operand,
2230 SourceLocation RParenLoc) {
2231 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2236 /// \brief Build a new C++ typeid(expr) expression.
2238 /// By default, performs semantic analysis to build the new expression.
2239 /// Subclasses may override this routine to provide different behavior.
2240 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2241 SourceLocation TypeidLoc,
2243 SourceLocation RParenLoc) {
2244 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2248 /// \brief Build a new C++ __uuidof(type) expression.
2250 /// By default, performs semantic analysis to build the new expression.
2251 /// Subclasses may override this routine to provide different behavior.
2252 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2253 SourceLocation TypeidLoc,
2254 TypeSourceInfo *Operand,
2255 SourceLocation RParenLoc) {
2256 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2260 /// \brief Build a new C++ __uuidof(expr) expression.
2262 /// By default, performs semantic analysis to build the new expression.
2263 /// Subclasses may override this routine to provide different behavior.
2264 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2265 SourceLocation TypeidLoc,
2267 SourceLocation RParenLoc) {
2268 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2272 /// \brief Build a new C++ "this" expression.
2274 /// By default, builds a new "this" expression without performing any
2275 /// semantic analysis. Subclasses may override this routine to provide
2276 /// different behavior.
2277 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2280 getSema().CheckCXXThisCapture(ThisLoc);
2281 return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2284 /// \brief Build a new C++ throw expression.
2286 /// By default, performs semantic analysis to build the new expression.
2287 /// Subclasses may override this routine to provide different behavior.
2288 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2289 bool IsThrownVariableInScope) {
2290 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2293 /// \brief Build a new C++ default-argument expression.
2295 /// By default, builds a new default-argument expression, which does not
2296 /// require any semantic analysis. Subclasses may override this routine to
2297 /// provide different behavior.
2298 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2299 ParmVarDecl *Param) {
2300 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2303 /// \brief Build a new C++11 default-initialization expression.
2305 /// By default, builds a new default field initialization expression, which
2306 /// does not require any semantic analysis. Subclasses may override this
2307 /// routine to provide different behavior.
2308 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2310 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2313 /// \brief Build a new C++ zero-initialization expression.
2315 /// By default, performs semantic analysis to build the new expression.
2316 /// Subclasses may override this routine to provide different behavior.
2317 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2318 SourceLocation LParenLoc,
2319 SourceLocation RParenLoc) {
2320 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
2324 /// \brief Build a new C++ "new" expression.
2326 /// By default, performs semantic analysis to build the new expression.
2327 /// Subclasses may override this routine to provide different behavior.
2328 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2330 SourceLocation PlacementLParen,
2331 MultiExprArg PlacementArgs,
2332 SourceLocation PlacementRParen,
2333 SourceRange TypeIdParens,
2334 QualType AllocatedType,
2335 TypeSourceInfo *AllocatedTypeInfo,
2337 SourceRange DirectInitRange,
2338 Expr *Initializer) {
2339 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2351 /// \brief Build a new C++ "delete" expression.
2353 /// By default, performs semantic analysis to build the new expression.
2354 /// Subclasses may override this routine to provide different behavior.
2355 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2356 bool IsGlobalDelete,
2359 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2363 /// \brief Build a new type trait expression.
2365 /// By default, performs semantic analysis to build the new expression.
2366 /// Subclasses may override this routine to provide different behavior.
2367 ExprResult RebuildTypeTrait(TypeTrait Trait,
2368 SourceLocation StartLoc,
2369 ArrayRef<TypeSourceInfo *> Args,
2370 SourceLocation RParenLoc) {
2371 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2374 /// \brief Build a new array type trait expression.
2376 /// By default, performs semantic analysis to build the new expression.
2377 /// Subclasses may override this routine to provide different behavior.
2378 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2379 SourceLocation StartLoc,
2380 TypeSourceInfo *TSInfo,
2382 SourceLocation RParenLoc) {
2383 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2386 /// \brief Build a new expression trait expression.
2388 /// By default, performs semantic analysis to build the new expression.
2389 /// Subclasses may override this routine to provide different behavior.
2390 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2391 SourceLocation StartLoc,
2393 SourceLocation RParenLoc) {
2394 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2397 /// \brief Build a new (previously unresolved) declaration reference
2400 /// By default, performs semantic analysis to build the new expression.
2401 /// Subclasses may override this routine to provide different behavior.
2402 ExprResult RebuildDependentScopeDeclRefExpr(
2403 NestedNameSpecifierLoc QualifierLoc,
2404 SourceLocation TemplateKWLoc,
2405 const DeclarationNameInfo &NameInfo,
2406 const TemplateArgumentListInfo *TemplateArgs,
2407 bool IsAddressOfOperand,
2408 TypeSourceInfo **RecoveryTSI) {
2410 SS.Adopt(QualifierLoc);
2412 if (TemplateArgs || TemplateKWLoc.isValid())
2413 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2416 return getSema().BuildQualifiedDeclarationNameExpr(
2417 SS, NameInfo, IsAddressOfOperand, RecoveryTSI);
2420 /// \brief Build a new template-id expression.
2422 /// By default, performs semantic analysis to build the new expression.
2423 /// Subclasses may override this routine to provide different behavior.
2424 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2425 SourceLocation TemplateKWLoc,
2428 const TemplateArgumentListInfo *TemplateArgs) {
2429 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2433 /// \brief Build a new object-construction expression.
2435 /// By default, performs semantic analysis to build the new expression.
2436 /// Subclasses may override this routine to provide different behavior.
2437 ExprResult RebuildCXXConstructExpr(QualType T,
2439 CXXConstructorDecl *Constructor,
2442 bool HadMultipleCandidates,
2443 bool ListInitialization,
2444 bool StdInitListInitialization,
2445 bool RequiresZeroInit,
2446 CXXConstructExpr::ConstructionKind ConstructKind,
2447 SourceRange ParenRange) {
2448 SmallVector<Expr*, 8> ConvertedArgs;
2449 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2453 return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
2455 HadMultipleCandidates,
2457 StdInitListInitialization,
2458 RequiresZeroInit, ConstructKind,
2462 /// \brief Build a new object-construction expression.
2464 /// By default, performs semantic analysis to build the new expression.
2465 /// Subclasses may override this routine to provide different behavior.
2466 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2467 SourceLocation LParenLoc,
2469 SourceLocation RParenLoc) {
2470 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2476 /// \brief Build a new object-construction expression.
2478 /// By default, performs semantic analysis to build the new expression.
2479 /// Subclasses may override this routine to provide different behavior.
2480 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2481 SourceLocation LParenLoc,
2483 SourceLocation RParenLoc) {
2484 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2490 /// \brief Build a new member reference expression.
2492 /// By default, performs semantic analysis to build the new expression.
2493 /// Subclasses may override this routine to provide different behavior.
2494 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2497 SourceLocation OperatorLoc,
2498 NestedNameSpecifierLoc QualifierLoc,
2499 SourceLocation TemplateKWLoc,
2500 NamedDecl *FirstQualifierInScope,
2501 const DeclarationNameInfo &MemberNameInfo,
2502 const TemplateArgumentListInfo *TemplateArgs) {
2504 SS.Adopt(QualifierLoc);
2506 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2507 OperatorLoc, IsArrow,
2509 FirstQualifierInScope,
2514 /// \brief Build a new member reference expression.
2516 /// By default, performs semantic analysis to build the new expression.
2517 /// Subclasses may override this routine to provide different behavior.
2518 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2519 SourceLocation OperatorLoc,
2521 NestedNameSpecifierLoc QualifierLoc,
2522 SourceLocation TemplateKWLoc,
2523 NamedDecl *FirstQualifierInScope,
2525 const TemplateArgumentListInfo *TemplateArgs) {
2527 SS.Adopt(QualifierLoc);
2529 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2530 OperatorLoc, IsArrow,
2532 FirstQualifierInScope,
2536 /// \brief Build a new noexcept expression.
2538 /// By default, performs semantic analysis to build the new expression.
2539 /// Subclasses may override this routine to provide different behavior.
2540 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2541 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2544 /// \brief Build a new expression to compute the length of a parameter pack.
2545 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
2546 SourceLocation PackLoc,
2547 SourceLocation RParenLoc,
2548 Optional<unsigned> Length) {
2550 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2551 OperatorLoc, Pack, PackLoc,
2552 RParenLoc, *Length);
2554 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2555 OperatorLoc, Pack, PackLoc,
2559 /// \brief Build a new Objective-C boxed expression.
2561 /// By default, performs semantic analysis to build the new expression.
2562 /// Subclasses may override this routine to provide different behavior.
2563 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2564 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2567 /// \brief Build a new Objective-C array literal.
2569 /// By default, performs semantic analysis to build the new expression.
2570 /// Subclasses may override this routine to provide different behavior.
2571 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2572 Expr **Elements, unsigned NumElements) {
2573 return getSema().BuildObjCArrayLiteral(Range,
2574 MultiExprArg(Elements, NumElements));
2577 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2578 Expr *Base, Expr *Key,
2579 ObjCMethodDecl *getterMethod,
2580 ObjCMethodDecl *setterMethod) {
2581 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2582 getterMethod, setterMethod);
2585 /// \brief Build a new Objective-C dictionary literal.
2587 /// By default, performs semantic analysis to build the new expression.
2588 /// Subclasses may override this routine to provide different behavior.
2589 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2590 ObjCDictionaryElement *Elements,
2591 unsigned NumElements) {
2592 return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
2595 /// \brief Build a new Objective-C \@encode expression.
2597 /// By default, performs semantic analysis to build the new expression.
2598 /// Subclasses may override this routine to provide different behavior.
2599 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2600 TypeSourceInfo *EncodeTypeInfo,
2601 SourceLocation RParenLoc) {
2602 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2605 /// \brief Build a new Objective-C class message.
2606 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2608 ArrayRef<SourceLocation> SelectorLocs,
2609 ObjCMethodDecl *Method,
2610 SourceLocation LBracLoc,
2612 SourceLocation RBracLoc) {
2613 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2614 ReceiverTypeInfo->getType(),
2615 /*SuperLoc=*/SourceLocation(),
2616 Sel, Method, LBracLoc, SelectorLocs,
2620 /// \brief Build a new Objective-C instance message.
2621 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2623 ArrayRef<SourceLocation> SelectorLocs,
2624 ObjCMethodDecl *Method,
2625 SourceLocation LBracLoc,
2627 SourceLocation RBracLoc) {
2628 return SemaRef.BuildInstanceMessage(Receiver,
2629 Receiver->getType(),
2630 /*SuperLoc=*/SourceLocation(),
2631 Sel, Method, LBracLoc, SelectorLocs,
2635 /// \brief Build a new Objective-C instance/class message to 'super'.
2636 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
2638 ArrayRef<SourceLocation> SelectorLocs,
2639 ObjCMethodDecl *Method,
2640 SourceLocation LBracLoc,
2642 SourceLocation RBracLoc) {
2643 ObjCInterfaceDecl *Class = Method->getClassInterface();
2644 QualType ReceiverTy = SemaRef.Context.getObjCInterfaceType(Class);
2646 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
2649 Sel, Method, LBracLoc, SelectorLocs,
2651 : SemaRef.BuildClassMessage(nullptr,
2654 Sel, Method, LBracLoc, SelectorLocs,
2660 /// \brief Build a new Objective-C ivar reference expression.
2662 /// By default, performs semantic analysis to build the new expression.
2663 /// Subclasses may override this routine to provide different behavior.
2664 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
2665 SourceLocation IvarLoc,
2666 bool IsArrow, bool IsFreeIvar) {
2667 // FIXME: We lose track of the IsFreeIvar bit.
2669 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
2670 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2671 /*FIXME:*/IvarLoc, IsArrow,
2672 SS, SourceLocation(),
2673 /*FirstQualifierInScope=*/nullptr,
2675 /*TemplateArgs=*/nullptr);
2678 /// \brief Build a new Objective-C property reference expression.
2680 /// By default, performs semantic analysis to build the new expression.
2681 /// Subclasses may override this routine to provide different behavior.
2682 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
2683 ObjCPropertyDecl *Property,
2684 SourceLocation PropertyLoc) {
2686 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
2687 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2688 /*FIXME:*/PropertyLoc,
2690 SS, SourceLocation(),
2691 /*FirstQualifierInScope=*/nullptr,
2693 /*TemplateArgs=*/nullptr);
2696 /// \brief Build a new Objective-C property reference expression.
2698 /// By default, performs semantic analysis to build the new expression.
2699 /// Subclasses may override this routine to provide different behavior.
2700 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
2701 ObjCMethodDecl *Getter,
2702 ObjCMethodDecl *Setter,
2703 SourceLocation PropertyLoc) {
2704 // Since these expressions can only be value-dependent, we do not
2705 // need to perform semantic analysis again.
2707 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
2708 VK_LValue, OK_ObjCProperty,
2709 PropertyLoc, Base));
2712 /// \brief Build a new Objective-C "isa" expression.
2714 /// By default, performs semantic analysis to build the new expression.
2715 /// Subclasses may override this routine to provide different behavior.
2716 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
2717 SourceLocation OpLoc, bool IsArrow) {
2719 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
2720 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2722 SS, SourceLocation(),
2723 /*FirstQualifierInScope=*/nullptr,
2725 /*TemplateArgs=*/nullptr);
2728 /// \brief Build a new shuffle vector expression.
2730 /// By default, performs semantic analysis to build the new expression.
2731 /// Subclasses may override this routine to provide different behavior.
2732 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
2733 MultiExprArg SubExprs,
2734 SourceLocation RParenLoc) {
2735 // Find the declaration for __builtin_shufflevector
2736 const IdentifierInfo &Name
2737 = SemaRef.Context.Idents.get("__builtin_shufflevector");
2738 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
2739 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
2740 assert(!Lookup.empty() && "No __builtin_shufflevector?");
2742 // Build a reference to the __builtin_shufflevector builtin
2743 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
2744 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
2745 SemaRef.Context.BuiltinFnTy,
2746 VK_RValue, BuiltinLoc);
2747 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
2748 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
2749 CK_BuiltinFnToFnPtr).get();
2751 // Build the CallExpr
2752 ExprResult TheCall = new (SemaRef.Context) CallExpr(
2753 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
2754 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
2756 // Type-check the __builtin_shufflevector expression.
2757 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
2760 /// \brief Build a new convert vector expression.
2761 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
2762 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
2763 SourceLocation RParenLoc) {
2764 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
2765 BuiltinLoc, RParenLoc);
2768 /// \brief Build a new template argument pack expansion.
2770 /// By default, performs semantic analysis to build a new pack expansion
2771 /// for a template argument. Subclasses may override this routine to provide
2772 /// different behavior.
2773 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
2774 SourceLocation EllipsisLoc,
2775 Optional<unsigned> NumExpansions) {
2776 switch (Pattern.getArgument().getKind()) {
2777 case TemplateArgument::Expression: {
2779 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
2780 EllipsisLoc, NumExpansions);
2781 if (Result.isInvalid())
2782 return TemplateArgumentLoc();
2784 return TemplateArgumentLoc(Result.get(), Result.get());
2787 case TemplateArgument::Template:
2788 return TemplateArgumentLoc(TemplateArgument(
2789 Pattern.getArgument().getAsTemplate(),
2791 Pattern.getTemplateQualifierLoc(),
2792 Pattern.getTemplateNameLoc(),
2795 case TemplateArgument::Null:
2796 case TemplateArgument::Integral:
2797 case TemplateArgument::Declaration:
2798 case TemplateArgument::Pack:
2799 case TemplateArgument::TemplateExpansion:
2800 case TemplateArgument::NullPtr:
2801 llvm_unreachable("Pack expansion pattern has no parameter packs");
2803 case TemplateArgument::Type:
2804 if (TypeSourceInfo *Expansion
2805 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
2808 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
2813 return TemplateArgumentLoc();
2816 /// \brief Build a new expression pack expansion.
2818 /// By default, performs semantic analysis to build a new pack expansion
2819 /// for an expression. Subclasses may override this routine to provide
2820 /// different behavior.
2821 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
2822 Optional<unsigned> NumExpansions) {
2823 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
2826 /// \brief Build a new C++1z fold-expression.
2828 /// By default, performs semantic analysis in order to build a new fold
2830 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
2831 BinaryOperatorKind Operator,
2832 SourceLocation EllipsisLoc, Expr *RHS,
2833 SourceLocation RParenLoc) {
2834 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
2838 /// \brief Build an empty C++1z fold-expression with the given operator.
2840 /// By default, produces the fallback value for the fold-expression, or
2841 /// produce an error if there is no fallback value.
2842 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
2843 BinaryOperatorKind Operator) {
2844 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
2847 /// \brief Build a new atomic operation expression.
2849 /// By default, performs semantic analysis to build the new expression.
2850 /// Subclasses may override this routine to provide different behavior.
2851 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
2852 MultiExprArg SubExprs,
2854 AtomicExpr::AtomicOp Op,
2855 SourceLocation RParenLoc) {
2856 // Just create the expression; there is not any interesting semantic
2857 // analysis here because we can't actually build an AtomicExpr until
2858 // we are sure it is semantically sound.
2859 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
2864 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
2865 QualType ObjectType,
2866 NamedDecl *FirstQualifierInScope,
2869 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
2870 QualType ObjectType,
2871 NamedDecl *FirstQualifierInScope,
2874 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
2875 NamedDecl *FirstQualifierInScope,
2879 template<typename Derived>
2880 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
2884 switch (S->getStmtClass()) {
2885 case Stmt::NoStmtClass: break;
2887 // Transform individual statement nodes
2888 #define STMT(Node, Parent) \
2889 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
2890 #define ABSTRACT_STMT(Node)
2891 #define EXPR(Node, Parent)
2892 #include "clang/AST/StmtNodes.inc"
2894 // Transform expressions by calling TransformExpr.
2895 #define STMT(Node, Parent)
2896 #define ABSTRACT_STMT(Stmt)
2897 #define EXPR(Node, Parent) case Stmt::Node##Class:
2898 #include "clang/AST/StmtNodes.inc"
2900 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
2904 return getSema().ActOnExprStmt(E);
2911 template<typename Derived>
2912 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
2916 switch (S->getClauseKind()) {
2918 // Transform individual clause nodes
2919 #define OPENMP_CLAUSE(Name, Class) \
2920 case OMPC_ ## Name : \
2921 return getDerived().Transform ## Class(cast<Class>(S));
2922 #include "clang/Basic/OpenMPKinds.def"
2929 template<typename Derived>
2930 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
2934 switch (E->getStmtClass()) {
2935 case Stmt::NoStmtClass: break;
2936 #define STMT(Node, Parent) case Stmt::Node##Class: break;
2937 #define ABSTRACT_STMT(Stmt)
2938 #define EXPR(Node, Parent) \
2939 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
2940 #include "clang/AST/StmtNodes.inc"
2946 template<typename Derived>
2947 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
2949 // Initializers are instantiated like expressions, except that various outer
2950 // layers are stripped.
2954 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2955 Init = ExprTemp->getSubExpr();
2957 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
2958 Init = MTE->GetTemporaryExpr();
2960 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2961 Init = Binder->getSubExpr();
2963 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2964 Init = ICE->getSubExprAsWritten();
2966 if (CXXStdInitializerListExpr *ILE =
2967 dyn_cast<CXXStdInitializerListExpr>(Init))
2968 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
2970 // If this is copy-initialization, we only need to reconstruct
2971 // InitListExprs. Other forms of copy-initialization will be a no-op if
2972 // the initializer is already the right type.
2973 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
2974 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
2975 return getDerived().TransformExpr(Init);
2977 // Revert value-initialization back to empty parens.
2978 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
2979 SourceRange Parens = VIE->getSourceRange();
2980 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
2984 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
2985 if (isa<ImplicitValueInitExpr>(Init))
2986 return getDerived().RebuildParenListExpr(SourceLocation(), None,
2989 // Revert initialization by constructor back to a parenthesized or braced list
2990 // of expressions. Any other form of initializer can just be reused directly.
2991 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
2992 return getDerived().TransformExpr(Init);
2994 // If the initialization implicitly converted an initializer list to a
2995 // std::initializer_list object, unwrap the std::initializer_list too.
2996 if (Construct && Construct->isStdInitListInitialization())
2997 return TransformInitializer(Construct->getArg(0), NotCopyInit);
2999 SmallVector<Expr*, 8> NewArgs;
3000 bool ArgChanged = false;
3001 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3002 /*IsCall*/true, NewArgs, &ArgChanged))
3005 // If this was list initialization, revert to list form.
3006 if (Construct->isListInitialization())
3007 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
3008 Construct->getLocEnd(),
3009 Construct->getType());
3011 // Build a ParenListExpr to represent anything else.
3012 SourceRange Parens = Construct->getParenOrBraceRange();
3013 if (Parens.isInvalid()) {
3014 // This was a variable declaration's initialization for which no initializer
3016 assert(NewArgs.empty() &&
3017 "no parens or braces but have direct init with arguments?");
3020 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3024 template<typename Derived>
3025 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
3028 SmallVectorImpl<Expr *> &Outputs,
3030 for (unsigned I = 0; I != NumInputs; ++I) {
3031 // If requested, drop call arguments that need to be dropped.
3032 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3039 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3040 Expr *Pattern = Expansion->getPattern();
3042 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3043 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3044 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3046 // Determine whether the set of unexpanded parameter packs can and should
3049 bool RetainExpansion = false;
3050 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3051 Optional<unsigned> NumExpansions = OrigNumExpansions;
3052 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3053 Pattern->getSourceRange(),
3055 Expand, RetainExpansion,
3060 // The transform has determined that we should perform a simple
3061 // transformation on the pack expansion, producing another pack
3063 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3064 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3065 if (OutPattern.isInvalid())
3068 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3069 Expansion->getEllipsisLoc(),
3071 if (Out.isInvalid())
3076 Outputs.push_back(Out.get());
3080 // Record right away that the argument was changed. This needs
3081 // to happen even if the array expands to nothing.
3082 if (ArgChanged) *ArgChanged = true;
3084 // The transform has determined that we should perform an elementwise
3085 // expansion of the pattern. Do so.
3086 for (unsigned I = 0; I != *NumExpansions; ++I) {
3087 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3088 ExprResult Out = getDerived().TransformExpr(Pattern);
3089 if (Out.isInvalid())
3092 // FIXME: Can this happen? We should not try to expand the pack
3094 if (Out.get()->containsUnexpandedParameterPack()) {
3095 Out = getDerived().RebuildPackExpansion(
3096 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3097 if (Out.isInvalid())
3101 Outputs.push_back(Out.get());
3104 // If we're supposed to retain a pack expansion, do so by temporarily
3105 // forgetting the partially-substituted parameter pack.
3106 if (RetainExpansion) {
3107 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3109 ExprResult Out = getDerived().TransformExpr(Pattern);
3110 if (Out.isInvalid())
3113 Out = getDerived().RebuildPackExpansion(
3114 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3115 if (Out.isInvalid())
3118 Outputs.push_back(Out.get());
3125 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3126 : getDerived().TransformExpr(Inputs[I]);
3127 if (Result.isInvalid())
3130 if (Result.get() != Inputs[I] && ArgChanged)
3133 Outputs.push_back(Result.get());
3139 template<typename Derived>
3140 NestedNameSpecifierLoc
3141 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3142 NestedNameSpecifierLoc NNS,
3143 QualType ObjectType,
3144 NamedDecl *FirstQualifierInScope) {
3145 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3146 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3147 Qualifier = Qualifier.getPrefix())
3148 Qualifiers.push_back(Qualifier);
3151 while (!Qualifiers.empty()) {
3152 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3153 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3155 switch (QNNS->getKind()) {
3156 case NestedNameSpecifier::Identifier:
3157 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr,
3158 *QNNS->getAsIdentifier(),
3159 Q.getLocalBeginLoc(),
3161 ObjectType, false, SS,
3162 FirstQualifierInScope, false))
3163 return NestedNameSpecifierLoc();
3167 case NestedNameSpecifier::Namespace: {
3169 = cast_or_null<NamespaceDecl>(
3170 getDerived().TransformDecl(
3171 Q.getLocalBeginLoc(),
3172 QNNS->getAsNamespace()));
3173 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3177 case NestedNameSpecifier::NamespaceAlias: {
3178 NamespaceAliasDecl *Alias
3179 = cast_or_null<NamespaceAliasDecl>(
3180 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3181 QNNS->getAsNamespaceAlias()));
3182 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3183 Q.getLocalEndLoc());
3187 case NestedNameSpecifier::Global:
3188 // There is no meaningful transformation that one could perform on the
3190 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3193 case NestedNameSpecifier::Super: {
3195 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3196 SourceLocation(), QNNS->getAsRecordDecl()));
3197 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3201 case NestedNameSpecifier::TypeSpecWithTemplate:
3202 case NestedNameSpecifier::TypeSpec: {
3203 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3204 FirstQualifierInScope, SS);
3207 return NestedNameSpecifierLoc();
3209 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3210 (SemaRef.getLangOpts().CPlusPlus11 &&
3211 TL.getType()->isEnumeralType())) {
3212 assert(!TL.getType().hasLocalQualifiers() &&
3213 "Can't get cv-qualifiers here");
3214 if (TL.getType()->isEnumeralType())
3215 SemaRef.Diag(TL.getBeginLoc(),
3216 diag::warn_cxx98_compat_enum_nested_name_spec);
3217 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3218 Q.getLocalEndLoc());
3221 // If the nested-name-specifier is an invalid type def, don't emit an
3222 // error because a previous error should have already been emitted.
3223 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3224 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3225 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3226 << TL.getType() << SS.getRange();
3228 return NestedNameSpecifierLoc();
3232 // The qualifier-in-scope and object type only apply to the leftmost entity.
3233 FirstQualifierInScope = nullptr;
3234 ObjectType = QualType();
3237 // Don't rebuild the nested-name-specifier if we don't have to.
3238 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3239 !getDerived().AlwaysRebuild())
3242 // If we can re-use the source-location data from the original
3243 // nested-name-specifier, do so.
3244 if (SS.location_size() == NNS.getDataLength() &&
3245 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3246 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3248 // Allocate new nested-name-specifier location information.
3249 return SS.getWithLocInContext(SemaRef.Context);
3252 template<typename Derived>
3254 TreeTransform<Derived>
3255 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3256 DeclarationName Name = NameInfo.getName();
3258 return DeclarationNameInfo();
3260 switch (Name.getNameKind()) {
3261 case DeclarationName::Identifier:
3262 case DeclarationName::ObjCZeroArgSelector:
3263 case DeclarationName::ObjCOneArgSelector:
3264 case DeclarationName::ObjCMultiArgSelector:
3265 case DeclarationName::CXXOperatorName:
3266 case DeclarationName::CXXLiteralOperatorName:
3267 case DeclarationName::CXXUsingDirective:
3270 case DeclarationName::CXXConstructorName:
3271 case DeclarationName::CXXDestructorName:
3272 case DeclarationName::CXXConversionFunctionName: {
3273 TypeSourceInfo *NewTInfo;
3274 CanQualType NewCanTy;
3275 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3276 NewTInfo = getDerived().TransformType(OldTInfo);
3278 return DeclarationNameInfo();
3279 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3283 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3284 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3286 return DeclarationNameInfo();
3287 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3290 DeclarationName NewName
3291 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3293 DeclarationNameInfo NewNameInfo(NameInfo);
3294 NewNameInfo.setName(NewName);
3295 NewNameInfo.setNamedTypeInfo(NewTInfo);
3300 llvm_unreachable("Unknown name kind.");
3303 template<typename Derived>
3305 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3307 SourceLocation NameLoc,
3308 QualType ObjectType,
3309 NamedDecl *FirstQualifierInScope) {
3310 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3311 TemplateDecl *Template = QTN->getTemplateDecl();
3312 assert(Template && "qualified template name must refer to a template");
3314 TemplateDecl *TransTemplate
3315 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3318 return TemplateName();
3320 if (!getDerived().AlwaysRebuild() &&
3321 SS.getScopeRep() == QTN->getQualifier() &&
3322 TransTemplate == Template)
3325 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3329 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3330 if (SS.getScopeRep()) {
3331 // These apply to the scope specifier, not the template.
3332 ObjectType = QualType();
3333 FirstQualifierInScope = nullptr;
3336 if (!getDerived().AlwaysRebuild() &&
3337 SS.getScopeRep() == DTN->getQualifier() &&
3338 ObjectType.isNull())
3341 if (DTN->isIdentifier()) {
3342 return getDerived().RebuildTemplateName(SS,
3343 *DTN->getIdentifier(),
3346 FirstQualifierInScope);
3349 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
3353 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3354 TemplateDecl *TransTemplate
3355 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3358 return TemplateName();
3360 if (!getDerived().AlwaysRebuild() &&
3361 TransTemplate == Template)
3364 return TemplateName(TransTemplate);
3367 if (SubstTemplateTemplateParmPackStorage *SubstPack
3368 = Name.getAsSubstTemplateTemplateParmPack()) {
3369 TemplateTemplateParmDecl *TransParam
3370 = cast_or_null<TemplateTemplateParmDecl>(
3371 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3373 return TemplateName();
3375 if (!getDerived().AlwaysRebuild() &&
3376 TransParam == SubstPack->getParameterPack())
3379 return getDerived().RebuildTemplateName(TransParam,
3380 SubstPack->getArgumentPack());
3383 // These should be getting filtered out before they reach the AST.
3384 llvm_unreachable("overloaded function decl survived to here");
3387 template<typename Derived>
3388 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3389 const TemplateArgument &Arg,
3390 TemplateArgumentLoc &Output) {
3391 SourceLocation Loc = getDerived().getBaseLocation();
3392 switch (Arg.getKind()) {
3393 case TemplateArgument::Null:
3394 llvm_unreachable("null template argument in TreeTransform");
3397 case TemplateArgument::Type:
3398 Output = TemplateArgumentLoc(Arg,
3399 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3403 case TemplateArgument::Template:
3404 case TemplateArgument::TemplateExpansion: {
3405 NestedNameSpecifierLocBuilder Builder;
3406 TemplateName Template = Arg.getAsTemplate();
3407 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3408 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3409 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3410 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3412 if (Arg.getKind() == TemplateArgument::Template)
3413 Output = TemplateArgumentLoc(Arg,
3414 Builder.getWithLocInContext(SemaRef.Context),
3417 Output = TemplateArgumentLoc(Arg,
3418 Builder.getWithLocInContext(SemaRef.Context),
3424 case TemplateArgument::Expression:
3425 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3428 case TemplateArgument::Declaration:
3429 case TemplateArgument::Integral:
3430 case TemplateArgument::Pack:
3431 case TemplateArgument::NullPtr:
3432 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3437 template<typename Derived>
3438 bool TreeTransform<Derived>::TransformTemplateArgument(
3439 const TemplateArgumentLoc &Input,
3440 TemplateArgumentLoc &Output) {
3441 const TemplateArgument &Arg = Input.getArgument();
3442 switch (Arg.getKind()) {
3443 case TemplateArgument::Null:
3444 case TemplateArgument::Integral:
3445 case TemplateArgument::Pack:
3446 case TemplateArgument::Declaration:
3447 case TemplateArgument::NullPtr:
3448 llvm_unreachable("Unexpected TemplateArgument");
3450 case TemplateArgument::Type: {
3451 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3453 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3455 DI = getDerived().TransformType(DI);
3456 if (!DI) return true;
3458 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3462 case TemplateArgument::Template: {
3463 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3465 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3471 SS.Adopt(QualifierLoc);
3472 TemplateName Template
3473 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3474 Input.getTemplateNameLoc());
3475 if (Template.isNull())
3478 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3479 Input.getTemplateNameLoc());
3483 case TemplateArgument::TemplateExpansion:
3484 llvm_unreachable("Caller should expand pack expansions");
3486 case TemplateArgument::Expression: {
3487 // Template argument expressions are constant expressions.
3488 EnterExpressionEvaluationContext Unevaluated(getSema(),
3489 Sema::ConstantEvaluated);
3491 Expr *InputExpr = Input.getSourceExpression();
3492 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3494 ExprResult E = getDerived().TransformExpr(InputExpr);
3495 E = SemaRef.ActOnConstantExpression(E);
3496 if (E.isInvalid()) return true;
3497 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3502 // Work around bogus GCC warning
3506 /// \brief Iterator adaptor that invents template argument location information
3507 /// for each of the template arguments in its underlying iterator.
3508 template<typename Derived, typename InputIterator>
3509 class TemplateArgumentLocInventIterator {
3510 TreeTransform<Derived> &Self;
3514 typedef TemplateArgumentLoc value_type;
3515 typedef TemplateArgumentLoc reference;
3516 typedef typename std::iterator_traits<InputIterator>::difference_type
3518 typedef std::input_iterator_tag iterator_category;
3521 TemplateArgumentLoc Arg;
3524 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3526 const TemplateArgumentLoc *operator->() const { return &Arg; }
3529 TemplateArgumentLocInventIterator() { }
3531 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3533 : Self(Self), Iter(Iter) { }
3535 TemplateArgumentLocInventIterator &operator++() {
3540 TemplateArgumentLocInventIterator operator++(int) {
3541 TemplateArgumentLocInventIterator Old(*this);
3546 reference operator*() const {
3547 TemplateArgumentLoc Result;
3548 Self.InventTemplateArgumentLoc(*Iter, Result);
3552 pointer operator->() const { return pointer(**this); }
3554 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3555 const TemplateArgumentLocInventIterator &Y) {
3556 return X.Iter == Y.Iter;
3559 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3560 const TemplateArgumentLocInventIterator &Y) {
3561 return X.Iter != Y.Iter;
3565 template<typename Derived>
3566 template<typename InputIterator>
3567 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
3569 TemplateArgumentListInfo &Outputs) {
3570 for (; First != Last; ++First) {
3571 TemplateArgumentLoc Out;
3572 TemplateArgumentLoc In = *First;
3574 if (In.getArgument().getKind() == TemplateArgument::Pack) {
3575 // Unpack argument packs, which we translate them into separate
3577 // FIXME: We could do much better if we could guarantee that the
3578 // TemplateArgumentLocInfo for the pack expansion would be usable for
3579 // all of the template arguments in the argument pack.
3580 typedef TemplateArgumentLocInventIterator<Derived,
3581 TemplateArgument::pack_iterator>
3583 if (TransformTemplateArguments(PackLocIterator(*this,
3584 In.getArgument().pack_begin()),
3585 PackLocIterator(*this,
3586 In.getArgument().pack_end()),
3593 if (In.getArgument().isPackExpansion()) {
3594 // We have a pack expansion, for which we will be substituting into
3596 SourceLocation Ellipsis;
3597 Optional<unsigned> OrigNumExpansions;
3598 TemplateArgumentLoc Pattern
3599 = getSema().getTemplateArgumentPackExpansionPattern(
3600 In, Ellipsis, OrigNumExpansions);
3602 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3603 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3604 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3606 // Determine whether the set of unexpanded parameter packs can and should
3609 bool RetainExpansion = false;
3610 Optional<unsigned> NumExpansions = OrigNumExpansions;
3611 if (getDerived().TryExpandParameterPacks(Ellipsis,
3612 Pattern.getSourceRange(),
3620 // The transform has determined that we should perform a simple
3621 // transformation on the pack expansion, producing another pack
3623 TemplateArgumentLoc OutPattern;
3624 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3625 if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
3628 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
3630 if (Out.getArgument().isNull())
3633 Outputs.addArgument(Out);
3637 // The transform has determined that we should perform an elementwise
3638 // expansion of the pattern. Do so.
3639 for (unsigned I = 0; I != *NumExpansions; ++I) {
3640 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3642 if (getDerived().TransformTemplateArgument(Pattern, Out))
3645 if (Out.getArgument().containsUnexpandedParameterPack()) {
3646 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3648 if (Out.getArgument().isNull())
3652 Outputs.addArgument(Out);
3655 // If we're supposed to retain a pack expansion, do so by temporarily
3656 // forgetting the partially-substituted parameter pack.
3657 if (RetainExpansion) {
3658 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3660 if (getDerived().TransformTemplateArgument(Pattern, Out))
3663 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3665 if (Out.getArgument().isNull())
3668 Outputs.addArgument(Out);
3675 if (getDerived().TransformTemplateArgument(In, Out))
3678 Outputs.addArgument(Out);
3685 //===----------------------------------------------------------------------===//
3686 // Type transformation
3687 //===----------------------------------------------------------------------===//
3689 template<typename Derived>
3690 QualType TreeTransform<Derived>::TransformType(QualType T) {
3691 if (getDerived().AlreadyTransformed(T))
3694 // Temporary workaround. All of these transformations should
3695 // eventually turn into transformations on TypeLocs.
3696 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
3697 getDerived().getBaseLocation());
3699 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
3704 return NewDI->getType();
3707 template<typename Derived>
3708 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
3709 // Refine the base location to the type's location.
3710 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
3711 getDerived().getBaseEntity());
3712 if (getDerived().AlreadyTransformed(DI->getType()))
3717 TypeLoc TL = DI->getTypeLoc();
3718 TLB.reserve(TL.getFullDataSize());
3720 QualType Result = getDerived().TransformType(TLB, TL);
3721 if (Result.isNull())
3724 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3727 template<typename Derived>
3729 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
3730 switch (T.getTypeLocClass()) {
3731 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3732 #define TYPELOC(CLASS, PARENT) \
3733 case TypeLoc::CLASS: \
3734 return getDerived().Transform##CLASS##Type(TLB, \
3735 T.castAs<CLASS##TypeLoc>());
3736 #include "clang/AST/TypeLocNodes.def"
3739 llvm_unreachable("unhandled type loc!");
3742 /// FIXME: By default, this routine adds type qualifiers only to types
3743 /// that can have qualifiers, and silently suppresses those qualifiers
3744 /// that are not permitted (e.g., qualifiers on reference or function
3745 /// types). This is the right thing for template instantiation, but
3746 /// probably not for other clients.
3747 template<typename Derived>
3749 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
3750 QualifiedTypeLoc T) {
3751 Qualifiers Quals = T.getType().getLocalQualifiers();
3753 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
3754 if (Result.isNull())
3757 // Silently suppress qualifiers if the result type can't be qualified.
3758 // FIXME: this is the right thing for template instantiation, but
3759 // probably not for other clients.
3760 if (Result->isFunctionType() || Result->isReferenceType())
3763 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
3765 if (Quals.hasObjCLifetime()) {
3766 if (!Result->isObjCLifetimeType() && !Result->isDependentType())
3767 Quals.removeObjCLifetime();
3768 else if (Result.getObjCLifetime()) {
3770 // A lifetime qualifier applied to a substituted template parameter
3771 // overrides the lifetime qualifier from the template argument.
3772 const AutoType *AutoTy;
3773 if (const SubstTemplateTypeParmType *SubstTypeParam
3774 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
3775 QualType Replacement = SubstTypeParam->getReplacementType();
3776 Qualifiers Qs = Replacement.getQualifiers();
3777 Qs.removeObjCLifetime();
3779 = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
3781 Result = SemaRef.Context.getSubstTemplateTypeParmType(
3782 SubstTypeParam->getReplacedParameter(),
3784 TLB.TypeWasModifiedSafely(Result);
3785 } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
3786 // 'auto' types behave the same way as template parameters.
3787 QualType Deduced = AutoTy->getDeducedType();
3788 Qualifiers Qs = Deduced.getQualifiers();
3789 Qs.removeObjCLifetime();
3790 Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
3792 Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto(),
3793 AutoTy->isDependentType());
3794 TLB.TypeWasModifiedSafely(Result);
3796 // Otherwise, complain about the addition of a qualifier to an
3797 // already-qualified type.
3798 SourceRange R = T.getUnqualifiedLoc().getSourceRange();
3799 SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
3802 Quals.removeObjCLifetime();
3806 if (!Quals.empty()) {
3807 Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
3808 // BuildQualifiedType might not add qualifiers if they are invalid.
3809 if (Result.hasLocalQualifiers())
3810 TLB.push<QualifiedTypeLoc>(Result);
3811 // No location information to preserve.
3817 template<typename Derived>
3819 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
3820 QualType ObjectType,
3821 NamedDecl *UnqualLookup,
3823 if (getDerived().AlreadyTransformed(TL.getType()))
3826 TypeSourceInfo *TSI =
3827 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
3829 return TSI->getTypeLoc();
3833 template<typename Derived>
3835 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3836 QualType ObjectType,
3837 NamedDecl *UnqualLookup,
3839 if (getDerived().AlreadyTransformed(TSInfo->getType()))
3842 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
3846 template <typename Derived>
3847 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
3848 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
3850 QualType T = TL.getType();
3851 assert(!getDerived().AlreadyTransformed(T));
3856 if (isa<TemplateSpecializationType>(T)) {
3857 TemplateSpecializationTypeLoc SpecTL =
3858 TL.castAs<TemplateSpecializationTypeLoc>();
3860 TemplateName Template
3861 = getDerived().TransformTemplateName(SS,
3862 SpecTL.getTypePtr()->getTemplateName(),
3863 SpecTL.getTemplateNameLoc(),
3864 ObjectType, UnqualLookup);
3865 if (Template.isNull())
3868 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
3870 } else if (isa<DependentTemplateSpecializationType>(T)) {
3871 DependentTemplateSpecializationTypeLoc SpecTL =
3872 TL.castAs<DependentTemplateSpecializationTypeLoc>();
3874 TemplateName Template
3875 = getDerived().RebuildTemplateName(SS,
3876 *SpecTL.getTypePtr()->getIdentifier(),
3877 SpecTL.getTemplateNameLoc(),
3878 ObjectType, UnqualLookup);
3879 if (Template.isNull())
3882 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
3887 // Nothing special needs to be done for these.
3888 Result = getDerived().TransformType(TLB, TL);
3891 if (Result.isNull())
3894 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3897 template <class TyLoc> static inline
3898 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
3899 TyLoc NewT = TLB.push<TyLoc>(T.getType());
3900 NewT.setNameLoc(T.getNameLoc());
3904 template<typename Derived>
3905 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
3907 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
3908 NewT.setBuiltinLoc(T.getBuiltinLoc());
3909 if (T.needsExtraLocalData())
3910 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
3914 template<typename Derived>
3915 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
3918 return TransformTypeSpecType(TLB, T);
3921 template <typename Derived>
3922 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
3923 AdjustedTypeLoc TL) {
3924 // Adjustments applied during transformation are handled elsewhere.
3925 return getDerived().TransformType(TLB, TL.getOriginalLoc());
3928 template<typename Derived>
3929 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
3930 DecayedTypeLoc TL) {
3931 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
3932 if (OriginalType.isNull())
3935 QualType Result = TL.getType();
3936 if (getDerived().AlwaysRebuild() ||
3937 OriginalType != TL.getOriginalLoc().getType())
3938 Result = SemaRef.Context.getDecayedType(OriginalType);
3939 TLB.push<DecayedTypeLoc>(Result);
3940 // Nothing to set for DecayedTypeLoc.
3944 template<typename Derived>
3945 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
3946 PointerTypeLoc TL) {
3947 QualType PointeeType
3948 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3949 if (PointeeType.isNull())
3952 QualType Result = TL.getType();
3953 if (PointeeType->getAs<ObjCObjectType>()) {
3954 // A dependent pointer type 'T *' has is being transformed such
3955 // that an Objective-C class type is being replaced for 'T'. The
3956 // resulting pointer type is an ObjCObjectPointerType, not a
3958 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
3960 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
3961 NewT.setStarLoc(TL.getStarLoc());
3965 if (getDerived().AlwaysRebuild() ||
3966 PointeeType != TL.getPointeeLoc().getType()) {
3967 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
3968 if (Result.isNull())
3972 // Objective-C ARC can add lifetime qualifiers to the type that we're
3974 TLB.TypeWasModifiedSafely(Result->getPointeeType());
3976 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
3977 NewT.setSigilLoc(TL.getSigilLoc());
3981 template<typename Derived>
3983 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
3984 BlockPointerTypeLoc TL) {
3985 QualType PointeeType
3986 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3987 if (PointeeType.isNull())
3990 QualType Result = TL.getType();
3991 if (getDerived().AlwaysRebuild() ||
3992 PointeeType != TL.getPointeeLoc().getType()) {
3993 Result = getDerived().RebuildBlockPointerType(PointeeType,
3995 if (Result.isNull())
3999 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4000 NewT.setSigilLoc(TL.getSigilLoc());
4004 /// Transforms a reference type. Note that somewhat paradoxically we
4005 /// don't care whether the type itself is an l-value type or an r-value
4006 /// type; we only care if the type was *written* as an l-value type
4007 /// or an r-value type.
4008 template<typename Derived>
4010 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4011 ReferenceTypeLoc TL) {
4012 const ReferenceType *T = TL.getTypePtr();
4014 // Note that this works with the pointee-as-written.
4015 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4016 if (PointeeType.isNull())
4019 QualType Result = TL.getType();
4020 if (getDerived().AlwaysRebuild() ||
4021 PointeeType != T->getPointeeTypeAsWritten()) {
4022 Result = getDerived().RebuildReferenceType(PointeeType,
4023 T->isSpelledAsLValue(),
4025 if (Result.isNull())
4029 // Objective-C ARC can add lifetime qualifiers to the type that we're
4031 TLB.TypeWasModifiedSafely(
4032 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4034 // r-value references can be rebuilt as l-value references.
4035 ReferenceTypeLoc NewTL;
4036 if (isa<LValueReferenceType>(Result))
4037 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4039 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4040 NewTL.setSigilLoc(TL.getSigilLoc());
4045 template<typename Derived>
4047 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4048 LValueReferenceTypeLoc TL) {
4049 return TransformReferenceType(TLB, TL);
4052 template<typename Derived>
4054 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4055 RValueReferenceTypeLoc TL) {
4056 return TransformReferenceType(TLB, TL);
4059 template<typename Derived>
4061 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4062 MemberPointerTypeLoc TL) {
4063 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4064 if (PointeeType.isNull())
4067 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4068 TypeSourceInfo *NewClsTInfo = nullptr;
4070 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4075 const MemberPointerType *T = TL.getTypePtr();
4076 QualType OldClsType = QualType(T->getClass(), 0);
4077 QualType NewClsType;
4079 NewClsType = NewClsTInfo->getType();
4081 NewClsType = getDerived().TransformType(OldClsType);
4082 if (NewClsType.isNull())
4086 QualType Result = TL.getType();
4087 if (getDerived().AlwaysRebuild() ||
4088 PointeeType != T->getPointeeType() ||
4089 NewClsType != OldClsType) {
4090 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4092 if (Result.isNull())
4096 // If we had to adjust the pointee type when building a member pointer, make
4097 // sure to push TypeLoc info for it.
4098 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4099 if (MPT && PointeeType != MPT->getPointeeType()) {
4100 assert(isa<AdjustedType>(MPT->getPointeeType()));
4101 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4104 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4105 NewTL.setSigilLoc(TL.getSigilLoc());
4106 NewTL.setClassTInfo(NewClsTInfo);
4111 template<typename Derived>
4113 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4114 ConstantArrayTypeLoc TL) {
4115 const ConstantArrayType *T = TL.getTypePtr();
4116 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4117 if (ElementType.isNull())
4120 QualType Result = TL.getType();
4121 if (getDerived().AlwaysRebuild() ||
4122 ElementType != T->getElementType()) {
4123 Result = getDerived().RebuildConstantArrayType(ElementType,
4124 T->getSizeModifier(),
4126 T->getIndexTypeCVRQualifiers(),
4127 TL.getBracketsRange());
4128 if (Result.isNull())
4132 // We might have either a ConstantArrayType or a VariableArrayType now:
4133 // a ConstantArrayType is allowed to have an element type which is a
4134 // VariableArrayType if the type is dependent. Fortunately, all array
4135 // types have the same location layout.
4136 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4137 NewTL.setLBracketLoc(TL.getLBracketLoc());
4138 NewTL.setRBracketLoc(TL.getRBracketLoc());
4140 Expr *Size = TL.getSizeExpr();
4142 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4143 Sema::ConstantEvaluated);
4144 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4145 Size = SemaRef.ActOnConstantExpression(Size).get();
4147 NewTL.setSizeExpr(Size);
4152 template<typename Derived>
4153 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4154 TypeLocBuilder &TLB,
4155 IncompleteArrayTypeLoc TL) {
4156 const IncompleteArrayType *T = TL.getTypePtr();
4157 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4158 if (ElementType.isNull())
4161 QualType Result = TL.getType();
4162 if (getDerived().AlwaysRebuild() ||
4163 ElementType != T->getElementType()) {
4164 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4165 T->getSizeModifier(),
4166 T->getIndexTypeCVRQualifiers(),
4167 TL.getBracketsRange());
4168 if (Result.isNull())
4172 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4173 NewTL.setLBracketLoc(TL.getLBracketLoc());
4174 NewTL.setRBracketLoc(TL.getRBracketLoc());
4175 NewTL.setSizeExpr(nullptr);
4180 template<typename Derived>
4182 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4183 VariableArrayTypeLoc TL) {
4184 const VariableArrayType *T = TL.getTypePtr();
4185 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4186 if (ElementType.isNull())
4189 ExprResult SizeResult
4190 = getDerived().TransformExpr(T->getSizeExpr());
4191 if (SizeResult.isInvalid())
4194 Expr *Size = SizeResult.get();
4196 QualType Result = TL.getType();
4197 if (getDerived().AlwaysRebuild() ||
4198 ElementType != T->getElementType() ||
4199 Size != T->getSizeExpr()) {
4200 Result = getDerived().RebuildVariableArrayType(ElementType,
4201 T->getSizeModifier(),
4203 T->getIndexTypeCVRQualifiers(),
4204 TL.getBracketsRange());
4205 if (Result.isNull())
4209 // We might have constant size array now, but fortunately it has the same
4211 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4212 NewTL.setLBracketLoc(TL.getLBracketLoc());
4213 NewTL.setRBracketLoc(TL.getRBracketLoc());
4214 NewTL.setSizeExpr(Size);
4219 template<typename Derived>
4221 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4222 DependentSizedArrayTypeLoc TL) {
4223 const DependentSizedArrayType *T = TL.getTypePtr();
4224 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4225 if (ElementType.isNull())
4228 // Array bounds are constant expressions.
4229 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4230 Sema::ConstantEvaluated);
4232 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4233 Expr *origSize = TL.getSizeExpr();
4234 if (!origSize) origSize = T->getSizeExpr();
4236 ExprResult sizeResult
4237 = getDerived().TransformExpr(origSize);
4238 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4239 if (sizeResult.isInvalid())
4242 Expr *size = sizeResult.get();
4244 QualType Result = TL.getType();
4245 if (getDerived().AlwaysRebuild() ||
4246 ElementType != T->getElementType() ||
4248 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4249 T->getSizeModifier(),
4251 T->getIndexTypeCVRQualifiers(),
4252 TL.getBracketsRange());
4253 if (Result.isNull())
4257 // We might have any sort of array type now, but fortunately they
4258 // all have the same location layout.
4259 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4260 NewTL.setLBracketLoc(TL.getLBracketLoc());
4261 NewTL.setRBracketLoc(TL.getRBracketLoc());
4262 NewTL.setSizeExpr(size);
4267 template<typename Derived>
4268 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4269 TypeLocBuilder &TLB,
4270 DependentSizedExtVectorTypeLoc TL) {
4271 const DependentSizedExtVectorType *T = TL.getTypePtr();
4273 // FIXME: ext vector locs should be nested
4274 QualType ElementType = getDerived().TransformType(T->getElementType());
4275 if (ElementType.isNull())
4278 // Vector sizes are constant expressions.
4279 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4280 Sema::ConstantEvaluated);
4282 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4283 Size = SemaRef.ActOnConstantExpression(Size);
4284 if (Size.isInvalid())
4287 QualType Result = TL.getType();
4288 if (getDerived().AlwaysRebuild() ||
4289 ElementType != T->getElementType() ||
4290 Size.get() != T->getSizeExpr()) {
4291 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4293 T->getAttributeLoc());
4294 if (Result.isNull())
4298 // Result might be dependent or not.
4299 if (isa<DependentSizedExtVectorType>(Result)) {
4300 DependentSizedExtVectorTypeLoc NewTL
4301 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4302 NewTL.setNameLoc(TL.getNameLoc());
4304 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4305 NewTL.setNameLoc(TL.getNameLoc());
4311 template<typename Derived>
4312 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4314 const VectorType *T = TL.getTypePtr();
4315 QualType ElementType = getDerived().TransformType(T->getElementType());
4316 if (ElementType.isNull())
4319 QualType Result = TL.getType();
4320 if (getDerived().AlwaysRebuild() ||
4321 ElementType != T->getElementType()) {
4322 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
4323 T->getVectorKind());
4324 if (Result.isNull())
4328 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4329 NewTL.setNameLoc(TL.getNameLoc());
4334 template<typename Derived>
4335 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
4336 ExtVectorTypeLoc TL) {
4337 const VectorType *T = TL.getTypePtr();
4338 QualType ElementType = getDerived().TransformType(T->getElementType());
4339 if (ElementType.isNull())
4342 QualType Result = TL.getType();
4343 if (getDerived().AlwaysRebuild() ||
4344 ElementType != T->getElementType()) {
4345 Result = getDerived().RebuildExtVectorType(ElementType,
4346 T->getNumElements(),
4347 /*FIXME*/ SourceLocation());
4348 if (Result.isNull())
4352 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4353 NewTL.setNameLoc(TL.getNameLoc());
4358 template <typename Derived>
4359 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
4360 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
4361 bool ExpectParameterPack) {
4362 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
4363 TypeSourceInfo *NewDI = nullptr;
4365 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
4366 // If we're substituting into a pack expansion type and we know the
4367 // length we want to expand to, just substitute for the pattern.
4368 TypeLoc OldTL = OldDI->getTypeLoc();
4369 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4372 TypeLoc NewTL = OldDI->getTypeLoc();
4373 TLB.reserve(NewTL.getFullDataSize());
4375 QualType Result = getDerived().TransformType(TLB,
4376 OldExpansionTL.getPatternLoc());
4377 if (Result.isNull())
4380 Result = RebuildPackExpansionType(Result,
4381 OldExpansionTL.getPatternLoc().getSourceRange(),
4382 OldExpansionTL.getEllipsisLoc(),
4384 if (Result.isNull())
4387 PackExpansionTypeLoc NewExpansionTL
4388 = TLB.push<PackExpansionTypeLoc>(Result);
4389 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4390 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4392 NewDI = getDerived().TransformType(OldDI);
4396 if (NewDI == OldDI && indexAdjustment == 0)
4399 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4400 OldParm->getDeclContext(),
4401 OldParm->getInnerLocStart(),
4402 OldParm->getLocation(),
4403 OldParm->getIdentifier(),
4406 OldParm->getStorageClass(),
4407 /* DefArg */ nullptr);
4408 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4409 OldParm->getFunctionScopeIndex() + indexAdjustment);
4413 template<typename Derived>
4414 bool TreeTransform<Derived>::
4415 TransformFunctionTypeParams(SourceLocation Loc,
4416 ParmVarDecl **Params, unsigned NumParams,
4417 const QualType *ParamTypes,
4418 SmallVectorImpl<QualType> &OutParamTypes,
4419 SmallVectorImpl<ParmVarDecl*> *PVars) {
4420 int indexAdjustment = 0;
4422 for (unsigned i = 0; i != NumParams; ++i) {
4423 if (ParmVarDecl *OldParm = Params[i]) {
4424 assert(OldParm->getFunctionScopeIndex() == i);
4426 Optional<unsigned> NumExpansions;
4427 ParmVarDecl *NewParm = nullptr;
4428 if (OldParm->isParameterPack()) {
4429 // We have a function parameter pack that may need to be expanded.
4430 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4432 // Find the parameter packs that could be expanded.
4433 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4434 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4435 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4436 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4437 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4439 // Determine whether we should expand the parameter packs.
4440 bool ShouldExpand = false;
4441 bool RetainExpansion = false;
4442 Optional<unsigned> OrigNumExpansions =
4443 ExpansionTL.getTypePtr()->getNumExpansions();
4444 NumExpansions = OrigNumExpansions;
4445 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4446 Pattern.getSourceRange(),
4455 // Expand the function parameter pack into multiple, separate
4457 getDerived().ExpandingFunctionParameterPack(OldParm);
4458 for (unsigned I = 0; I != *NumExpansions; ++I) {
4459 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4460 ParmVarDecl *NewParm
4461 = getDerived().TransformFunctionTypeParam(OldParm,
4464 /*ExpectParameterPack=*/false);
4468 OutParamTypes.push_back(NewParm->getType());
4470 PVars->push_back(NewParm);
4473 // If we're supposed to retain a pack expansion, do so by temporarily
4474 // forgetting the partially-substituted parameter pack.
4475 if (RetainExpansion) {
4476 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4477 ParmVarDecl *NewParm
4478 = getDerived().TransformFunctionTypeParam(OldParm,
4481 /*ExpectParameterPack=*/false);
4485 OutParamTypes.push_back(NewParm->getType());
4487 PVars->push_back(NewParm);
4490 // The next parameter should have the same adjustment as the
4491 // last thing we pushed, but we post-incremented indexAdjustment
4492 // on every push. Also, if we push nothing, the adjustment should
4496 // We're done with the pack expansion.
4500 // We'll substitute the parameter now without expanding the pack
4502 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4503 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4506 /*ExpectParameterPack=*/true);
4508 NewParm = getDerived().TransformFunctionTypeParam(
4509 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4515 OutParamTypes.push_back(NewParm->getType());
4517 PVars->push_back(NewParm);
4521 // Deal with the possibility that we don't have a parameter
4522 // declaration for this parameter.
4523 QualType OldType = ParamTypes[i];
4524 bool IsPackExpansion = false;
4525 Optional<unsigned> NumExpansions;
4527 if (const PackExpansionType *Expansion
4528 = dyn_cast<PackExpansionType>(OldType)) {
4529 // We have a function parameter pack that may need to be expanded.
4530 QualType Pattern = Expansion->getPattern();
4531 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4532 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4534 // Determine whether we should expand the parameter packs.
4535 bool ShouldExpand = false;
4536 bool RetainExpansion = false;
4537 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
4546 // Expand the function parameter pack into multiple, separate
4548 for (unsigned I = 0; I != *NumExpansions; ++I) {
4549 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4550 QualType NewType = getDerived().TransformType(Pattern);
4551 if (NewType.isNull())
4554 OutParamTypes.push_back(NewType);
4556 PVars->push_back(nullptr);
4559 // We're done with the pack expansion.
4563 // If we're supposed to retain a pack expansion, do so by temporarily
4564 // forgetting the partially-substituted parameter pack.
4565 if (RetainExpansion) {
4566 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4567 QualType NewType = getDerived().TransformType(Pattern);
4568 if (NewType.isNull())
4571 OutParamTypes.push_back(NewType);
4573 PVars->push_back(nullptr);
4576 // We'll substitute the parameter now without expanding the pack
4578 OldType = Expansion->getPattern();
4579 IsPackExpansion = true;
4580 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4581 NewType = getDerived().TransformType(OldType);
4583 NewType = getDerived().TransformType(OldType);
4586 if (NewType.isNull())
4589 if (IsPackExpansion)
4590 NewType = getSema().Context.getPackExpansionType(NewType,
4593 OutParamTypes.push_back(NewType);
4595 PVars->push_back(nullptr);
4600 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
4601 if (ParmVarDecl *parm = (*PVars)[i])
4602 assert(parm->getFunctionScopeIndex() == i);
4609 template<typename Derived>
4611 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4612 FunctionProtoTypeLoc TL) {
4613 SmallVector<QualType, 4> ExceptionStorage;
4614 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
4615 return getDerived().TransformFunctionProtoType(
4616 TLB, TL, nullptr, 0,
4617 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
4618 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
4619 ExceptionStorage, Changed);
4623 template<typename Derived> template<typename Fn>
4624 QualType TreeTransform<Derived>::TransformFunctionProtoType(
4625 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
4626 unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
4627 // Transform the parameters and return type.
4629 // We are required to instantiate the params and return type in source order.
4630 // When the function has a trailing return type, we instantiate the
4631 // parameters before the return type, since the return type can then refer
4632 // to the parameters themselves (via decltype, sizeof, etc.).
4634 SmallVector<QualType, 4> ParamTypes;
4635 SmallVector<ParmVarDecl*, 4> ParamDecls;
4636 const FunctionProtoType *T = TL.getTypePtr();
4638 QualType ResultType;
4640 if (T->hasTrailingReturn()) {
4641 if (getDerived().TransformFunctionTypeParams(
4642 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4643 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4647 // C++11 [expr.prim.general]p3:
4648 // If a declaration declares a member function or member function
4649 // template of a class X, the expression this is a prvalue of type
4650 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4651 // and the end of the function-definition, member-declarator, or
4653 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
4655 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4656 if (ResultType.isNull())
4661 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4662 if (ResultType.isNull())
4665 if (getDerived().TransformFunctionTypeParams(
4666 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4667 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4671 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
4673 bool EPIChanged = false;
4674 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
4677 // FIXME: Need to transform ConsumedParameters for variadic template
4680 QualType Result = TL.getType();
4681 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
4682 T->getNumParams() != ParamTypes.size() ||
4683 !std::equal(T->param_type_begin(), T->param_type_end(),
4684 ParamTypes.begin()) || EPIChanged) {
4685 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
4686 if (Result.isNull())
4690 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
4691 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4692 NewTL.setLParenLoc(TL.getLParenLoc());
4693 NewTL.setRParenLoc(TL.getRParenLoc());
4694 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4695 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
4696 NewTL.setParam(i, ParamDecls[i]);
4701 template<typename Derived>
4702 bool TreeTransform<Derived>::TransformExceptionSpec(
4703 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
4704 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
4705 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
4707 // Instantiate a dynamic noexcept expression, if any.
4708 if (ESI.Type == EST_ComputedNoexcept) {
4709 EnterExpressionEvaluationContext Unevaluated(getSema(),
4710 Sema::ConstantEvaluated);
4711 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
4712 if (NoexceptExpr.isInvalid())
4715 NoexceptExpr = getSema().CheckBooleanCondition(
4716 NoexceptExpr.get(), NoexceptExpr.get()->getLocStart());
4717 if (NoexceptExpr.isInvalid())
4720 if (!NoexceptExpr.get()->isValueDependent()) {
4721 NoexceptExpr = getSema().VerifyIntegerConstantExpression(
4722 NoexceptExpr.get(), nullptr,
4723 diag::err_noexcept_needs_constant_expression,
4724 /*AllowFold*/false);
4725 if (NoexceptExpr.isInvalid())
4729 if (ESI.NoexceptExpr != NoexceptExpr.get())
4731 ESI.NoexceptExpr = NoexceptExpr.get();
4734 if (ESI.Type != EST_Dynamic)
4737 // Instantiate a dynamic exception specification's type.
4738 for (QualType T : ESI.Exceptions) {
4739 if (const PackExpansionType *PackExpansion =
4740 T->getAs<PackExpansionType>()) {
4743 // We have a pack expansion. Instantiate it.
4744 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4745 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
4747 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4749 // Determine whether the set of unexpanded parameter packs can and
4752 bool Expand = false;
4753 bool RetainExpansion = false;
4754 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
4755 // FIXME: Track the location of the ellipsis (and track source location
4756 // information for the types in the exception specification in general).
4757 if (getDerived().TryExpandParameterPacks(
4758 Loc, SourceRange(), Unexpanded, Expand,
4759 RetainExpansion, NumExpansions))
4763 // We can't expand this pack expansion into separate arguments yet;
4764 // just substitute into the pattern and create a new pack expansion
4766 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4767 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4771 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
4772 Exceptions.push_back(U);
4776 // Substitute into the pack expansion pattern for each slice of the
4778 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
4779 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
4781 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4782 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4785 Exceptions.push_back(U);
4788 QualType U = getDerived().TransformType(T);
4789 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4794 Exceptions.push_back(U);
4798 ESI.Exceptions = Exceptions;
4802 template<typename Derived>
4803 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
4804 TypeLocBuilder &TLB,
4805 FunctionNoProtoTypeLoc TL) {
4806 const FunctionNoProtoType *T = TL.getTypePtr();
4807 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4808 if (ResultType.isNull())
4811 QualType Result = TL.getType();
4812 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
4813 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
4815 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
4816 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4817 NewTL.setLParenLoc(TL.getLParenLoc());
4818 NewTL.setRParenLoc(TL.getRParenLoc());
4819 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4824 template<typename Derived> QualType
4825 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
4826 UnresolvedUsingTypeLoc TL) {
4827 const UnresolvedUsingType *T = TL.getTypePtr();
4828 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
4832 QualType Result = TL.getType();
4833 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
4834 Result = getDerived().RebuildUnresolvedUsingType(D);
4835 if (Result.isNull())
4839 // We might get an arbitrary type spec type back. We should at
4840 // least always get a type spec type, though.
4841 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
4842 NewTL.setNameLoc(TL.getNameLoc());
4847 template<typename Derived>
4848 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
4849 TypedefTypeLoc TL) {
4850 const TypedefType *T = TL.getTypePtr();
4851 TypedefNameDecl *Typedef
4852 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4857 QualType Result = TL.getType();
4858 if (getDerived().AlwaysRebuild() ||
4859 Typedef != T->getDecl()) {
4860 Result = getDerived().RebuildTypedefType(Typedef);
4861 if (Result.isNull())
4865 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
4866 NewTL.setNameLoc(TL.getNameLoc());
4871 template<typename Derived>
4872 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
4873 TypeOfExprTypeLoc TL) {
4874 // typeof expressions are not potentially evaluated contexts
4875 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4876 Sema::ReuseLambdaContextDecl);
4878 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
4882 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
4886 QualType Result = TL.getType();
4887 if (getDerived().AlwaysRebuild() ||
4888 E.get() != TL.getUnderlyingExpr()) {
4889 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
4890 if (Result.isNull())
4895 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
4896 NewTL.setTypeofLoc(TL.getTypeofLoc());
4897 NewTL.setLParenLoc(TL.getLParenLoc());
4898 NewTL.setRParenLoc(TL.getRParenLoc());
4903 template<typename Derived>
4904 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
4906 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
4907 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
4911 QualType Result = TL.getType();
4912 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
4913 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
4914 if (Result.isNull())
4918 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
4919 NewTL.setTypeofLoc(TL.getTypeofLoc());
4920 NewTL.setLParenLoc(TL.getLParenLoc());
4921 NewTL.setRParenLoc(TL.getRParenLoc());
4922 NewTL.setUnderlyingTInfo(New_Under_TI);
4927 template<typename Derived>
4928 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
4929 DecltypeTypeLoc TL) {
4930 const DecltypeType *T = TL.getTypePtr();
4932 // decltype expressions are not potentially evaluated contexts
4933 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4934 nullptr, /*IsDecltype=*/ true);
4936 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
4940 E = getSema().ActOnDecltypeExpression(E.get());
4944 QualType Result = TL.getType();
4945 if (getDerived().AlwaysRebuild() ||
4946 E.get() != T->getUnderlyingExpr()) {
4947 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
4948 if (Result.isNull())
4953 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
4954 NewTL.setNameLoc(TL.getNameLoc());
4959 template<typename Derived>
4960 QualType TreeTransform<Derived>::TransformUnaryTransformType(
4961 TypeLocBuilder &TLB,
4962 UnaryTransformTypeLoc TL) {
4963 QualType Result = TL.getType();
4964 if (Result->isDependentType()) {
4965 const UnaryTransformType *T = TL.getTypePtr();
4967 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
4968 Result = getDerived().RebuildUnaryTransformType(NewBase,
4971 if (Result.isNull())
4975 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
4976 NewTL.setKWLoc(TL.getKWLoc());
4977 NewTL.setParensRange(TL.getParensRange());
4978 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
4982 template<typename Derived>
4983 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
4985 const AutoType *T = TL.getTypePtr();
4986 QualType OldDeduced = T->getDeducedType();
4987 QualType NewDeduced;
4988 if (!OldDeduced.isNull()) {
4989 NewDeduced = getDerived().TransformType(OldDeduced);
4990 if (NewDeduced.isNull())
4994 QualType Result = TL.getType();
4995 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
4996 T->isDependentType()) {
4997 Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
4998 if (Result.isNull())
5002 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5003 NewTL.setNameLoc(TL.getNameLoc());
5008 template<typename Derived>
5009 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5011 const RecordType *T = TL.getTypePtr();
5013 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5018 QualType Result = TL.getType();
5019 if (getDerived().AlwaysRebuild() ||
5020 Record != T->getDecl()) {
5021 Result = getDerived().RebuildRecordType(Record);
5022 if (Result.isNull())
5026 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5027 NewTL.setNameLoc(TL.getNameLoc());
5032 template<typename Derived>
5033 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5035 const EnumType *T = TL.getTypePtr();
5037 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5042 QualType Result = TL.getType();
5043 if (getDerived().AlwaysRebuild() ||
5044 Enum != T->getDecl()) {
5045 Result = getDerived().RebuildEnumType(Enum);
5046 if (Result.isNull())
5050 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5051 NewTL.setNameLoc(TL.getNameLoc());
5056 template<typename Derived>
5057 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5058 TypeLocBuilder &TLB,
5059 InjectedClassNameTypeLoc TL) {
5060 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5061 TL.getTypePtr()->getDecl());
5062 if (!D) return QualType();
5064 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5065 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5069 template<typename Derived>
5070 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5071 TypeLocBuilder &TLB,
5072 TemplateTypeParmTypeLoc TL) {
5073 return TransformTypeSpecType(TLB, TL);
5076 template<typename Derived>
5077 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5078 TypeLocBuilder &TLB,
5079 SubstTemplateTypeParmTypeLoc TL) {
5080 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5082 // Substitute into the replacement type, which itself might involve something
5083 // that needs to be transformed. This only tends to occur with default
5084 // template arguments of template template parameters.
5085 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5086 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5087 if (Replacement.isNull())
5090 // Always canonicalize the replacement type.
5091 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5093 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5096 // Propagate type-source information.
5097 SubstTemplateTypeParmTypeLoc NewTL
5098 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5099 NewTL.setNameLoc(TL.getNameLoc());
5104 template<typename Derived>
5105 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5106 TypeLocBuilder &TLB,
5107 SubstTemplateTypeParmPackTypeLoc TL) {
5108 return TransformTypeSpecType(TLB, TL);
5111 template<typename Derived>
5112 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5113 TypeLocBuilder &TLB,
5114 TemplateSpecializationTypeLoc TL) {
5115 const TemplateSpecializationType *T = TL.getTypePtr();
5117 // The nested-name-specifier never matters in a TemplateSpecializationType,
5118 // because we can't have a dependent nested-name-specifier anyway.
5120 TemplateName Template
5121 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5122 TL.getTemplateNameLoc());
5123 if (Template.isNull())
5126 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5129 template<typename Derived>
5130 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5132 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5133 if (ValueType.isNull())
5136 QualType Result = TL.getType();
5137 if (getDerived().AlwaysRebuild() ||
5138 ValueType != TL.getValueLoc().getType()) {
5139 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5140 if (Result.isNull())
5144 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5145 NewTL.setKWLoc(TL.getKWLoc());
5146 NewTL.setLParenLoc(TL.getLParenLoc());
5147 NewTL.setRParenLoc(TL.getRParenLoc());
5152 /// \brief Simple iterator that traverses the template arguments in a
5153 /// container that provides a \c getArgLoc() member function.
5155 /// This iterator is intended to be used with the iterator form of
5156 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5157 template<typename ArgLocContainer>
5158 class TemplateArgumentLocContainerIterator {
5159 ArgLocContainer *Container;
5163 typedef TemplateArgumentLoc value_type;
5164 typedef TemplateArgumentLoc reference;
5165 typedef int difference_type;
5166 typedef std::input_iterator_tag iterator_category;
5169 TemplateArgumentLoc Arg;
5172 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5174 const TemplateArgumentLoc *operator->() const {
5180 TemplateArgumentLocContainerIterator() {}
5182 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5184 : Container(&Container), Index(Index) { }
5186 TemplateArgumentLocContainerIterator &operator++() {
5191 TemplateArgumentLocContainerIterator operator++(int) {
5192 TemplateArgumentLocContainerIterator Old(*this);
5197 TemplateArgumentLoc operator*() const {
5198 return Container->getArgLoc(Index);
5201 pointer operator->() const {
5202 return pointer(Container->getArgLoc(Index));
5205 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5206 const TemplateArgumentLocContainerIterator &Y) {
5207 return X.Container == Y.Container && X.Index == Y.Index;
5210 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
5211 const TemplateArgumentLocContainerIterator &Y) {
5217 template <typename Derived>
5218 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5219 TypeLocBuilder &TLB,
5220 TemplateSpecializationTypeLoc TL,
5221 TemplateName Template) {
5222 TemplateArgumentListInfo NewTemplateArgs;
5223 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5224 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5225 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
5227 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5228 ArgIterator(TL, TL.getNumArgs()),
5232 // FIXME: maybe don't rebuild if all the template arguments are the same.
5235 getDerived().RebuildTemplateSpecializationType(Template,
5236 TL.getTemplateNameLoc(),
5239 if (!Result.isNull()) {
5240 // Specializations of template template parameters are represented as
5241 // TemplateSpecializationTypes, and substitution of type alias templates
5242 // within a dependent context can transform them into
5243 // DependentTemplateSpecializationTypes.
5244 if (isa<DependentTemplateSpecializationType>(Result)) {
5245 DependentTemplateSpecializationTypeLoc NewTL
5246 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5247 NewTL.setElaboratedKeywordLoc(SourceLocation());
5248 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
5249 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5250 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5251 NewTL.setLAngleLoc(TL.getLAngleLoc());
5252 NewTL.setRAngleLoc(TL.getRAngleLoc());
5253 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5254 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5258 TemplateSpecializationTypeLoc NewTL
5259 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5260 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5261 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5262 NewTL.setLAngleLoc(TL.getLAngleLoc());
5263 NewTL.setRAngleLoc(TL.getRAngleLoc());
5264 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5265 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5271 template <typename Derived>
5272 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
5273 TypeLocBuilder &TLB,
5274 DependentTemplateSpecializationTypeLoc TL,
5275 TemplateName Template,
5277 TemplateArgumentListInfo NewTemplateArgs;
5278 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5279 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5280 typedef TemplateArgumentLocContainerIterator<
5281 DependentTemplateSpecializationTypeLoc> ArgIterator;
5282 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5283 ArgIterator(TL, TL.getNumArgs()),
5287 // FIXME: maybe don't rebuild if all the template arguments are the same.
5289 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
5291 = getSema().Context.getDependentTemplateSpecializationType(
5292 TL.getTypePtr()->getKeyword(),
5293 DTN->getQualifier(),
5294 DTN->getIdentifier(),
5297 DependentTemplateSpecializationTypeLoc NewTL
5298 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5299 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5300 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
5301 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5302 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5303 NewTL.setLAngleLoc(TL.getLAngleLoc());
5304 NewTL.setRAngleLoc(TL.getRAngleLoc());
5305 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5306 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5311 = getDerived().RebuildTemplateSpecializationType(Template,
5312 TL.getTemplateNameLoc(),
5315 if (!Result.isNull()) {
5316 /// FIXME: Wrap this in an elaborated-type-specifier?
5317 TemplateSpecializationTypeLoc NewTL
5318 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5319 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5320 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5321 NewTL.setLAngleLoc(TL.getLAngleLoc());
5322 NewTL.setRAngleLoc(TL.getRAngleLoc());
5323 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5324 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5330 template<typename Derived>
5332 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
5333 ElaboratedTypeLoc TL) {
5334 const ElaboratedType *T = TL.getTypePtr();
5336 NestedNameSpecifierLoc QualifierLoc;
5337 // NOTE: the qualifier in an ElaboratedType is optional.
5338 if (TL.getQualifierLoc()) {
5340 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5345 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
5346 if (NamedT.isNull())
5349 // C++0x [dcl.type.elab]p2:
5350 // If the identifier resolves to a typedef-name or the simple-template-id
5351 // resolves to an alias template specialization, the
5352 // elaborated-type-specifier is ill-formed.
5353 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
5354 if (const TemplateSpecializationType *TST =
5355 NamedT->getAs<TemplateSpecializationType>()) {
5356 TemplateName Template = TST->getTemplateName();
5357 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
5358 Template.getAsTemplateDecl())) {
5359 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
5360 diag::err_tag_reference_non_tag) << 4;
5361 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
5366 QualType Result = TL.getType();
5367 if (getDerived().AlwaysRebuild() ||
5368 QualifierLoc != TL.getQualifierLoc() ||
5369 NamedT != T->getNamedType()) {
5370 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
5372 QualifierLoc, NamedT);
5373 if (Result.isNull())
5377 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5378 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5379 NewTL.setQualifierLoc(QualifierLoc);
5383 template<typename Derived>
5384 QualType TreeTransform<Derived>::TransformAttributedType(
5385 TypeLocBuilder &TLB,
5386 AttributedTypeLoc TL) {
5387 const AttributedType *oldType = TL.getTypePtr();
5388 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
5389 if (modifiedType.isNull())
5392 QualType result = TL.getType();
5394 // FIXME: dependent operand expressions?
5395 if (getDerived().AlwaysRebuild() ||
5396 modifiedType != oldType->getModifiedType()) {
5397 // TODO: this is really lame; we should really be rebuilding the
5398 // equivalent type from first principles.
5399 QualType equivalentType
5400 = getDerived().TransformType(oldType->getEquivalentType());
5401 if (equivalentType.isNull())
5404 // Check whether we can add nullability; it is only represented as
5405 // type sugar, and therefore cannot be diagnosed in any other way.
5406 if (auto nullability = oldType->getImmediateNullability()) {
5407 if (!modifiedType->canHaveNullability()) {
5408 SemaRef.Diag(TL.getAttrNameLoc(), diag::err_nullability_nonpointer)
5409 << DiagNullabilityKind(*nullability, false) << modifiedType;
5414 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
5419 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
5420 newTL.setAttrNameLoc(TL.getAttrNameLoc());
5421 if (TL.hasAttrOperand())
5422 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5423 if (TL.hasAttrExprOperand())
5424 newTL.setAttrExprOperand(TL.getAttrExprOperand());
5425 else if (TL.hasAttrEnumOperand())
5426 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
5431 template<typename Derived>
5433 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
5435 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
5439 QualType Result = TL.getType();
5440 if (getDerived().AlwaysRebuild() ||
5441 Inner != TL.getInnerLoc().getType()) {
5442 Result = getDerived().RebuildParenType(Inner);
5443 if (Result.isNull())
5447 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
5448 NewTL.setLParenLoc(TL.getLParenLoc());
5449 NewTL.setRParenLoc(TL.getRParenLoc());
5453 template<typename Derived>
5454 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
5455 DependentNameTypeLoc TL) {
5456 const DependentNameType *T = TL.getTypePtr();
5458 NestedNameSpecifierLoc QualifierLoc
5459 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5464 = getDerived().RebuildDependentNameType(T->getKeyword(),
5465 TL.getElaboratedKeywordLoc(),
5469 if (Result.isNull())
5472 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5473 QualType NamedT = ElabT->getNamedType();
5474 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5476 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5477 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5478 NewTL.setQualifierLoc(QualifierLoc);
5480 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5481 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5482 NewTL.setQualifierLoc(QualifierLoc);
5483 NewTL.setNameLoc(TL.getNameLoc());
5488 template<typename Derived>
5489 QualType TreeTransform<Derived>::
5490 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5491 DependentTemplateSpecializationTypeLoc TL) {
5492 NestedNameSpecifierLoc QualifierLoc;
5493 if (TL.getQualifierLoc()) {
5495 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5501 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
5504 template<typename Derived>
5505 QualType TreeTransform<Derived>::
5506 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5507 DependentTemplateSpecializationTypeLoc TL,
5508 NestedNameSpecifierLoc QualifierLoc) {
5509 const DependentTemplateSpecializationType *T = TL.getTypePtr();
5511 TemplateArgumentListInfo NewTemplateArgs;
5512 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5513 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5515 typedef TemplateArgumentLocContainerIterator<
5516 DependentTemplateSpecializationTypeLoc> ArgIterator;
5517 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5518 ArgIterator(TL, TL.getNumArgs()),
5523 = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
5526 TL.getTemplateNameLoc(),
5528 if (Result.isNull())
5531 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
5532 QualType NamedT = ElabT->getNamedType();
5534 // Copy information relevant to the template specialization.
5535 TemplateSpecializationTypeLoc NamedTL
5536 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5537 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5538 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5539 NamedTL.setLAngleLoc(TL.getLAngleLoc());
5540 NamedTL.setRAngleLoc(TL.getRAngleLoc());
5541 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5542 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5544 // Copy information relevant to the elaborated type.
5545 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5546 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5547 NewTL.setQualifierLoc(QualifierLoc);
5548 } else if (isa<DependentTemplateSpecializationType>(Result)) {
5549 DependentTemplateSpecializationTypeLoc SpecTL
5550 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5551 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5552 SpecTL.setQualifierLoc(QualifierLoc);
5553 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5554 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5555 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5556 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5557 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5558 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5560 TemplateSpecializationTypeLoc SpecTL
5561 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5562 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5563 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5564 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5565 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5566 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5567 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5572 template<typename Derived>
5573 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
5574 PackExpansionTypeLoc TL) {
5576 = getDerived().TransformType(TLB, TL.getPatternLoc());
5577 if (Pattern.isNull())
5580 QualType Result = TL.getType();
5581 if (getDerived().AlwaysRebuild() ||
5582 Pattern != TL.getPatternLoc().getType()) {
5583 Result = getDerived().RebuildPackExpansionType(Pattern,
5584 TL.getPatternLoc().getSourceRange(),
5585 TL.getEllipsisLoc(),
5586 TL.getTypePtr()->getNumExpansions());
5587 if (Result.isNull())
5591 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
5592 NewT.setEllipsisLoc(TL.getEllipsisLoc());
5596 template<typename Derived>
5598 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
5599 ObjCInterfaceTypeLoc TL) {
5600 // ObjCInterfaceType is never dependent.
5601 TLB.pushFullCopy(TL);
5602 return TL.getType();
5605 template<typename Derived>
5607 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
5608 ObjCObjectTypeLoc TL) {
5609 // ObjCObjectType is never dependent.
5610 TLB.pushFullCopy(TL);
5611 return TL.getType();
5614 template<typename Derived>
5616 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
5617 ObjCObjectPointerTypeLoc TL) {
5618 // ObjCObjectPointerType is never dependent.
5619 TLB.pushFullCopy(TL);
5620 return TL.getType();
5623 //===----------------------------------------------------------------------===//
5624 // Statement transformation
5625 //===----------------------------------------------------------------------===//
5626 template<typename Derived>
5628 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
5632 template<typename Derived>
5634 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
5635 return getDerived().TransformCompoundStmt(S, false);
5638 template<typename Derived>
5640 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
5642 Sema::CompoundScopeRAII CompoundScope(getSema());
5644 bool SubStmtInvalid = false;
5645 bool SubStmtChanged = false;
5646 SmallVector<Stmt*, 8> Statements;
5647 for (auto *B : S->body()) {
5648 StmtResult Result = getDerived().TransformStmt(B);
5649 if (Result.isInvalid()) {
5650 // Immediately fail if this was a DeclStmt, since it's very
5651 // likely that this will cause problems for future statements.
5652 if (isa<DeclStmt>(B))
5655 // Otherwise, just keep processing substatements and fail later.
5656 SubStmtInvalid = true;
5660 SubStmtChanged = SubStmtChanged || Result.get() != B;
5661 Statements.push_back(Result.getAs<Stmt>());
5667 if (!getDerived().AlwaysRebuild() &&
5671 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
5677 template<typename Derived>
5679 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
5680 ExprResult LHS, RHS;
5682 EnterExpressionEvaluationContext Unevaluated(SemaRef,
5683 Sema::ConstantEvaluated);
5685 // Transform the left-hand case value.
5686 LHS = getDerived().TransformExpr(S->getLHS());
5687 LHS = SemaRef.ActOnConstantExpression(LHS);
5688 if (LHS.isInvalid())
5691 // Transform the right-hand case value (for the GNU case-range extension).
5692 RHS = getDerived().TransformExpr(S->getRHS());
5693 RHS = SemaRef.ActOnConstantExpression(RHS);
5694 if (RHS.isInvalid())
5698 // Build the case statement.
5699 // Case statements are always rebuilt so that they will attached to their
5700 // transformed switch statement.
5701 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
5703 S->getEllipsisLoc(),
5706 if (Case.isInvalid())
5709 // Transform the statement following the case
5710 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5711 if (SubStmt.isInvalid())
5714 // Attach the body to the case statement
5715 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
5718 template<typename Derived>
5720 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
5721 // Transform the statement following the default case
5722 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5723 if (SubStmt.isInvalid())
5726 // Default statements are always rebuilt
5727 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
5731 template<typename Derived>
5733 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
5734 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5735 if (SubStmt.isInvalid())
5738 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
5744 // FIXME: Pass the real colon location in.
5745 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
5746 cast<LabelDecl>(LD), SourceLocation(),
5750 template <typename Derived>
5751 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
5755 switch (R->getKind()) {
5756 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
5758 #define PRAGMA_SPELLING_ATTR(X) \
5760 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
5761 #include "clang/Basic/AttrList.inc"
5767 template <typename Derived>
5768 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
5769 bool AttrsChanged = false;
5770 SmallVector<const Attr *, 1> Attrs;
5772 // Visit attributes and keep track if any are transformed.
5773 for (const auto *I : S->getAttrs()) {
5774 const Attr *R = getDerived().TransformAttr(I);
5775 AttrsChanged |= (I != R);
5779 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5780 if (SubStmt.isInvalid())
5783 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
5786 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
5790 template<typename Derived>
5792 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
5793 // Transform the condition
5795 VarDecl *ConditionVar = nullptr;
5796 if (S->getConditionVariable()) {
5798 = cast_or_null<VarDecl>(
5799 getDerived().TransformDefinition(
5800 S->getConditionVariable()->getLocation(),
5801 S->getConditionVariable()));
5805 Cond = getDerived().TransformExpr(S->getCond());
5807 if (Cond.isInvalid())
5810 // Convert the condition to a boolean value.
5812 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr, S->getIfLoc(),
5814 if (CondE.isInvalid())
5821 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5822 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5825 // Transform the "then" branch.
5826 StmtResult Then = getDerived().TransformStmt(S->getThen());
5827 if (Then.isInvalid())
5830 // Transform the "else" branch.
5831 StmtResult Else = getDerived().TransformStmt(S->getElse());
5832 if (Else.isInvalid())
5835 if (!getDerived().AlwaysRebuild() &&
5836 FullCond.get() == S->getCond() &&
5837 ConditionVar == S->getConditionVariable() &&
5838 Then.get() == S->getThen() &&
5839 Else.get() == S->getElse())
5842 return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
5844 S->getElseLoc(), Else.get());
5847 template<typename Derived>
5849 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
5850 // Transform the condition.
5852 VarDecl *ConditionVar = nullptr;
5853 if (S->getConditionVariable()) {
5855 = cast_or_null<VarDecl>(
5856 getDerived().TransformDefinition(
5857 S->getConditionVariable()->getLocation(),
5858 S->getConditionVariable()));
5862 Cond = getDerived().TransformExpr(S->getCond());
5864 if (Cond.isInvalid())
5868 // Rebuild the switch statement.
5870 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
5872 if (Switch.isInvalid())
5875 // Transform the body of the switch statement.
5876 StmtResult Body = getDerived().TransformStmt(S->getBody());
5877 if (Body.isInvalid())
5880 // Complete the switch statement.
5881 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
5885 template<typename Derived>
5887 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
5888 // Transform the condition
5890 VarDecl *ConditionVar = nullptr;
5891 if (S->getConditionVariable()) {
5893 = cast_or_null<VarDecl>(
5894 getDerived().TransformDefinition(
5895 S->getConditionVariable()->getLocation(),
5896 S->getConditionVariable()));
5900 Cond = getDerived().TransformExpr(S->getCond());
5902 if (Cond.isInvalid())
5906 // Convert the condition to a boolean value.
5907 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
5910 if (CondE.isInvalid())
5916 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5917 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5920 // Transform the body
5921 StmtResult Body = getDerived().TransformStmt(S->getBody());
5922 if (Body.isInvalid())
5925 if (!getDerived().AlwaysRebuild() &&
5926 FullCond.get() == S->getCond() &&
5927 ConditionVar == S->getConditionVariable() &&
5928 Body.get() == S->getBody())
5931 return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
5932 ConditionVar, Body.get());
5935 template<typename Derived>
5937 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
5938 // Transform the body
5939 StmtResult Body = getDerived().TransformStmt(S->getBody());
5940 if (Body.isInvalid())
5943 // Transform the condition
5944 ExprResult Cond = getDerived().TransformExpr(S->getCond());
5945 if (Cond.isInvalid())
5948 if (!getDerived().AlwaysRebuild() &&
5949 Cond.get() == S->getCond() &&
5950 Body.get() == S->getBody())
5953 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
5954 /*FIXME:*/S->getWhileLoc(), Cond.get(),
5958 template<typename Derived>
5960 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
5961 // Transform the initialization statement
5962 StmtResult Init = getDerived().TransformStmt(S->getInit());
5963 if (Init.isInvalid())
5966 // Transform the condition
5968 VarDecl *ConditionVar = nullptr;
5969 if (S->getConditionVariable()) {
5971 = cast_or_null<VarDecl>(
5972 getDerived().TransformDefinition(
5973 S->getConditionVariable()->getLocation(),
5974 S->getConditionVariable()));
5978 Cond = getDerived().TransformExpr(S->getCond());
5980 if (Cond.isInvalid())
5984 // Convert the condition to a boolean value.
5985 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
5988 if (CondE.isInvalid())
5995 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5996 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5999 // Transform the increment
6000 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6001 if (Inc.isInvalid())
6004 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6005 if (S->getInc() && !FullInc.get())
6008 // Transform the body
6009 StmtResult Body = getDerived().TransformStmt(S->getBody());
6010 if (Body.isInvalid())
6013 if (!getDerived().AlwaysRebuild() &&
6014 Init.get() == S->getInit() &&
6015 FullCond.get() == S->getCond() &&
6016 Inc.get() == S->getInc() &&
6017 Body.get() == S->getBody())
6020 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6021 Init.get(), FullCond, ConditionVar,
6022 FullInc, S->getRParenLoc(), Body.get());
6025 template<typename Derived>
6027 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6028 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6033 // Goto statements must always be rebuilt, to resolve the label.
6034 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6035 cast<LabelDecl>(LD));
6038 template<typename Derived>
6040 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6041 ExprResult Target = getDerived().TransformExpr(S->getTarget());
6042 if (Target.isInvalid())
6044 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6046 if (!getDerived().AlwaysRebuild() &&
6047 Target.get() == S->getTarget())
6050 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6054 template<typename Derived>
6056 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6060 template<typename Derived>
6062 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6066 template<typename Derived>
6068 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
6069 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
6070 /*NotCopyInit*/false);
6071 if (Result.isInvalid())
6074 // FIXME: We always rebuild the return statement because there is no way
6075 // to tell whether the return type of the function has changed.
6076 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
6079 template<typename Derived>
6081 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
6082 bool DeclChanged = false;
6083 SmallVector<Decl *, 4> Decls;
6084 for (auto *D : S->decls()) {
6085 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
6089 if (Transformed != D)
6092 Decls.push_back(Transformed);
6095 if (!getDerived().AlwaysRebuild() && !DeclChanged)
6098 return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
6101 template<typename Derived>
6103 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
6105 SmallVector<Expr*, 8> Constraints;
6106 SmallVector<Expr*, 8> Exprs;
6107 SmallVector<IdentifierInfo *, 4> Names;
6109 ExprResult AsmString;
6110 SmallVector<Expr*, 8> Clobbers;
6112 bool ExprsChanged = false;
6114 // Go through the outputs.
6115 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
6116 Names.push_back(S->getOutputIdentifier(I));
6118 // No need to transform the constraint literal.
6119 Constraints.push_back(S->getOutputConstraintLiteral(I));
6121 // Transform the output expr.
6122 Expr *OutputExpr = S->getOutputExpr(I);
6123 ExprResult Result = getDerived().TransformExpr(OutputExpr);
6124 if (Result.isInvalid())
6127 ExprsChanged |= Result.get() != OutputExpr;
6129 Exprs.push_back(Result.get());
6132 // Go through the inputs.
6133 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
6134 Names.push_back(S->getInputIdentifier(I));
6136 // No need to transform the constraint literal.
6137 Constraints.push_back(S->getInputConstraintLiteral(I));
6139 // Transform the input expr.
6140 Expr *InputExpr = S->getInputExpr(I);
6141 ExprResult Result = getDerived().TransformExpr(InputExpr);
6142 if (Result.isInvalid())
6145 ExprsChanged |= Result.get() != InputExpr;
6147 Exprs.push_back(Result.get());
6150 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
6153 // Go through the clobbers.
6154 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
6155 Clobbers.push_back(S->getClobberStringLiteral(I));
6157 // No need to transform the asm string literal.
6158 AsmString = S->getAsmString();
6159 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
6160 S->isVolatile(), S->getNumOutputs(),
6161 S->getNumInputs(), Names.data(),
6162 Constraints, Exprs, AsmString.get(),
6163 Clobbers, S->getRParenLoc());
6166 template<typename Derived>
6168 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
6169 ArrayRef<Token> AsmToks =
6170 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
6172 bool HadError = false, HadChange = false;
6174 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
6175 SmallVector<Expr*, 8> TransformedExprs;
6176 TransformedExprs.reserve(SrcExprs.size());
6177 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
6178 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
6179 if (!Result.isUsable()) {
6182 HadChange |= (Result.get() != SrcExprs[i]);
6183 TransformedExprs.push_back(Result.get());
6187 if (HadError) return StmtError();
6188 if (!HadChange && !getDerived().AlwaysRebuild())
6191 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
6192 AsmToks, S->getAsmString(),
6193 S->getNumOutputs(), S->getNumInputs(),
6194 S->getAllConstraints(), S->getClobbers(),
6195 TransformedExprs, S->getEndLoc());
6198 template<typename Derived>
6200 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
6201 // Transform the body of the @try.
6202 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
6203 if (TryBody.isInvalid())
6206 // Transform the @catch statements (if present).
6207 bool AnyCatchChanged = false;
6208 SmallVector<Stmt*, 8> CatchStmts;
6209 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
6210 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
6211 if (Catch.isInvalid())
6213 if (Catch.get() != S->getCatchStmt(I))
6214 AnyCatchChanged = true;
6215 CatchStmts.push_back(Catch.get());
6218 // Transform the @finally statement (if present).
6220 if (S->getFinallyStmt()) {
6221 Finally = getDerived().TransformStmt(S->getFinallyStmt());
6222 if (Finally.isInvalid())
6226 // If nothing changed, just retain this statement.
6227 if (!getDerived().AlwaysRebuild() &&
6228 TryBody.get() == S->getTryBody() &&
6230 Finally.get() == S->getFinallyStmt())
6233 // Build a new statement.
6234 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
6235 CatchStmts, Finally.get());
6238 template<typename Derived>
6240 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
6241 // Transform the @catch parameter, if there is one.
6242 VarDecl *Var = nullptr;
6243 if (VarDecl *FromVar = S->getCatchParamDecl()) {
6244 TypeSourceInfo *TSInfo = nullptr;
6245 if (FromVar->getTypeSourceInfo()) {
6246 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
6253 T = TSInfo->getType();
6255 T = getDerived().TransformType(FromVar->getType());
6260 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
6265 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
6266 if (Body.isInvalid())
6269 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
6274 template<typename Derived>
6276 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
6277 // Transform the body.
6278 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
6279 if (Body.isInvalid())
6282 // If nothing changed, just retain this statement.
6283 if (!getDerived().AlwaysRebuild() &&
6284 Body.get() == S->getFinallyBody())
6287 // Build a new statement.
6288 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
6292 template<typename Derived>
6294 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
6296 if (S->getThrowExpr()) {
6297 Operand = getDerived().TransformExpr(S->getThrowExpr());
6298 if (Operand.isInvalid())
6302 if (!getDerived().AlwaysRebuild() &&
6303 Operand.get() == S->getThrowExpr())
6306 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
6309 template<typename Derived>
6311 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
6312 ObjCAtSynchronizedStmt *S) {
6313 // Transform the object we are locking.
6314 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
6315 if (Object.isInvalid())
6318 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
6320 if (Object.isInvalid())
6323 // Transform the body.
6324 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
6325 if (Body.isInvalid())
6328 // If nothing change, just retain the current statement.
6329 if (!getDerived().AlwaysRebuild() &&
6330 Object.get() == S->getSynchExpr() &&
6331 Body.get() == S->getSynchBody())
6334 // Build a new statement.
6335 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
6336 Object.get(), Body.get());
6339 template<typename Derived>
6341 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
6342 ObjCAutoreleasePoolStmt *S) {
6343 // Transform the body.
6344 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
6345 if (Body.isInvalid())
6348 // If nothing changed, just retain this statement.
6349 if (!getDerived().AlwaysRebuild() &&
6350 Body.get() == S->getSubStmt())
6353 // Build a new statement.
6354 return getDerived().RebuildObjCAutoreleasePoolStmt(
6355 S->getAtLoc(), Body.get());
6358 template<typename Derived>
6360 TreeTransform<Derived>::TransformObjCForCollectionStmt(
6361 ObjCForCollectionStmt *S) {
6362 // Transform the element statement.
6363 StmtResult Element = getDerived().TransformStmt(S->getElement());
6364 if (Element.isInvalid())
6367 // Transform the collection expression.
6368 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
6369 if (Collection.isInvalid())
6372 // Transform the body.
6373 StmtResult Body = getDerived().TransformStmt(S->getBody());
6374 if (Body.isInvalid())
6377 // If nothing changed, just retain this statement.
6378 if (!getDerived().AlwaysRebuild() &&
6379 Element.get() == S->getElement() &&
6380 Collection.get() == S->getCollection() &&
6381 Body.get() == S->getBody())
6384 // Build a new statement.
6385 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
6392 template <typename Derived>
6393 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
6394 // Transform the exception declaration, if any.
6395 VarDecl *Var = nullptr;
6396 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
6398 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
6402 Var = getDerived().RebuildExceptionDecl(
6403 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
6404 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
6405 if (!Var || Var->isInvalidDecl())
6409 // Transform the actual exception handler.
6410 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
6411 if (Handler.isInvalid())
6414 if (!getDerived().AlwaysRebuild() && !Var &&
6415 Handler.get() == S->getHandlerBlock())
6418 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
6421 template <typename Derived>
6422 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
6423 // Transform the try block itself.
6424 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6425 if (TryBlock.isInvalid())
6428 // Transform the handlers.
6429 bool HandlerChanged = false;
6430 SmallVector<Stmt *, 8> Handlers;
6431 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
6432 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
6433 if (Handler.isInvalid())
6436 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
6437 Handlers.push_back(Handler.getAs<Stmt>());
6440 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6444 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
6448 template<typename Derived>
6450 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
6451 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
6452 if (Range.isInvalid())
6455 StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
6456 if (BeginEnd.isInvalid())
6459 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6460 if (Cond.isInvalid())
6463 Cond = SemaRef.CheckBooleanCondition(Cond.get(), S->getColonLoc());
6464 if (Cond.isInvalid())
6467 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
6469 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6470 if (Inc.isInvalid())
6473 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
6475 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
6476 if (LoopVar.isInvalid())
6479 StmtResult NewStmt = S;
6480 if (getDerived().AlwaysRebuild() ||
6481 Range.get() != S->getRangeStmt() ||
6482 BeginEnd.get() != S->getBeginEndStmt() ||
6483 Cond.get() != S->getCond() ||
6484 Inc.get() != S->getInc() ||
6485 LoopVar.get() != S->getLoopVarStmt()) {
6486 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6487 S->getColonLoc(), Range.get(),
6488 BeginEnd.get(), Cond.get(),
6489 Inc.get(), LoopVar.get(),
6491 if (NewStmt.isInvalid())
6495 StmtResult Body = getDerived().TransformStmt(S->getBody());
6496 if (Body.isInvalid())
6499 // Body has changed but we didn't rebuild the for-range statement. Rebuild
6500 // it now so we have a new statement to attach the body to.
6501 if (Body.get() != S->getBody() && NewStmt.get() == S) {
6502 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6503 S->getColonLoc(), Range.get(),
6504 BeginEnd.get(), Cond.get(),
6505 Inc.get(), LoopVar.get(),
6507 if (NewStmt.isInvalid())
6511 if (NewStmt.get() == S)
6514 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
6517 template<typename Derived>
6519 TreeTransform<Derived>::TransformMSDependentExistsStmt(
6520 MSDependentExistsStmt *S) {
6521 // Transform the nested-name-specifier, if any.
6522 NestedNameSpecifierLoc QualifierLoc;
6523 if (S->getQualifierLoc()) {
6525 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
6530 // Transform the declaration name.
6531 DeclarationNameInfo NameInfo = S->getNameInfo();
6532 if (NameInfo.getName()) {
6533 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6534 if (!NameInfo.getName())
6538 // Check whether anything changed.
6539 if (!getDerived().AlwaysRebuild() &&
6540 QualifierLoc == S->getQualifierLoc() &&
6541 NameInfo.getName() == S->getNameInfo().getName())
6544 // Determine whether this name exists, if we can.
6546 SS.Adopt(QualifierLoc);
6547 bool Dependent = false;
6548 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
6549 case Sema::IER_Exists:
6550 if (S->isIfExists())
6553 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6555 case Sema::IER_DoesNotExist:
6556 if (S->isIfNotExists())
6559 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6561 case Sema::IER_Dependent:
6565 case Sema::IER_Error:
6569 // We need to continue with the instantiation, so do so now.
6570 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
6571 if (SubStmt.isInvalid())
6574 // If we have resolved the name, just transform to the substatement.
6578 // The name is still dependent, so build a dependent expression again.
6579 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
6586 template<typename Derived>
6588 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
6589 NestedNameSpecifierLoc QualifierLoc;
6590 if (E->getQualifierLoc()) {
6592 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6597 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
6598 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
6602 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
6603 if (Base.isInvalid())
6606 return new (SemaRef.getASTContext())
6607 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
6608 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
6609 QualifierLoc, E->getMemberLoc());
6612 template <typename Derived>
6613 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
6614 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6615 if (TryBlock.isInvalid())
6618 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
6619 if (Handler.isInvalid())
6622 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6623 Handler.get() == S->getHandler())
6626 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
6627 TryBlock.get(), Handler.get());
6630 template <typename Derived>
6631 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
6632 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6633 if (Block.isInvalid())
6636 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
6639 template <typename Derived>
6640 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
6641 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
6642 if (FilterExpr.isInvalid())
6645 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6646 if (Block.isInvalid())
6649 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
6653 template <typename Derived>
6654 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
6655 if (isa<SEHFinallyStmt>(Handler))
6656 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
6658 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
6661 template<typename Derived>
6663 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
6667 //===----------------------------------------------------------------------===//
6668 // OpenMP directive transformation
6669 //===----------------------------------------------------------------------===//
6670 template <typename Derived>
6671 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
6672 OMPExecutableDirective *D) {
6674 // Transform the clauses
6675 llvm::SmallVector<OMPClause *, 16> TClauses;
6676 ArrayRef<OMPClause *> Clauses = D->clauses();
6677 TClauses.reserve(Clauses.size());
6678 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
6681 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
6682 OMPClause *Clause = getDerived().TransformOMPClause(*I);
6683 getDerived().getSema().EndOpenMPClause();
6685 TClauses.push_back(Clause);
6687 TClauses.push_back(nullptr);
6690 StmtResult AssociatedStmt;
6691 if (D->hasAssociatedStmt()) {
6692 if (!D->getAssociatedStmt()) {
6695 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
6696 /*CurScope=*/nullptr);
6699 Sema::CompoundScopeRAII CompoundScope(getSema());
6700 Body = getDerived().TransformStmt(
6701 cast<CapturedStmt>(D->getAssociatedStmt())->getCapturedStmt());
6704 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
6705 if (AssociatedStmt.isInvalid()) {
6709 if (TClauses.size() != Clauses.size()) {
6713 // Transform directive name for 'omp critical' directive.
6714 DeclarationNameInfo DirName;
6715 if (D->getDirectiveKind() == OMPD_critical) {
6716 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
6717 DirName = getDerived().TransformDeclarationNameInfo(DirName);
6719 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
6720 if (D->getDirectiveKind() == OMPD_cancellation_point) {
6721 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
6722 } else if (D->getDirectiveKind() == OMPD_cancel) {
6723 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
6726 return getDerived().RebuildOMPExecutableDirective(
6727 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
6728 AssociatedStmt.get(), D->getLocStart(), D->getLocEnd());
6731 template <typename Derived>
6733 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
6734 DeclarationNameInfo DirName;
6735 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
6737 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6738 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6742 template <typename Derived>
6744 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
6745 DeclarationNameInfo DirName;
6746 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
6748 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6749 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6753 template <typename Derived>
6755 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
6756 DeclarationNameInfo DirName;
6757 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
6759 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6760 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6764 template <typename Derived>
6766 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
6767 DeclarationNameInfo DirName;
6768 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
6770 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6771 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6775 template <typename Derived>
6777 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
6778 DeclarationNameInfo DirName;
6779 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
6781 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6782 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6786 template <typename Derived>
6788 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
6789 DeclarationNameInfo DirName;
6790 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
6792 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6793 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6797 template <typename Derived>
6799 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
6800 DeclarationNameInfo DirName;
6801 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
6803 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6804 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6808 template <typename Derived>
6810 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
6811 DeclarationNameInfo DirName;
6812 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
6814 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6815 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6819 template <typename Derived>
6821 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
6822 getDerived().getSema().StartOpenMPDSABlock(
6823 OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
6824 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6825 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6829 template <typename Derived>
6830 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
6831 OMPParallelForDirective *D) {
6832 DeclarationNameInfo DirName;
6833 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
6834 nullptr, D->getLocStart());
6835 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6836 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6840 template <typename Derived>
6841 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
6842 OMPParallelForSimdDirective *D) {
6843 DeclarationNameInfo DirName;
6844 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
6845 nullptr, D->getLocStart());
6846 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6847 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6851 template <typename Derived>
6852 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
6853 OMPParallelSectionsDirective *D) {
6854 DeclarationNameInfo DirName;
6855 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
6856 nullptr, D->getLocStart());
6857 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6858 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6862 template <typename Derived>
6864 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
6865 DeclarationNameInfo DirName;
6866 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
6868 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6869 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6873 template <typename Derived>
6874 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
6875 OMPTaskyieldDirective *D) {
6876 DeclarationNameInfo DirName;
6877 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
6879 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6880 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6884 template <typename Derived>
6886 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
6887 DeclarationNameInfo DirName;
6888 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
6890 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6891 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6895 template <typename Derived>
6897 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
6898 DeclarationNameInfo DirName;
6899 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
6901 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6902 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6906 template <typename Derived>
6907 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
6908 OMPTaskgroupDirective *D) {
6909 DeclarationNameInfo DirName;
6910 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
6912 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6913 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6917 template <typename Derived>
6919 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
6920 DeclarationNameInfo DirName;
6921 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
6923 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6924 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6928 template <typename Derived>
6930 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
6931 DeclarationNameInfo DirName;
6932 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
6934 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6935 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6939 template <typename Derived>
6941 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
6942 DeclarationNameInfo DirName;
6943 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
6945 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6946 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6950 template <typename Derived>
6952 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
6953 DeclarationNameInfo DirName;
6954 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
6956 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6957 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6961 template <typename Derived>
6963 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
6964 DeclarationNameInfo DirName;
6965 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
6967 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6968 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6972 template <typename Derived>
6973 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
6974 OMPCancellationPointDirective *D) {
6975 DeclarationNameInfo DirName;
6976 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
6977 nullptr, D->getLocStart());
6978 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6979 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6983 template <typename Derived>
6985 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
6986 DeclarationNameInfo DirName;
6987 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
6989 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6990 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6994 //===----------------------------------------------------------------------===//
6995 // OpenMP clause transformation
6996 //===----------------------------------------------------------------------===//
6997 template <typename Derived>
6998 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
6999 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
7000 if (Cond.isInvalid())
7002 return getDerived().RebuildOMPIfClause(Cond.get(), C->getLocStart(),
7003 C->getLParenLoc(), C->getLocEnd());
7006 template <typename Derived>
7007 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
7008 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
7009 if (Cond.isInvalid())
7011 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
7012 C->getLParenLoc(), C->getLocEnd());
7015 template <typename Derived>
7017 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
7018 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
7019 if (NumThreads.isInvalid())
7021 return getDerived().RebuildOMPNumThreadsClause(
7022 NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7025 template <typename Derived>
7027 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
7028 ExprResult E = getDerived().TransformExpr(C->getSafelen());
7031 return getDerived().RebuildOMPSafelenClause(
7032 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7035 template <typename Derived>
7037 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
7038 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
7041 return getDerived().RebuildOMPCollapseClause(
7042 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7045 template <typename Derived>
7047 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
7048 return getDerived().RebuildOMPDefaultClause(
7049 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
7050 C->getLParenLoc(), C->getLocEnd());
7053 template <typename Derived>
7055 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
7056 return getDerived().RebuildOMPProcBindClause(
7057 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
7058 C->getLParenLoc(), C->getLocEnd());
7061 template <typename Derived>
7063 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
7064 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
7067 return getDerived().RebuildOMPScheduleClause(
7068 C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
7069 C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
7072 template <typename Derived>
7074 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
7075 // No need to rebuild this clause, no template-dependent parameters.
7079 template <typename Derived>
7081 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
7082 // No need to rebuild this clause, no template-dependent parameters.
7086 template <typename Derived>
7088 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
7089 // No need to rebuild this clause, no template-dependent parameters.
7093 template <typename Derived>
7095 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
7096 // No need to rebuild this clause, no template-dependent parameters.
7100 template <typename Derived>
7101 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
7102 // No need to rebuild this clause, no template-dependent parameters.
7106 template <typename Derived>
7107 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
7108 // No need to rebuild this clause, no template-dependent parameters.
7112 template <typename Derived>
7114 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
7115 // No need to rebuild this clause, no template-dependent parameters.
7119 template <typename Derived>
7121 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
7122 // No need to rebuild this clause, no template-dependent parameters.
7126 template <typename Derived>
7128 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
7129 // No need to rebuild this clause, no template-dependent parameters.
7133 template <typename Derived>
7135 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
7136 llvm::SmallVector<Expr *, 16> Vars;
7137 Vars.reserve(C->varlist_size());
7138 for (auto *VE : C->varlists()) {
7139 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7140 if (EVar.isInvalid())
7142 Vars.push_back(EVar.get());
7144 return getDerived().RebuildOMPPrivateClause(
7145 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7148 template <typename Derived>
7149 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
7150 OMPFirstprivateClause *C) {
7151 llvm::SmallVector<Expr *, 16> Vars;
7152 Vars.reserve(C->varlist_size());
7153 for (auto *VE : C->varlists()) {
7154 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7155 if (EVar.isInvalid())
7157 Vars.push_back(EVar.get());
7159 return getDerived().RebuildOMPFirstprivateClause(
7160 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7163 template <typename Derived>
7165 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
7166 llvm::SmallVector<Expr *, 16> Vars;
7167 Vars.reserve(C->varlist_size());
7168 for (auto *VE : C->varlists()) {
7169 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7170 if (EVar.isInvalid())
7172 Vars.push_back(EVar.get());
7174 return getDerived().RebuildOMPLastprivateClause(
7175 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7178 template <typename Derived>
7180 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
7181 llvm::SmallVector<Expr *, 16> Vars;
7182 Vars.reserve(C->varlist_size());
7183 for (auto *VE : C->varlists()) {
7184 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7185 if (EVar.isInvalid())
7187 Vars.push_back(EVar.get());
7189 return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
7190 C->getLParenLoc(), C->getLocEnd());
7193 template <typename Derived>
7195 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
7196 llvm::SmallVector<Expr *, 16> Vars;
7197 Vars.reserve(C->varlist_size());
7198 for (auto *VE : C->varlists()) {
7199 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7200 if (EVar.isInvalid())
7202 Vars.push_back(EVar.get());
7204 CXXScopeSpec ReductionIdScopeSpec;
7205 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
7207 DeclarationNameInfo NameInfo = C->getNameInfo();
7208 if (NameInfo.getName()) {
7209 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7210 if (!NameInfo.getName())
7213 return getDerived().RebuildOMPReductionClause(
7214 Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
7215 C->getLocEnd(), ReductionIdScopeSpec, NameInfo);
7218 template <typename Derived>
7220 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
7221 llvm::SmallVector<Expr *, 16> Vars;
7222 Vars.reserve(C->varlist_size());
7223 for (auto *VE : C->varlists()) {
7224 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7225 if (EVar.isInvalid())
7227 Vars.push_back(EVar.get());
7229 ExprResult Step = getDerived().TransformExpr(C->getStep());
7230 if (Step.isInvalid())
7232 return getDerived().RebuildOMPLinearClause(Vars, Step.get(), C->getLocStart(),
7234 C->getColonLoc(), C->getLocEnd());
7237 template <typename Derived>
7239 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
7240 llvm::SmallVector<Expr *, 16> Vars;
7241 Vars.reserve(C->varlist_size());
7242 for (auto *VE : C->varlists()) {
7243 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7244 if (EVar.isInvalid())
7246 Vars.push_back(EVar.get());
7248 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
7249 if (Alignment.isInvalid())
7251 return getDerived().RebuildOMPAlignedClause(
7252 Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
7253 C->getColonLoc(), C->getLocEnd());
7256 template <typename Derived>
7258 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
7259 llvm::SmallVector<Expr *, 16> Vars;
7260 Vars.reserve(C->varlist_size());
7261 for (auto *VE : C->varlists()) {
7262 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7263 if (EVar.isInvalid())
7265 Vars.push_back(EVar.get());
7267 return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
7268 C->getLParenLoc(), C->getLocEnd());
7271 template <typename Derived>
7273 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
7274 llvm::SmallVector<Expr *, 16> Vars;
7275 Vars.reserve(C->varlist_size());
7276 for (auto *VE : C->varlists()) {
7277 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7278 if (EVar.isInvalid())
7280 Vars.push_back(EVar.get());
7282 return getDerived().RebuildOMPCopyprivateClause(
7283 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7286 template <typename Derived>
7287 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
7288 llvm::SmallVector<Expr *, 16> Vars;
7289 Vars.reserve(C->varlist_size());
7290 for (auto *VE : C->varlists()) {
7291 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7292 if (EVar.isInvalid())
7294 Vars.push_back(EVar.get());
7296 return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
7297 C->getLParenLoc(), C->getLocEnd());
7300 template <typename Derived>
7302 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
7303 llvm::SmallVector<Expr *, 16> Vars;
7304 Vars.reserve(C->varlist_size());
7305 for (auto *VE : C->varlists()) {
7306 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7307 if (EVar.isInvalid())
7309 Vars.push_back(EVar.get());
7311 return getDerived().RebuildOMPDependClause(
7312 C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
7313 C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7316 //===----------------------------------------------------------------------===//
7317 // Expression transformation
7318 //===----------------------------------------------------------------------===//
7319 template<typename Derived>
7321 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
7322 if (!E->isTypeDependent())
7325 return getDerived().RebuildPredefinedExpr(E->getLocation(),
7329 template<typename Derived>
7331 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
7332 NestedNameSpecifierLoc QualifierLoc;
7333 if (E->getQualifierLoc()) {
7335 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7341 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
7346 DeclarationNameInfo NameInfo = E->getNameInfo();
7347 if (NameInfo.getName()) {
7348 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7349 if (!NameInfo.getName())
7353 if (!getDerived().AlwaysRebuild() &&
7354 QualifierLoc == E->getQualifierLoc() &&
7355 ND == E->getDecl() &&
7356 NameInfo.getName() == E->getDecl()->getDeclName() &&
7357 !E->hasExplicitTemplateArgs()) {
7359 // Mark it referenced in the new context regardless.
7360 // FIXME: this is a bit instantiation-specific.
7361 SemaRef.MarkDeclRefReferenced(E);
7366 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
7367 if (E->hasExplicitTemplateArgs()) {
7368 TemplateArgs = &TransArgs;
7369 TransArgs.setLAngleLoc(E->getLAngleLoc());
7370 TransArgs.setRAngleLoc(E->getRAngleLoc());
7371 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7372 E->getNumTemplateArgs(),
7377 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
7381 template<typename Derived>
7383 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
7387 template<typename Derived>
7389 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
7393 template<typename Derived>
7395 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
7399 template<typename Derived>
7401 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
7405 template<typename Derived>
7407 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
7411 template<typename Derived>
7413 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
7414 if (FunctionDecl *FD = E->getDirectCallee())
7415 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
7416 return SemaRef.MaybeBindToTemporary(E);
7419 template<typename Derived>
7421 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
7422 ExprResult ControllingExpr =
7423 getDerived().TransformExpr(E->getControllingExpr());
7424 if (ControllingExpr.isInvalid())
7427 SmallVector<Expr *, 4> AssocExprs;
7428 SmallVector<TypeSourceInfo *, 4> AssocTypes;
7429 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
7430 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
7432 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
7435 AssocTypes.push_back(AssocType);
7437 AssocTypes.push_back(nullptr);
7440 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
7441 if (AssocExpr.isInvalid())
7443 AssocExprs.push_back(AssocExpr.get());
7446 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
7449 ControllingExpr.get(),
7454 template<typename Derived>
7456 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
7457 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
7458 if (SubExpr.isInvalid())
7461 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7464 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
7468 /// \brief The operand of a unary address-of operator has special rules: it's
7469 /// allowed to refer to a non-static member of a class even if there's no 'this'
7470 /// object available.
7471 template<typename Derived>
7473 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
7474 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
7475 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
7477 return getDerived().TransformExpr(E);
7480 template<typename Derived>
7482 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
7484 if (E->getOpcode() == UO_AddrOf)
7485 SubExpr = TransformAddressOfOperand(E->getSubExpr());
7487 SubExpr = TransformExpr(E->getSubExpr());
7488 if (SubExpr.isInvalid())
7491 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7494 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
7499 template<typename Derived>
7501 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
7502 // Transform the type.
7503 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
7507 // Transform all of the components into components similar to what the
7509 // FIXME: It would be slightly more efficient in the non-dependent case to
7510 // just map FieldDecls, rather than requiring the rebuilder to look for
7511 // the fields again. However, __builtin_offsetof is rare enough in
7512 // template code that we don't care.
7513 bool ExprChanged = false;
7514 typedef Sema::OffsetOfComponent Component;
7515 typedef OffsetOfExpr::OffsetOfNode Node;
7516 SmallVector<Component, 4> Components;
7517 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
7518 const Node &ON = E->getComponent(I);
7520 Comp.isBrackets = true;
7521 Comp.LocStart = ON.getSourceRange().getBegin();
7522 Comp.LocEnd = ON.getSourceRange().getEnd();
7523 switch (ON.getKind()) {
7525 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
7526 ExprResult Index = getDerived().TransformExpr(FromIndex);
7527 if (Index.isInvalid())
7530 ExprChanged = ExprChanged || Index.get() != FromIndex;
7531 Comp.isBrackets = true;
7532 Comp.U.E = Index.get();
7537 case Node::Identifier:
7538 Comp.isBrackets = false;
7539 Comp.U.IdentInfo = ON.getFieldName();
7540 if (!Comp.U.IdentInfo)
7546 // Will be recomputed during the rebuild.
7550 Components.push_back(Comp);
7553 // If nothing changed, retain the existing expression.
7554 if (!getDerived().AlwaysRebuild() &&
7555 Type == E->getTypeSourceInfo() &&
7559 // Build a new offsetof expression.
7560 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
7561 Components.data(), Components.size(),
7565 template<typename Derived>
7567 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
7568 assert(getDerived().AlreadyTransformed(E->getType()) &&
7569 "opaque value expression requires transformation");
7573 template<typename Derived>
7575 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
7579 template<typename Derived>
7581 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
7582 // Rebuild the syntactic form. The original syntactic form has
7583 // opaque-value expressions in it, so strip those away and rebuild
7584 // the result. This is a really awful way of doing this, but the
7585 // better solution (rebuilding the semantic expressions and
7586 // rebinding OVEs as necessary) doesn't work; we'd need
7587 // TreeTransform to not strip away implicit conversions.
7588 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
7589 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
7590 if (result.isInvalid()) return ExprError();
7592 // If that gives us a pseudo-object result back, the pseudo-object
7593 // expression must have been an lvalue-to-rvalue conversion which we
7595 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
7596 result = SemaRef.checkPseudoObjectRValue(result.get());
7601 template<typename Derived>
7603 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
7604 UnaryExprOrTypeTraitExpr *E) {
7605 if (E->isArgumentType()) {
7606 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
7608 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
7612 if (!getDerived().AlwaysRebuild() && OldT == NewT)
7615 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
7617 E->getSourceRange());
7620 // C++0x [expr.sizeof]p1:
7621 // The operand is either an expression, which is an unevaluated operand
7623 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
7624 Sema::ReuseLambdaContextDecl);
7626 // Try to recover if we have something like sizeof(T::X) where X is a type.
7627 // Notably, there must be *exactly* one set of parens if X is a type.
7628 TypeSourceInfo *RecoveryTSI = nullptr;
7630 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
7632 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
7633 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
7634 PE, DRE, false, &RecoveryTSI);
7636 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
7639 return getDerived().RebuildUnaryExprOrTypeTrait(
7640 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
7641 } else if (SubExpr.isInvalid())
7644 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
7647 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
7648 E->getOperatorLoc(),
7650 E->getSourceRange());
7653 template<typename Derived>
7655 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
7656 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7657 if (LHS.isInvalid())
7660 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7661 if (RHS.isInvalid())
7665 if (!getDerived().AlwaysRebuild() &&
7666 LHS.get() == E->getLHS() &&
7667 RHS.get() == E->getRHS())
7670 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
7671 /*FIXME:*/E->getLHS()->getLocStart(),
7673 E->getRBracketLoc());
7676 template<typename Derived>
7678 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
7679 // Transform the callee.
7680 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7681 if (Callee.isInvalid())
7684 // Transform arguments.
7685 bool ArgChanged = false;
7686 SmallVector<Expr*, 8> Args;
7687 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7691 if (!getDerived().AlwaysRebuild() &&
7692 Callee.get() == E->getCallee() &&
7694 return SemaRef.MaybeBindToTemporary(E);
7696 // FIXME: Wrong source location information for the '('.
7697 SourceLocation FakeLParenLoc
7698 = ((Expr *)Callee.get())->getSourceRange().getBegin();
7699 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
7704 template<typename Derived>
7706 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
7707 ExprResult Base = getDerived().TransformExpr(E->getBase());
7708 if (Base.isInvalid())
7711 NestedNameSpecifierLoc QualifierLoc;
7712 if (E->hasQualifier()) {
7714 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7719 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
7722 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
7723 E->getMemberDecl()));
7727 NamedDecl *FoundDecl = E->getFoundDecl();
7728 if (FoundDecl == E->getMemberDecl()) {
7731 FoundDecl = cast_or_null<NamedDecl>(
7732 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
7737 if (!getDerived().AlwaysRebuild() &&
7738 Base.get() == E->getBase() &&
7739 QualifierLoc == E->getQualifierLoc() &&
7740 Member == E->getMemberDecl() &&
7741 FoundDecl == E->getFoundDecl() &&
7742 !E->hasExplicitTemplateArgs()) {
7744 // Mark it referenced in the new context regardless.
7745 // FIXME: this is a bit instantiation-specific.
7746 SemaRef.MarkMemberReferenced(E);
7751 TemplateArgumentListInfo TransArgs;
7752 if (E->hasExplicitTemplateArgs()) {
7753 TransArgs.setLAngleLoc(E->getLAngleLoc());
7754 TransArgs.setRAngleLoc(E->getRAngleLoc());
7755 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7756 E->getNumTemplateArgs(),
7761 // FIXME: Bogus source location for the operator
7762 SourceLocation FakeOperatorLoc =
7763 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
7765 // FIXME: to do this check properly, we will need to preserve the
7766 // first-qualifier-in-scope here, just in case we had a dependent
7767 // base (and therefore couldn't do the check) and a
7768 // nested-name-qualifier (and therefore could do the lookup).
7769 NamedDecl *FirstQualifierInScope = nullptr;
7771 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
7775 E->getMemberNameInfo(),
7778 (E->hasExplicitTemplateArgs()
7779 ? &TransArgs : nullptr),
7780 FirstQualifierInScope);
7783 template<typename Derived>
7785 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
7786 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7787 if (LHS.isInvalid())
7790 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7791 if (RHS.isInvalid())
7794 if (!getDerived().AlwaysRebuild() &&
7795 LHS.get() == E->getLHS() &&
7796 RHS.get() == E->getRHS())
7799 Sema::FPContractStateRAII FPContractState(getSema());
7800 getSema().FPFeatures.fp_contract = E->isFPContractable();
7802 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
7803 LHS.get(), RHS.get());
7806 template<typename Derived>
7808 TreeTransform<Derived>::TransformCompoundAssignOperator(
7809 CompoundAssignOperator *E) {
7810 return getDerived().TransformBinaryOperator(E);
7813 template<typename Derived>
7814 ExprResult TreeTransform<Derived>::
7815 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
7816 // Just rebuild the common and RHS expressions and see whether we
7819 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
7820 if (commonExpr.isInvalid())
7823 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
7824 if (rhs.isInvalid())
7827 if (!getDerived().AlwaysRebuild() &&
7828 commonExpr.get() == e->getCommon() &&
7829 rhs.get() == e->getFalseExpr())
7832 return getDerived().RebuildConditionalOperator(commonExpr.get(),
7833 e->getQuestionLoc(),
7839 template<typename Derived>
7841 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
7842 ExprResult Cond = getDerived().TransformExpr(E->getCond());
7843 if (Cond.isInvalid())
7846 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7847 if (LHS.isInvalid())
7850 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7851 if (RHS.isInvalid())
7854 if (!getDerived().AlwaysRebuild() &&
7855 Cond.get() == E->getCond() &&
7856 LHS.get() == E->getLHS() &&
7857 RHS.get() == E->getRHS())
7860 return getDerived().RebuildConditionalOperator(Cond.get(),
7861 E->getQuestionLoc(),
7867 template<typename Derived>
7869 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
7870 // Implicit casts are eliminated during transformation, since they
7871 // will be recomputed by semantic analysis after transformation.
7872 return getDerived().TransformExpr(E->getSubExprAsWritten());
7875 template<typename Derived>
7877 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
7878 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
7883 = getDerived().TransformExpr(E->getSubExprAsWritten());
7884 if (SubExpr.isInvalid())
7887 if (!getDerived().AlwaysRebuild() &&
7888 Type == E->getTypeInfoAsWritten() &&
7889 SubExpr.get() == E->getSubExpr())
7892 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
7898 template<typename Derived>
7900 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
7901 TypeSourceInfo *OldT = E->getTypeSourceInfo();
7902 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
7906 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
7907 if (Init.isInvalid())
7910 if (!getDerived().AlwaysRebuild() &&
7912 Init.get() == E->getInitializer())
7913 return SemaRef.MaybeBindToTemporary(E);
7915 // Note: the expression type doesn't necessarily match the
7916 // type-as-written, but that's okay, because it should always be
7917 // derivable from the initializer.
7919 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
7920 /*FIXME:*/E->getInitializer()->getLocEnd(),
7924 template<typename Derived>
7926 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
7927 ExprResult Base = getDerived().TransformExpr(E->getBase());
7928 if (Base.isInvalid())
7931 if (!getDerived().AlwaysRebuild() &&
7932 Base.get() == E->getBase())
7935 // FIXME: Bad source location
7936 SourceLocation FakeOperatorLoc =
7937 SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
7938 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
7939 E->getAccessorLoc(),
7943 template<typename Derived>
7945 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
7946 if (InitListExpr *Syntactic = E->getSyntacticForm())
7949 bool InitChanged = false;
7951 SmallVector<Expr*, 4> Inits;
7952 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
7953 Inits, &InitChanged))
7956 if (!getDerived().AlwaysRebuild() && !InitChanged) {
7957 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
7958 // in some cases. We can't reuse it in general, because the syntactic and
7959 // semantic forms are linked, and we can't know that semantic form will
7960 // match even if the syntactic form does.
7963 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
7964 E->getRBraceLoc(), E->getType());
7967 template<typename Derived>
7969 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
7972 // transform the initializer value
7973 ExprResult Init = getDerived().TransformExpr(E->getInit());
7974 if (Init.isInvalid())
7977 // transform the designators.
7978 SmallVector<Expr*, 4> ArrayExprs;
7979 bool ExprChanged = false;
7980 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
7981 DEnd = E->designators_end();
7983 if (D->isFieldDesignator()) {
7984 Desig.AddDesignator(Designator::getField(D->getFieldName(),
7990 if (D->isArrayDesignator()) {
7991 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
7992 if (Index.isInvalid())
7995 Desig.AddDesignator(Designator::getArray(Index.get(),
7996 D->getLBracketLoc()));
7998 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
7999 ArrayExprs.push_back(Index.get());
8003 assert(D->isArrayRangeDesignator() && "New kind of designator?");
8005 = getDerived().TransformExpr(E->getArrayRangeStart(*D));
8006 if (Start.isInvalid())
8009 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
8010 if (End.isInvalid())
8013 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
8015 D->getLBracketLoc(),
8016 D->getEllipsisLoc()));
8018 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
8019 End.get() != E->getArrayRangeEnd(*D);
8021 ArrayExprs.push_back(Start.get());
8022 ArrayExprs.push_back(End.get());
8025 if (!getDerived().AlwaysRebuild() &&
8026 Init.get() == E->getInit() &&
8030 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
8031 E->getEqualOrColonLoc(),
8032 E->usesGNUSyntax(), Init.get());
8035 // Seems that if TransformInitListExpr() only works on the syntactic form of an
8036 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
8037 template<typename Derived>
8039 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
8040 DesignatedInitUpdateExpr *E) {
8041 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
8046 template<typename Derived>
8048 TreeTransform<Derived>::TransformNoInitExpr(
8050 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
8054 template<typename Derived>
8056 TreeTransform<Derived>::TransformImplicitValueInitExpr(
8057 ImplicitValueInitExpr *E) {
8058 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
8060 // FIXME: Will we ever have proper type location here? Will we actually
8061 // need to transform the type?
8062 QualType T = getDerived().TransformType(E->getType());
8066 if (!getDerived().AlwaysRebuild() &&
8070 return getDerived().RebuildImplicitValueInitExpr(T);
8073 template<typename Derived>
8075 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
8076 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
8080 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8081 if (SubExpr.isInvalid())
8084 if (!getDerived().AlwaysRebuild() &&
8085 TInfo == E->getWrittenTypeInfo() &&
8086 SubExpr.get() == E->getSubExpr())
8089 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
8090 TInfo, E->getRParenLoc());
8093 template<typename Derived>
8095 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
8096 bool ArgumentChanged = false;
8097 SmallVector<Expr*, 4> Inits;
8098 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
8102 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
8107 /// \brief Transform an address-of-label expression.
8109 /// By default, the transformation of an address-of-label expression always
8110 /// rebuilds the expression, so that the label identifier can be resolved to
8111 /// the corresponding label statement by semantic analysis.
8112 template<typename Derived>
8114 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
8115 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
8120 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
8121 cast<LabelDecl>(LD));
8124 template<typename Derived>
8126 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
8127 SemaRef.ActOnStartStmtExpr();
8129 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
8130 if (SubStmt.isInvalid()) {
8131 SemaRef.ActOnStmtExprError();
8135 if (!getDerived().AlwaysRebuild() &&
8136 SubStmt.get() == E->getSubStmt()) {
8137 // Calling this an 'error' is unintuitive, but it does the right thing.
8138 SemaRef.ActOnStmtExprError();
8139 return SemaRef.MaybeBindToTemporary(E);
8142 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
8147 template<typename Derived>
8149 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
8150 ExprResult Cond = getDerived().TransformExpr(E->getCond());
8151 if (Cond.isInvalid())
8154 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8155 if (LHS.isInvalid())
8158 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
8159 if (RHS.isInvalid())
8162 if (!getDerived().AlwaysRebuild() &&
8163 Cond.get() == E->getCond() &&
8164 LHS.get() == E->getLHS() &&
8165 RHS.get() == E->getRHS())
8168 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
8169 Cond.get(), LHS.get(), RHS.get(),
8173 template<typename Derived>
8175 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
8179 template<typename Derived>
8181 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8182 switch (E->getOperator()) {
8186 case OO_Array_Delete:
8187 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
8190 // This is a call to an object's operator().
8191 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
8193 // Transform the object itself.
8194 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
8195 if (Object.isInvalid())
8198 // FIXME: Poor location information
8199 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
8200 static_cast<Expr *>(Object.get())->getLocEnd());
8202 // Transform the call arguments.
8203 SmallVector<Expr*, 8> Args;
8204 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
8208 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
8213 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8215 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
8216 #include "clang/Basic/OperatorKinds.def"
8221 case OO_Conditional:
8222 llvm_unreachable("conditional operator is not actually overloadable");
8225 case NUM_OVERLOADED_OPERATORS:
8226 llvm_unreachable("not an overloaded operator?");
8229 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8230 if (Callee.isInvalid())
8234 if (E->getOperator() == OO_Amp)
8235 First = getDerived().TransformAddressOfOperand(E->getArg(0));
8237 First = getDerived().TransformExpr(E->getArg(0));
8238 if (First.isInvalid())
8242 if (E->getNumArgs() == 2) {
8243 Second = getDerived().TransformExpr(E->getArg(1));
8244 if (Second.isInvalid())
8248 if (!getDerived().AlwaysRebuild() &&
8249 Callee.get() == E->getCallee() &&
8250 First.get() == E->getArg(0) &&
8251 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
8252 return SemaRef.MaybeBindToTemporary(E);
8254 Sema::FPContractStateRAII FPContractState(getSema());
8255 getSema().FPFeatures.fp_contract = E->isFPContractable();
8257 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
8258 E->getOperatorLoc(),
8264 template<typename Derived>
8266 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
8267 return getDerived().TransformCallExpr(E);
8270 template<typename Derived>
8272 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
8273 // Transform the callee.
8274 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8275 if (Callee.isInvalid())
8278 // Transform exec config.
8279 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
8283 // Transform arguments.
8284 bool ArgChanged = false;
8285 SmallVector<Expr*, 8> Args;
8286 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
8290 if (!getDerived().AlwaysRebuild() &&
8291 Callee.get() == E->getCallee() &&
8293 return SemaRef.MaybeBindToTemporary(E);
8295 // FIXME: Wrong source location information for the '('.
8296 SourceLocation FakeLParenLoc
8297 = ((Expr *)Callee.get())->getSourceRange().getBegin();
8298 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
8300 E->getRParenLoc(), EC.get());
8303 template<typename Derived>
8305 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
8306 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8311 = getDerived().TransformExpr(E->getSubExprAsWritten());
8312 if (SubExpr.isInvalid())
8315 if (!getDerived().AlwaysRebuild() &&
8316 Type == E->getTypeInfoAsWritten() &&
8317 SubExpr.get() == E->getSubExpr())
8319 return getDerived().RebuildCXXNamedCastExpr(
8320 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
8321 Type, E->getAngleBrackets().getEnd(),
8322 // FIXME. this should be '(' location
8323 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
8326 template<typename Derived>
8328 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
8329 return getDerived().TransformCXXNamedCastExpr(E);
8332 template<typename Derived>
8334 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
8335 return getDerived().TransformCXXNamedCastExpr(E);
8338 template<typename Derived>
8340 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
8341 CXXReinterpretCastExpr *E) {
8342 return getDerived().TransformCXXNamedCastExpr(E);
8345 template<typename Derived>
8347 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
8348 return getDerived().TransformCXXNamedCastExpr(E);
8351 template<typename Derived>
8353 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
8354 CXXFunctionalCastExpr *E) {
8355 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8360 = getDerived().TransformExpr(E->getSubExprAsWritten());
8361 if (SubExpr.isInvalid())
8364 if (!getDerived().AlwaysRebuild() &&
8365 Type == E->getTypeInfoAsWritten() &&
8366 SubExpr.get() == E->getSubExpr())
8369 return getDerived().RebuildCXXFunctionalCastExpr(Type,
8375 template<typename Derived>
8377 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
8378 if (E->isTypeOperand()) {
8379 TypeSourceInfo *TInfo
8380 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8384 if (!getDerived().AlwaysRebuild() &&
8385 TInfo == E->getTypeOperandSourceInfo())
8388 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8394 // We don't know whether the subexpression is potentially evaluated until
8395 // after we perform semantic analysis. We speculatively assume it is
8396 // unevaluated; it will get fixed later if the subexpression is in fact
8397 // potentially evaluated.
8398 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
8399 Sema::ReuseLambdaContextDecl);
8401 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8402 if (SubExpr.isInvalid())
8405 if (!getDerived().AlwaysRebuild() &&
8406 SubExpr.get() == E->getExprOperand())
8409 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8415 template<typename Derived>
8417 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
8418 if (E->isTypeOperand()) {
8419 TypeSourceInfo *TInfo
8420 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8424 if (!getDerived().AlwaysRebuild() &&
8425 TInfo == E->getTypeOperandSourceInfo())
8428 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8434 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8436 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8437 if (SubExpr.isInvalid())
8440 if (!getDerived().AlwaysRebuild() &&
8441 SubExpr.get() == E->getExprOperand())
8444 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8450 template<typename Derived>
8452 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
8456 template<typename Derived>
8458 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
8459 CXXNullPtrLiteralExpr *E) {
8463 template<typename Derived>
8465 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
8466 QualType T = getSema().getCurrentThisType();
8468 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
8469 // Make sure that we capture 'this'.
8470 getSema().CheckCXXThisCapture(E->getLocStart());
8474 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
8477 template<typename Derived>
8479 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
8480 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8481 if (SubExpr.isInvalid())
8484 if (!getDerived().AlwaysRebuild() &&
8485 SubExpr.get() == E->getSubExpr())
8488 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
8489 E->isThrownVariableInScope());
8492 template<typename Derived>
8494 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8496 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
8501 if (!getDerived().AlwaysRebuild() &&
8502 Param == E->getParam())
8505 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
8508 template<typename Derived>
8510 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
8512 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
8517 if (!getDerived().AlwaysRebuild() && Field == E->getField())
8520 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
8523 template<typename Derived>
8525 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
8526 CXXScalarValueInitExpr *E) {
8527 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8531 if (!getDerived().AlwaysRebuild() &&
8532 T == E->getTypeSourceInfo())
8535 return getDerived().RebuildCXXScalarValueInitExpr(T,
8536 /*FIXME:*/T->getTypeLoc().getEndLoc(),
8540 template<typename Derived>
8542 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
8543 // Transform the type that we're allocating
8544 TypeSourceInfo *AllocTypeInfo
8545 = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
8549 // Transform the size of the array we're allocating (if any).
8550 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
8551 if (ArraySize.isInvalid())
8554 // Transform the placement arguments (if any).
8555 bool ArgumentChanged = false;
8556 SmallVector<Expr*, 8> PlacementArgs;
8557 if (getDerived().TransformExprs(E->getPlacementArgs(),
8558 E->getNumPlacementArgs(), true,
8559 PlacementArgs, &ArgumentChanged))
8562 // Transform the initializer (if any).
8563 Expr *OldInit = E->getInitializer();
8566 NewInit = getDerived().TransformInitializer(OldInit, true);
8567 if (NewInit.isInvalid())
8570 // Transform new operator and delete operator.
8571 FunctionDecl *OperatorNew = nullptr;
8572 if (E->getOperatorNew()) {
8573 OperatorNew = cast_or_null<FunctionDecl>(
8574 getDerived().TransformDecl(E->getLocStart(),
8575 E->getOperatorNew()));
8580 FunctionDecl *OperatorDelete = nullptr;
8581 if (E->getOperatorDelete()) {
8582 OperatorDelete = cast_or_null<FunctionDecl>(
8583 getDerived().TransformDecl(E->getLocStart(),
8584 E->getOperatorDelete()));
8585 if (!OperatorDelete)
8589 if (!getDerived().AlwaysRebuild() &&
8590 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
8591 ArraySize.get() == E->getArraySize() &&
8592 NewInit.get() == OldInit &&
8593 OperatorNew == E->getOperatorNew() &&
8594 OperatorDelete == E->getOperatorDelete() &&
8596 // Mark any declarations we need as referenced.
8597 // FIXME: instantiation-specific.
8599 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
8601 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8603 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
8604 QualType ElementType
8605 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
8606 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
8607 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
8608 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
8609 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
8617 QualType AllocType = AllocTypeInfo->getType();
8618 if (!ArraySize.get()) {
8619 // If no array size was specified, but the new expression was
8620 // instantiated with an array type (e.g., "new T" where T is
8621 // instantiated with "int[4]"), extract the outer bound from the
8622 // array type as our array size. We do this with constant and
8623 // dependently-sized array types.
8624 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
8627 } else if (const ConstantArrayType *ConsArrayT
8628 = dyn_cast<ConstantArrayType>(ArrayT)) {
8629 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
8630 SemaRef.Context.getSizeType(),
8631 /*FIXME:*/ E->getLocStart());
8632 AllocType = ConsArrayT->getElementType();
8633 } else if (const DependentSizedArrayType *DepArrayT
8634 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
8635 if (DepArrayT->getSizeExpr()) {
8636 ArraySize = DepArrayT->getSizeExpr();
8637 AllocType = DepArrayT->getElementType();
8642 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
8644 /*FIXME:*/E->getLocStart(),
8646 /*FIXME:*/E->getLocStart(),
8647 E->getTypeIdParens(),
8651 E->getDirectInitRange(),
8655 template<typename Derived>
8657 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
8658 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
8659 if (Operand.isInvalid())
8662 // Transform the delete operator, if known.
8663 FunctionDecl *OperatorDelete = nullptr;
8664 if (E->getOperatorDelete()) {
8665 OperatorDelete = cast_or_null<FunctionDecl>(
8666 getDerived().TransformDecl(E->getLocStart(),
8667 E->getOperatorDelete()));
8668 if (!OperatorDelete)
8672 if (!getDerived().AlwaysRebuild() &&
8673 Operand.get() == E->getArgument() &&
8674 OperatorDelete == E->getOperatorDelete()) {
8675 // Mark any declarations we need as referenced.
8676 // FIXME: instantiation-specific.
8678 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8680 if (!E->getArgument()->isTypeDependent()) {
8681 QualType Destroyed = SemaRef.Context.getBaseElementType(
8682 E->getDestroyedType());
8683 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
8684 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
8685 SemaRef.MarkFunctionReferenced(E->getLocStart(),
8686 SemaRef.LookupDestructor(Record));
8693 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
8694 E->isGlobalDelete(),
8699 template<typename Derived>
8701 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
8702 CXXPseudoDestructorExpr *E) {
8703 ExprResult Base = getDerived().TransformExpr(E->getBase());
8704 if (Base.isInvalid())
8707 ParsedType ObjectTypePtr;
8708 bool MayBePseudoDestructor = false;
8709 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
8710 E->getOperatorLoc(),
8711 E->isArrow()? tok::arrow : tok::period,
8713 MayBePseudoDestructor);
8714 if (Base.isInvalid())
8717 QualType ObjectType = ObjectTypePtr.get();
8718 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
8721 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
8726 SS.Adopt(QualifierLoc);
8728 PseudoDestructorTypeStorage Destroyed;
8729 if (E->getDestroyedTypeInfo()) {
8730 TypeSourceInfo *DestroyedTypeInfo
8731 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
8732 ObjectType, nullptr, SS);
8733 if (!DestroyedTypeInfo)
8735 Destroyed = DestroyedTypeInfo;
8736 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
8737 // We aren't likely to be able to resolve the identifier down to a type
8738 // now anyway, so just retain the identifier.
8739 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
8740 E->getDestroyedTypeLoc());
8742 // Look for a destructor known with the given name.
8743 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
8744 *E->getDestroyedTypeIdentifier(),
8745 E->getDestroyedTypeLoc(),
8753 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
8754 E->getDestroyedTypeLoc());
8757 TypeSourceInfo *ScopeTypeInfo = nullptr;
8758 if (E->getScopeTypeInfo()) {
8759 CXXScopeSpec EmptySS;
8760 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
8761 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
8766 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
8767 E->getOperatorLoc(),
8771 E->getColonColonLoc(),
8776 template<typename Derived>
8778 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
8779 UnresolvedLookupExpr *Old) {
8780 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
8781 Sema::LookupOrdinaryName);
8783 // Transform all the decls.
8784 for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
8785 E = Old->decls_end(); I != E; ++I) {
8786 NamedDecl *InstD = static_cast<NamedDecl*>(
8787 getDerived().TransformDecl(Old->getNameLoc(),
8790 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
8791 // This can happen because of dependent hiding.
8792 if (isa<UsingShadowDecl>(*I))
8800 // Expand using declarations.
8801 if (isa<UsingDecl>(InstD)) {
8802 UsingDecl *UD = cast<UsingDecl>(InstD);
8803 for (auto *I : UD->shadows())
8811 // Resolve a kind, but don't do any further analysis. If it's
8812 // ambiguous, the callee needs to deal with it.
8815 // Rebuild the nested-name qualifier, if present.
8817 if (Old->getQualifierLoc()) {
8818 NestedNameSpecifierLoc QualifierLoc
8819 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
8823 SS.Adopt(QualifierLoc);
8826 if (Old->getNamingClass()) {
8827 CXXRecordDecl *NamingClass
8828 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
8830 Old->getNamingClass()));
8836 R.setNamingClass(NamingClass);
8839 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
8841 // If we have neither explicit template arguments, nor the template keyword,
8842 // it's a normal declaration name.
8843 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
8844 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
8846 // If we have template arguments, rebuild them, then rebuild the
8847 // templateid expression.
8848 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
8849 if (Old->hasExplicitTemplateArgs() &&
8850 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
8851 Old->getNumTemplateArgs(),
8857 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
8858 Old->requiresADL(), &TransArgs);
8861 template<typename Derived>
8863 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
8864 bool ArgChanged = false;
8865 SmallVector<TypeSourceInfo *, 4> Args;
8866 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
8867 TypeSourceInfo *From = E->getArg(I);
8868 TypeLoc FromTL = From->getTypeLoc();
8869 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
8871 TLB.reserve(FromTL.getFullDataSize());
8872 QualType To = getDerived().TransformType(TLB, FromTL);
8876 if (To == From->getType())
8877 Args.push_back(From);
8879 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8887 // We have a pack expansion. Instantiate it.
8888 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
8889 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
8890 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
8891 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
8893 // Determine whether the set of unexpanded parameter packs can and should
8896 bool RetainExpansion = false;
8897 Optional<unsigned> OrigNumExpansions =
8898 ExpansionTL.getTypePtr()->getNumExpansions();
8899 Optional<unsigned> NumExpansions = OrigNumExpansions;
8900 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
8901 PatternTL.getSourceRange(),
8903 Expand, RetainExpansion,
8908 // The transform has determined that we should perform a simple
8909 // transformation on the pack expansion, producing another pack
8911 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
8914 TLB.reserve(From->getTypeLoc().getFullDataSize());
8916 QualType To = getDerived().TransformType(TLB, PatternTL);
8920 To = getDerived().RebuildPackExpansionType(To,
8921 PatternTL.getSourceRange(),
8922 ExpansionTL.getEllipsisLoc(),
8927 PackExpansionTypeLoc ToExpansionTL
8928 = TLB.push<PackExpansionTypeLoc>(To);
8929 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8930 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8934 // Expand the pack expansion by substituting for each argument in the
8936 for (unsigned I = 0; I != *NumExpansions; ++I) {
8937 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
8939 TLB.reserve(PatternTL.getFullDataSize());
8940 QualType To = getDerived().TransformType(TLB, PatternTL);
8944 if (To->containsUnexpandedParameterPack()) {
8945 To = getDerived().RebuildPackExpansionType(To,
8946 PatternTL.getSourceRange(),
8947 ExpansionTL.getEllipsisLoc(),
8952 PackExpansionTypeLoc ToExpansionTL
8953 = TLB.push<PackExpansionTypeLoc>(To);
8954 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8957 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8960 if (!RetainExpansion)
8963 // If we're supposed to retain a pack expansion, do so by temporarily
8964 // forgetting the partially-substituted parameter pack.
8965 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
8968 TLB.reserve(From->getTypeLoc().getFullDataSize());
8970 QualType To = getDerived().TransformType(TLB, PatternTL);
8974 To = getDerived().RebuildPackExpansionType(To,
8975 PatternTL.getSourceRange(),
8976 ExpansionTL.getEllipsisLoc(),
8981 PackExpansionTypeLoc ToExpansionTL
8982 = TLB.push<PackExpansionTypeLoc>(To);
8983 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8984 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8987 if (!getDerived().AlwaysRebuild() && !ArgChanged)
8990 return getDerived().RebuildTypeTrait(E->getTrait(),
8996 template<typename Derived>
8998 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
8999 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
9003 if (!getDerived().AlwaysRebuild() &&
9004 T == E->getQueriedTypeSourceInfo())
9009 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9010 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
9011 if (SubExpr.isInvalid())
9014 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
9018 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
9025 template<typename Derived>
9027 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
9030 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9031 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
9032 if (SubExpr.isInvalid())
9035 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
9039 return getDerived().RebuildExpressionTrait(
9040 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
9043 template <typename Derived>
9044 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
9045 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
9046 TypeSourceInfo **RecoveryTSI) {
9047 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
9048 DRE, AddrTaken, RecoveryTSI);
9050 // Propagate both errors and recovered types, which return ExprEmpty.
9051 if (!NewDRE.isUsable())
9054 // We got an expr, wrap it up in parens.
9055 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
9057 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
9061 template <typename Derived>
9062 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
9063 DependentScopeDeclRefExpr *E) {
9064 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
9068 template<typename Derived>
9070 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
9071 DependentScopeDeclRefExpr *E,
9072 bool IsAddressOfOperand,
9073 TypeSourceInfo **RecoveryTSI) {
9074 assert(E->getQualifierLoc());
9075 NestedNameSpecifierLoc QualifierLoc
9076 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9079 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9081 // TODO: If this is a conversion-function-id, verify that the
9082 // destination type name (if present) resolves the same way after
9083 // instantiation as it did in the local scope.
9085 DeclarationNameInfo NameInfo
9086 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
9087 if (!NameInfo.getName())
9090 if (!E->hasExplicitTemplateArgs()) {
9091 if (!getDerived().AlwaysRebuild() &&
9092 QualifierLoc == E->getQualifierLoc() &&
9093 // Note: it is sufficient to compare the Name component of NameInfo:
9094 // if name has not changed, DNLoc has not changed either.
9095 NameInfo.getName() == E->getDeclName())
9098 return getDerived().RebuildDependentScopeDeclRefExpr(
9099 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
9100 IsAddressOfOperand, RecoveryTSI);
9103 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
9104 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9105 E->getNumTemplateArgs(),
9109 return getDerived().RebuildDependentScopeDeclRefExpr(
9110 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
9114 template<typename Derived>
9116 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
9117 // CXXConstructExprs other than for list-initialization and
9118 // CXXTemporaryObjectExpr are always implicit, so when we have
9119 // a 1-argument construction we just transform that argument.
9120 if ((E->getNumArgs() == 1 ||
9121 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
9122 (!getDerived().DropCallArgument(E->getArg(0))) &&
9123 !E->isListInitialization())
9124 return getDerived().TransformExpr(E->getArg(0));
9126 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
9128 QualType T = getDerived().TransformType(E->getType());
9132 CXXConstructorDecl *Constructor
9133 = cast_or_null<CXXConstructorDecl>(
9134 getDerived().TransformDecl(E->getLocStart(),
9135 E->getConstructor()));
9139 bool ArgumentChanged = false;
9140 SmallVector<Expr*, 8> Args;
9141 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9145 if (!getDerived().AlwaysRebuild() &&
9146 T == E->getType() &&
9147 Constructor == E->getConstructor() &&
9149 // Mark the constructor as referenced.
9150 // FIXME: Instantiation-specific
9151 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9155 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
9156 Constructor, E->isElidable(),
9158 E->hadMultipleCandidates(),
9159 E->isListInitialization(),
9160 E->isStdInitListInitialization(),
9161 E->requiresZeroInitialization(),
9162 E->getConstructionKind(),
9163 E->getParenOrBraceRange());
9166 /// \brief Transform a C++ temporary-binding expression.
9168 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
9169 /// transform the subexpression and return that.
9170 template<typename Derived>
9172 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9173 return getDerived().TransformExpr(E->getSubExpr());
9176 /// \brief Transform a C++ expression that contains cleanups that should
9177 /// be run after the expression is evaluated.
9179 /// Since ExprWithCleanups nodes are implicitly generated, we
9180 /// just transform the subexpression and return that.
9181 template<typename Derived>
9183 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
9184 return getDerived().TransformExpr(E->getSubExpr());
9187 template<typename Derived>
9189 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
9190 CXXTemporaryObjectExpr *E) {
9191 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9195 CXXConstructorDecl *Constructor
9196 = cast_or_null<CXXConstructorDecl>(
9197 getDerived().TransformDecl(E->getLocStart(),
9198 E->getConstructor()));
9202 bool ArgumentChanged = false;
9203 SmallVector<Expr*, 8> Args;
9204 Args.reserve(E->getNumArgs());
9205 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9209 if (!getDerived().AlwaysRebuild() &&
9210 T == E->getTypeSourceInfo() &&
9211 Constructor == E->getConstructor() &&
9213 // FIXME: Instantiation-specific
9214 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9215 return SemaRef.MaybeBindToTemporary(E);
9218 // FIXME: Pass in E->isListInitialization().
9219 return getDerived().RebuildCXXTemporaryObjectExpr(T,
9220 /*FIXME:*/T->getTypeLoc().getEndLoc(),
9225 template<typename Derived>
9227 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
9228 // Transform any init-capture expressions before entering the scope of the
9229 // lambda body, because they are not semantically within that scope.
9230 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
9231 SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
9232 InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
9233 E->explicit_capture_begin());
9234 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9235 CEnd = E->capture_end();
9237 if (!E->isInitCapture(C))
9239 EnterExpressionEvaluationContext EEEC(getSema(),
9240 Sema::PotentiallyEvaluated);
9241 ExprResult NewExprInitResult = getDerived().TransformInitializer(
9242 C->getCapturedVar()->getInit(),
9243 C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
9245 if (NewExprInitResult.isInvalid())
9247 Expr *NewExprInit = NewExprInitResult.get();
9249 VarDecl *OldVD = C->getCapturedVar();
9250 QualType NewInitCaptureType =
9251 getSema().performLambdaInitCaptureInitialization(C->getLocation(),
9252 OldVD->getType()->isReferenceType(), OldVD->getIdentifier(),
9254 NewExprInitResult = NewExprInit;
9255 InitCaptureExprsAndTypes[C - E->capture_begin()] =
9256 std::make_pair(NewExprInitResult, NewInitCaptureType);
9259 // Transform the template parameters, and add them to the current
9260 // instantiation scope. The null case is handled correctly.
9261 auto TPL = getDerived().TransformTemplateParameterList(
9262 E->getTemplateParameterList());
9264 // Transform the type of the original lambda's call operator.
9265 // The transformation MUST be done in the CurrentInstantiationScope since
9266 // it introduces a mapping of the original to the newly created
9267 // transformed parameters.
9268 TypeSourceInfo *NewCallOpTSI = nullptr;
9270 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
9271 FunctionProtoTypeLoc OldCallOpFPTL =
9272 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
9274 TypeLocBuilder NewCallOpTLBuilder;
9275 SmallVector<QualType, 4> ExceptionStorage;
9276 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
9277 QualType NewCallOpType = TransformFunctionProtoType(
9278 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
9279 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
9280 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
9281 ExceptionStorage, Changed);
9283 if (NewCallOpType.isNull())
9285 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
9289 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
9290 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
9291 LSI->GLTemplateParameterList = TPL;
9293 // Create the local class that will describe the lambda.
9294 CXXRecordDecl *Class
9295 = getSema().createLambdaClosureType(E->getIntroducerRange(),
9297 /*KnownDependent=*/false,
9298 E->getCaptureDefault());
9299 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
9301 // Build the call operator.
9302 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
9303 Class, E->getIntroducerRange(), NewCallOpTSI,
9304 E->getCallOperator()->getLocEnd(),
9305 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams());
9306 LSI->CallOperator = NewCallOperator;
9308 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
9309 getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
9311 // Introduce the context of the call operator.
9312 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
9313 /*NewThisContext*/false);
9315 // Enter the scope of the lambda.
9316 getSema().buildLambdaScope(LSI, NewCallOperator,
9317 E->getIntroducerRange(),
9318 E->getCaptureDefault(),
9319 E->getCaptureDefaultLoc(),
9320 E->hasExplicitParameters(),
9321 E->hasExplicitResultType(),
9324 bool Invalid = false;
9326 // Transform captures.
9327 bool FinishedExplicitCaptures = false;
9328 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9329 CEnd = E->capture_end();
9331 // When we hit the first implicit capture, tell Sema that we've finished
9332 // the list of explicit captures.
9333 if (!FinishedExplicitCaptures && C->isImplicit()) {
9334 getSema().finishLambdaExplicitCaptures(LSI);
9335 FinishedExplicitCaptures = true;
9338 // Capturing 'this' is trivial.
9339 if (C->capturesThis()) {
9340 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
9343 // Captured expression will be recaptured during captured variables
9345 if (C->capturesVLAType())
9348 // Rebuild init-captures, including the implied field declaration.
9349 if (E->isInitCapture(C)) {
9350 InitCaptureInfoTy InitExprTypePair =
9351 InitCaptureExprsAndTypes[C - E->capture_begin()];
9352 ExprResult Init = InitExprTypePair.first;
9353 QualType InitQualType = InitExprTypePair.second;
9354 if (Init.isInvalid() || InitQualType.isNull()) {
9358 VarDecl *OldVD = C->getCapturedVar();
9359 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
9360 OldVD->getLocation(), InitExprTypePair.second,
9361 OldVD->getIdentifier(), Init.get());
9365 getDerived().transformedLocalDecl(OldVD, NewVD);
9367 getSema().buildInitCaptureField(LSI, NewVD);
9371 assert(C->capturesVariable() && "unexpected kind of lambda capture");
9373 // Determine the capture kind for Sema.
9374 Sema::TryCaptureKind Kind
9375 = C->isImplicit()? Sema::TryCapture_Implicit
9376 : C->getCaptureKind() == LCK_ByCopy
9377 ? Sema::TryCapture_ExplicitByVal
9378 : Sema::TryCapture_ExplicitByRef;
9379 SourceLocation EllipsisLoc;
9380 if (C->isPackExpansion()) {
9381 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
9382 bool ShouldExpand = false;
9383 bool RetainExpansion = false;
9384 Optional<unsigned> NumExpansions;
9385 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
9388 ShouldExpand, RetainExpansion,
9395 // The transform has determined that we should perform an expansion;
9396 // transform and capture each of the arguments.
9397 // expansion of the pattern. Do so.
9398 VarDecl *Pack = C->getCapturedVar();
9399 for (unsigned I = 0; I != *NumExpansions; ++I) {
9400 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
9401 VarDecl *CapturedVar
9402 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9409 // Capture the transformed variable.
9410 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
9413 // FIXME: Retain a pack expansion if RetainExpansion is true.
9418 EllipsisLoc = C->getEllipsisLoc();
9421 // Transform the captured variable.
9422 VarDecl *CapturedVar
9423 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9424 C->getCapturedVar()));
9425 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
9430 // Capture the transformed variable.
9431 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
9434 if (!FinishedExplicitCaptures)
9435 getSema().finishLambdaExplicitCaptures(LSI);
9437 // Enter a new evaluation context to insulate the lambda from any
9438 // cleanups from the enclosing full-expression.
9439 getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9441 // Instantiate the body of the lambda expression.
9443 Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
9445 // ActOnLambda* will pop the function scope for us.
9446 FuncScopeCleanup.disable();
9448 if (Body.isInvalid()) {
9450 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
9451 /*IsInstantiation=*/true);
9455 // Copy the LSI before ActOnFinishFunctionBody removes it.
9456 // FIXME: This is dumb. Store the lambda information somewhere that outlives
9457 // the call operator.
9458 auto LSICopy = *LSI;
9459 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
9460 /*IsInstantiation*/ true);
9463 return getSema().BuildLambdaExpr(E->getLocStart(), Body.get()->getLocEnd(),
9467 template<typename Derived>
9469 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
9470 CXXUnresolvedConstructExpr *E) {
9471 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9475 bool ArgumentChanged = false;
9476 SmallVector<Expr*, 8> Args;
9477 Args.reserve(E->arg_size());
9478 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
9482 if (!getDerived().AlwaysRebuild() &&
9483 T == E->getTypeSourceInfo() &&
9487 // FIXME: we're faking the locations of the commas
9488 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
9494 template<typename Derived>
9496 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
9497 CXXDependentScopeMemberExpr *E) {
9498 // Transform the base of the expression.
9499 ExprResult Base((Expr*) nullptr);
9502 QualType ObjectType;
9503 if (!E->isImplicitAccess()) {
9504 OldBase = E->getBase();
9505 Base = getDerived().TransformExpr(OldBase);
9506 if (Base.isInvalid())
9509 // Start the member reference and compute the object's type.
9510 ParsedType ObjectTy;
9511 bool MayBePseudoDestructor = false;
9512 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
9513 E->getOperatorLoc(),
9514 E->isArrow()? tok::arrow : tok::period,
9516 MayBePseudoDestructor);
9517 if (Base.isInvalid())
9520 ObjectType = ObjectTy.get();
9521 BaseType = ((Expr*) Base.get())->getType();
9524 BaseType = getDerived().TransformType(E->getBaseType());
9525 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
9528 // Transform the first part of the nested-name-specifier that qualifies
9530 NamedDecl *FirstQualifierInScope
9531 = getDerived().TransformFirstQualifierInScope(
9532 E->getFirstQualifierFoundInScope(),
9533 E->getQualifierLoc().getBeginLoc());
9535 NestedNameSpecifierLoc QualifierLoc;
9536 if (E->getQualifier()) {
9538 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
9540 FirstQualifierInScope);
9545 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9547 // TODO: If this is a conversion-function-id, verify that the
9548 // destination type name (if present) resolves the same way after
9549 // instantiation as it did in the local scope.
9551 DeclarationNameInfo NameInfo
9552 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
9553 if (!NameInfo.getName())
9556 if (!E->hasExplicitTemplateArgs()) {
9557 // This is a reference to a member without an explicitly-specified
9558 // template argument list. Optimize for this common case.
9559 if (!getDerived().AlwaysRebuild() &&
9560 Base.get() == OldBase &&
9561 BaseType == E->getBaseType() &&
9562 QualifierLoc == E->getQualifierLoc() &&
9563 NameInfo.getName() == E->getMember() &&
9564 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
9567 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9570 E->getOperatorLoc(),
9573 FirstQualifierInScope,
9575 /*TemplateArgs*/nullptr);
9578 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
9579 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9580 E->getNumTemplateArgs(),
9584 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9587 E->getOperatorLoc(),
9590 FirstQualifierInScope,
9595 template<typename Derived>
9597 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
9598 // Transform the base of the expression.
9599 ExprResult Base((Expr*) nullptr);
9601 if (!Old->isImplicitAccess()) {
9602 Base = getDerived().TransformExpr(Old->getBase());
9603 if (Base.isInvalid())
9605 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
9607 if (Base.isInvalid())
9609 BaseType = Base.get()->getType();
9611 BaseType = getDerived().TransformType(Old->getBaseType());
9614 NestedNameSpecifierLoc QualifierLoc;
9615 if (Old->getQualifierLoc()) {
9617 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
9622 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
9624 LookupResult R(SemaRef, Old->getMemberNameInfo(),
9625 Sema::LookupOrdinaryName);
9627 // Transform all the decls.
9628 for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
9629 E = Old->decls_end(); I != E; ++I) {
9630 NamedDecl *InstD = static_cast<NamedDecl*>(
9631 getDerived().TransformDecl(Old->getMemberLoc(),
9634 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
9635 // This can happen because of dependent hiding.
9636 if (isa<UsingShadowDecl>(*I))
9644 // Expand using declarations.
9645 if (isa<UsingDecl>(InstD)) {
9646 UsingDecl *UD = cast<UsingDecl>(InstD);
9647 for (auto *I : UD->shadows())
9657 // Determine the naming class.
9658 if (Old->getNamingClass()) {
9659 CXXRecordDecl *NamingClass
9660 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
9661 Old->getMemberLoc(),
9662 Old->getNamingClass()));
9666 R.setNamingClass(NamingClass);
9669 TemplateArgumentListInfo TransArgs;
9670 if (Old->hasExplicitTemplateArgs()) {
9671 TransArgs.setLAngleLoc(Old->getLAngleLoc());
9672 TransArgs.setRAngleLoc(Old->getRAngleLoc());
9673 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
9674 Old->getNumTemplateArgs(),
9679 // FIXME: to do this check properly, we will need to preserve the
9680 // first-qualifier-in-scope here, just in case we had a dependent
9681 // base (and therefore couldn't do the check) and a
9682 // nested-name-qualifier (and therefore could do the lookup).
9683 NamedDecl *FirstQualifierInScope = nullptr;
9685 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
9687 Old->getOperatorLoc(),
9691 FirstQualifierInScope,
9693 (Old->hasExplicitTemplateArgs()
9694 ? &TransArgs : nullptr));
9697 template<typename Derived>
9699 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
9700 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9701 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
9702 if (SubExpr.isInvalid())
9705 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
9708 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
9711 template<typename Derived>
9713 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
9714 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
9715 if (Pattern.isInvalid())
9718 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
9721 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
9722 E->getNumExpansions());
9725 template<typename Derived>
9727 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
9728 // If E is not value-dependent, then nothing will change when we transform it.
9729 // Note: This is an instantiation-centric view.
9730 if (!E->isValueDependent())
9733 // Note: None of the implementations of TryExpandParameterPacks can ever
9734 // produce a diagnostic when given only a single unexpanded parameter pack,
9736 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
9737 bool ShouldExpand = false;
9738 bool RetainExpansion = false;
9739 Optional<unsigned> NumExpansions;
9740 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
9742 ShouldExpand, RetainExpansion,
9746 if (RetainExpansion)
9749 NamedDecl *Pack = E->getPack();
9750 if (!ShouldExpand) {
9751 Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
9758 // We now know the length of the parameter pack, so build a new expression
9759 // that stores that length.
9760 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
9761 E->getPackLoc(), E->getRParenLoc(),
9765 template<typename Derived>
9767 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
9768 SubstNonTypeTemplateParmPackExpr *E) {
9769 // Default behavior is to do nothing with this transformation.
9773 template<typename Derived>
9775 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
9776 SubstNonTypeTemplateParmExpr *E) {
9777 // Default behavior is to do nothing with this transformation.
9781 template<typename Derived>
9783 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
9784 // Default behavior is to do nothing with this transformation.
9788 template<typename Derived>
9790 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
9791 MaterializeTemporaryExpr *E) {
9792 return getDerived().TransformExpr(E->GetTemporaryExpr());
9795 template<typename Derived>
9797 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
9798 Expr *Pattern = E->getPattern();
9800 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9801 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
9802 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
9804 // Determine whether the set of unexpanded parameter packs can and should
9807 bool RetainExpansion = false;
9808 Optional<unsigned> NumExpansions;
9809 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
9810 Pattern->getSourceRange(),
9812 Expand, RetainExpansion,
9817 // Do not expand any packs here, just transform and rebuild a fold
9819 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
9822 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
9823 if (LHS.isInvalid())
9827 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
9828 if (RHS.isInvalid())
9831 if (!getDerived().AlwaysRebuild() &&
9832 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
9835 return getDerived().RebuildCXXFoldExpr(
9836 E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
9837 RHS.get(), E->getLocEnd());
9840 // The transform has determined that we should perform an elementwise
9841 // expansion of the pattern. Do so.
9842 ExprResult Result = getDerived().TransformExpr(E->getInit());
9843 if (Result.isInvalid())
9845 bool LeftFold = E->isLeftFold();
9847 // If we're retaining an expansion for a right fold, it is the innermost
9848 // component and takes the init (if any).
9849 if (!LeftFold && RetainExpansion) {
9850 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
9852 ExprResult Out = getDerived().TransformExpr(Pattern);
9853 if (Out.isInvalid())
9856 Result = getDerived().RebuildCXXFoldExpr(
9857 E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
9858 Result.get(), E->getLocEnd());
9859 if (Result.isInvalid())
9863 for (unsigned I = 0; I != *NumExpansions; ++I) {
9864 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
9865 getSema(), LeftFold ? I : *NumExpansions - I - 1);
9866 ExprResult Out = getDerived().TransformExpr(Pattern);
9867 if (Out.isInvalid())
9870 if (Out.get()->containsUnexpandedParameterPack()) {
9871 // We still have a pack; retain a pack expansion for this slice.
9872 Result = getDerived().RebuildCXXFoldExpr(
9874 LeftFold ? Result.get() : Out.get(),
9875 E->getOperator(), E->getEllipsisLoc(),
9876 LeftFold ? Out.get() : Result.get(),
9878 } else if (Result.isUsable()) {
9879 // We've got down to a single element; build a binary operator.
9880 Result = getDerived().RebuildBinaryOperator(
9881 E->getEllipsisLoc(), E->getOperator(),
9882 LeftFold ? Result.get() : Out.get(),
9883 LeftFold ? Out.get() : Result.get());
9887 if (Result.isInvalid())
9891 // If we're retaining an expansion for a left fold, it is the outermost
9892 // component and takes the complete expansion so far as its init (if any).
9893 if (LeftFold && RetainExpansion) {
9894 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
9896 ExprResult Out = getDerived().TransformExpr(Pattern);
9897 if (Out.isInvalid())
9900 Result = getDerived().RebuildCXXFoldExpr(
9901 E->getLocStart(), Result.get(),
9902 E->getOperator(), E->getEllipsisLoc(),
9903 Out.get(), E->getLocEnd());
9904 if (Result.isInvalid())
9908 // If we had no init and an empty pack, and we're not retaining an expansion,
9909 // then produce a fallback value or error.
9910 if (Result.isUnset())
9911 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
9917 template<typename Derived>
9919 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
9920 CXXStdInitializerListExpr *E) {
9921 return getDerived().TransformExpr(E->getSubExpr());
9924 template<typename Derived>
9926 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
9927 return SemaRef.MaybeBindToTemporary(E);
9930 template<typename Derived>
9932 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
9936 template<typename Derived>
9938 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
9939 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9940 if (SubExpr.isInvalid())
9943 if (!getDerived().AlwaysRebuild() &&
9944 SubExpr.get() == E->getSubExpr())
9947 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
9950 template<typename Derived>
9952 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
9953 // Transform each of the elements.
9954 SmallVector<Expr *, 8> Elements;
9955 bool ArgChanged = false;
9956 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
9957 /*IsCall=*/false, Elements, &ArgChanged))
9960 if (!getDerived().AlwaysRebuild() && !ArgChanged)
9961 return SemaRef.MaybeBindToTemporary(E);
9963 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
9968 template<typename Derived>
9970 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
9971 ObjCDictionaryLiteral *E) {
9972 // Transform each of the elements.
9973 SmallVector<ObjCDictionaryElement, 8> Elements;
9974 bool ArgChanged = false;
9975 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
9976 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
9978 if (OrigElement.isPackExpansion()) {
9979 // This key/value element is a pack expansion.
9980 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9981 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
9982 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
9983 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
9985 // Determine whether the set of unexpanded parameter packs can
9986 // and should be expanded.
9988 bool RetainExpansion = false;
9989 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
9990 Optional<unsigned> NumExpansions = OrigNumExpansions;
9991 SourceRange PatternRange(OrigElement.Key->getLocStart(),
9992 OrigElement.Value->getLocEnd());
9993 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
9996 Expand, RetainExpansion,
10001 // The transform has determined that we should perform a simple
10002 // transformation on the pack expansion, producing another pack
10004 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10005 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
10006 if (Key.isInvalid())
10007 return ExprError();
10009 if (Key.get() != OrigElement.Key)
10012 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
10013 if (Value.isInvalid())
10014 return ExprError();
10016 if (Value.get() != OrigElement.Value)
10019 ObjCDictionaryElement Expansion = {
10020 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
10022 Elements.push_back(Expansion);
10026 // Record right away that the argument was changed. This needs
10027 // to happen even if the array expands to nothing.
10030 // The transform has determined that we should perform an elementwise
10031 // expansion of the pattern. Do so.
10032 for (unsigned I = 0; I != *NumExpansions; ++I) {
10033 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
10034 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
10035 if (Key.isInvalid())
10036 return ExprError();
10038 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
10039 if (Value.isInvalid())
10040 return ExprError();
10042 ObjCDictionaryElement Element = {
10043 Key.get(), Value.get(), SourceLocation(), NumExpansions
10046 // If any unexpanded parameter packs remain, we still have a
10048 // FIXME: Can this really happen?
10049 if (Key.get()->containsUnexpandedParameterPack() ||
10050 Value.get()->containsUnexpandedParameterPack())
10051 Element.EllipsisLoc = OrigElement.EllipsisLoc;
10053 Elements.push_back(Element);
10056 // FIXME: Retain a pack expansion if RetainExpansion is true.
10058 // We've finished with this pack expansion.
10062 // Transform and check key.
10063 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
10064 if (Key.isInvalid())
10065 return ExprError();
10067 if (Key.get() != OrigElement.Key)
10070 // Transform and check value.
10072 = getDerived().TransformExpr(OrigElement.Value);
10073 if (Value.isInvalid())
10074 return ExprError();
10076 if (Value.get() != OrigElement.Value)
10079 ObjCDictionaryElement Element = {
10080 Key.get(), Value.get(), SourceLocation(), None
10082 Elements.push_back(Element);
10085 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10086 return SemaRef.MaybeBindToTemporary(E);
10088 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
10093 template<typename Derived>
10095 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
10096 TypeSourceInfo *EncodedTypeInfo
10097 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
10098 if (!EncodedTypeInfo)
10099 return ExprError();
10101 if (!getDerived().AlwaysRebuild() &&
10102 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
10105 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
10107 E->getRParenLoc());
10110 template<typename Derived>
10111 ExprResult TreeTransform<Derived>::
10112 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
10113 // This is a kind of implicit conversion, and it needs to get dropped
10114 // and recomputed for the same general reasons that ImplicitCastExprs
10115 // do, as well a more specific one: this expression is only valid when
10116 // it appears *immediately* as an argument expression.
10117 return getDerived().TransformExpr(E->getSubExpr());
10120 template<typename Derived>
10121 ExprResult TreeTransform<Derived>::
10122 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
10123 TypeSourceInfo *TSInfo
10124 = getDerived().TransformType(E->getTypeInfoAsWritten());
10126 return ExprError();
10128 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
10129 if (Result.isInvalid())
10130 return ExprError();
10132 if (!getDerived().AlwaysRebuild() &&
10133 TSInfo == E->getTypeInfoAsWritten() &&
10134 Result.get() == E->getSubExpr())
10137 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
10138 E->getBridgeKeywordLoc(), TSInfo,
10142 template<typename Derived>
10144 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
10145 // Transform arguments.
10146 bool ArgChanged = false;
10147 SmallVector<Expr*, 8> Args;
10148 Args.reserve(E->getNumArgs());
10149 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
10151 return ExprError();
10153 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
10154 // Class message: transform the receiver type.
10155 TypeSourceInfo *ReceiverTypeInfo
10156 = getDerived().TransformType(E->getClassReceiverTypeInfo());
10157 if (!ReceiverTypeInfo)
10158 return ExprError();
10160 // If nothing changed, just retain the existing message send.
10161 if (!getDerived().AlwaysRebuild() &&
10162 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
10163 return SemaRef.MaybeBindToTemporary(E);
10165 // Build a new class message send.
10166 SmallVector<SourceLocation, 16> SelLocs;
10167 E->getSelectorLocs(SelLocs);
10168 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
10171 E->getMethodDecl(),
10176 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
10177 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10178 // Build a new class message send to 'super'.
10179 SmallVector<SourceLocation, 16> SelLocs;
10180 E->getSelectorLocs(SelLocs);
10181 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
10184 E->getMethodDecl(),
10190 // Instance message: transform the receiver
10191 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
10192 "Only class and instance messages may be instantiated");
10193 ExprResult Receiver
10194 = getDerived().TransformExpr(E->getInstanceReceiver());
10195 if (Receiver.isInvalid())
10196 return ExprError();
10198 // If nothing changed, just retain the existing message send.
10199 if (!getDerived().AlwaysRebuild() &&
10200 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
10201 return SemaRef.MaybeBindToTemporary(E);
10203 // Build a new instance message send.
10204 SmallVector<SourceLocation, 16> SelLocs;
10205 E->getSelectorLocs(SelLocs);
10206 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
10209 E->getMethodDecl(),
10215 template<typename Derived>
10217 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
10221 template<typename Derived>
10223 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
10227 template<typename Derived>
10229 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
10230 // Transform the base expression.
10231 ExprResult Base = getDerived().TransformExpr(E->getBase());
10232 if (Base.isInvalid())
10233 return ExprError();
10235 // We don't need to transform the ivar; it will never change.
10237 // If nothing changed, just retain the existing expression.
10238 if (!getDerived().AlwaysRebuild() &&
10239 Base.get() == E->getBase())
10242 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
10244 E->isArrow(), E->isFreeIvar());
10247 template<typename Derived>
10249 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
10250 // 'super' and types never change. Property never changes. Just
10251 // retain the existing expression.
10252 if (!E->isObjectReceiver())
10255 // Transform the base expression.
10256 ExprResult Base = getDerived().TransformExpr(E->getBase());
10257 if (Base.isInvalid())
10258 return ExprError();
10260 // We don't need to transform the property; it will never change.
10262 // If nothing changed, just retain the existing expression.
10263 if (!getDerived().AlwaysRebuild() &&
10264 Base.get() == E->getBase())
10267 if (E->isExplicitProperty())
10268 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10269 E->getExplicitProperty(),
10272 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10273 SemaRef.Context.PseudoObjectTy,
10274 E->getImplicitPropertyGetter(),
10275 E->getImplicitPropertySetter(),
10279 template<typename Derived>
10281 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
10282 // Transform the base expression.
10283 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
10284 if (Base.isInvalid())
10285 return ExprError();
10287 // Transform the key expression.
10288 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
10289 if (Key.isInvalid())
10290 return ExprError();
10292 // If nothing changed, just retain the existing expression.
10293 if (!getDerived().AlwaysRebuild() &&
10294 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
10297 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
10298 Base.get(), Key.get(),
10299 E->getAtIndexMethodDecl(),
10300 E->setAtIndexMethodDecl());
10303 template<typename Derived>
10305 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
10306 // Transform the base expression.
10307 ExprResult Base = getDerived().TransformExpr(E->getBase());
10308 if (Base.isInvalid())
10309 return ExprError();
10311 // If nothing changed, just retain the existing expression.
10312 if (!getDerived().AlwaysRebuild() &&
10313 Base.get() == E->getBase())
10316 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
10321 template<typename Derived>
10323 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
10324 bool ArgumentChanged = false;
10325 SmallVector<Expr*, 8> SubExprs;
10326 SubExprs.reserve(E->getNumSubExprs());
10327 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10328 SubExprs, &ArgumentChanged))
10329 return ExprError();
10331 if (!getDerived().AlwaysRebuild() &&
10335 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
10337 E->getRParenLoc());
10340 template<typename Derived>
10342 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
10343 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
10344 if (SrcExpr.isInvalid())
10345 return ExprError();
10347 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10349 return ExprError();
10351 if (!getDerived().AlwaysRebuild() &&
10352 Type == E->getTypeSourceInfo() &&
10353 SrcExpr.get() == E->getSrcExpr())
10356 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
10357 SrcExpr.get(), Type,
10358 E->getRParenLoc());
10361 template<typename Derived>
10363 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
10364 BlockDecl *oldBlock = E->getBlockDecl();
10366 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
10367 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
10369 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
10370 blockScope->TheDecl->setBlockMissingReturnType(
10371 oldBlock->blockMissingReturnType());
10373 SmallVector<ParmVarDecl*, 4> params;
10374 SmallVector<QualType, 4> paramTypes;
10376 // Parameter substitution.
10377 if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
10378 oldBlock->param_begin(),
10379 oldBlock->param_size(),
10380 nullptr, paramTypes, ¶ms)) {
10381 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10382 return ExprError();
10385 const FunctionProtoType *exprFunctionType = E->getFunctionType();
10386 QualType exprResultType =
10387 getDerived().TransformType(exprFunctionType->getReturnType());
10389 QualType functionType =
10390 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
10391 exprFunctionType->getExtProtoInfo());
10392 blockScope->FunctionType = functionType;
10394 // Set the parameters on the block decl.
10395 if (!params.empty())
10396 blockScope->TheDecl->setParams(params);
10398 if (!oldBlock->blockMissingReturnType()) {
10399 blockScope->HasImplicitReturnType = false;
10400 blockScope->ReturnType = exprResultType;
10403 // Transform the body
10404 StmtResult body = getDerived().TransformStmt(E->getBody());
10405 if (body.isInvalid()) {
10406 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10407 return ExprError();
10411 // In builds with assertions, make sure that we captured everything we
10412 // captured before.
10413 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
10414 for (const auto &I : oldBlock->captures()) {
10415 VarDecl *oldCapture = I.getVariable();
10417 // Ignore parameter packs.
10418 if (isa<ParmVarDecl>(oldCapture) &&
10419 cast<ParmVarDecl>(oldCapture)->isParameterPack())
10422 VarDecl *newCapture =
10423 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
10425 assert(blockScope->CaptureMap.count(newCapture));
10427 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
10431 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
10432 /*Scope=*/nullptr);
10435 template<typename Derived>
10437 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
10438 llvm_unreachable("Cannot transform asType expressions yet");
10441 template<typename Derived>
10443 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
10444 QualType RetTy = getDerived().TransformType(E->getType());
10445 bool ArgumentChanged = false;
10446 SmallVector<Expr*, 8> SubExprs;
10447 SubExprs.reserve(E->getNumSubExprs());
10448 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10449 SubExprs, &ArgumentChanged))
10450 return ExprError();
10452 if (!getDerived().AlwaysRebuild() &&
10456 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
10457 RetTy, E->getOp(), E->getRParenLoc());
10460 //===----------------------------------------------------------------------===//
10461 // Type reconstruction
10462 //===----------------------------------------------------------------------===//
10464 template<typename Derived>
10465 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
10466 SourceLocation Star) {
10467 return SemaRef.BuildPointerType(PointeeType, Star,
10468 getDerived().getBaseEntity());
10471 template<typename Derived>
10472 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
10473 SourceLocation Star) {
10474 return SemaRef.BuildBlockPointerType(PointeeType, Star,
10475 getDerived().getBaseEntity());
10478 template<typename Derived>
10480 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
10481 bool WrittenAsLValue,
10482 SourceLocation Sigil) {
10483 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
10484 Sigil, getDerived().getBaseEntity());
10487 template<typename Derived>
10489 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
10490 QualType ClassType,
10491 SourceLocation Sigil) {
10492 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
10493 getDerived().getBaseEntity());
10496 template<typename Derived>
10498 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
10499 ArrayType::ArraySizeModifier SizeMod,
10500 const llvm::APInt *Size,
10502 unsigned IndexTypeQuals,
10503 SourceRange BracketsRange) {
10504 if (SizeExpr || !Size)
10505 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
10506 IndexTypeQuals, BracketsRange,
10507 getDerived().getBaseEntity());
10509 QualType Types[] = {
10510 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
10511 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
10512 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
10514 const unsigned NumTypes = llvm::array_lengthof(Types);
10516 for (unsigned I = 0; I != NumTypes; ++I)
10517 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
10518 SizeType = Types[I];
10522 // Note that we can return a VariableArrayType here in the case where
10523 // the element type was a dependent VariableArrayType.
10524 IntegerLiteral *ArraySize
10525 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
10526 /*FIXME*/BracketsRange.getBegin());
10527 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
10528 IndexTypeQuals, BracketsRange,
10529 getDerived().getBaseEntity());
10532 template<typename Derived>
10534 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
10535 ArrayType::ArraySizeModifier SizeMod,
10536 const llvm::APInt &Size,
10537 unsigned IndexTypeQuals,
10538 SourceRange BracketsRange) {
10539 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
10540 IndexTypeQuals, BracketsRange);
10543 template<typename Derived>
10545 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
10546 ArrayType::ArraySizeModifier SizeMod,
10547 unsigned IndexTypeQuals,
10548 SourceRange BracketsRange) {
10549 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
10550 IndexTypeQuals, BracketsRange);
10553 template<typename Derived>
10555 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
10556 ArrayType::ArraySizeModifier SizeMod,
10558 unsigned IndexTypeQuals,
10559 SourceRange BracketsRange) {
10560 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10562 IndexTypeQuals, BracketsRange);
10565 template<typename Derived>
10567 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
10568 ArrayType::ArraySizeModifier SizeMod,
10570 unsigned IndexTypeQuals,
10571 SourceRange BracketsRange) {
10572 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10574 IndexTypeQuals, BracketsRange);
10577 template<typename Derived>
10578 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
10579 unsigned NumElements,
10580 VectorType::VectorKind VecKind) {
10581 // FIXME: semantic checking!
10582 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
10585 template<typename Derived>
10586 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
10587 unsigned NumElements,
10588 SourceLocation AttributeLoc) {
10589 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
10590 NumElements, true);
10591 IntegerLiteral *VectorSize
10592 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
10594 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
10597 template<typename Derived>
10599 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
10601 SourceLocation AttributeLoc) {
10602 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
10605 template<typename Derived>
10606 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
10608 MutableArrayRef<QualType> ParamTypes,
10609 const FunctionProtoType::ExtProtoInfo &EPI) {
10610 return SemaRef.BuildFunctionType(T, ParamTypes,
10611 getDerived().getBaseLocation(),
10612 getDerived().getBaseEntity(),
10616 template<typename Derived>
10617 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
10618 return SemaRef.Context.getFunctionNoProtoType(T);
10621 template<typename Derived>
10622 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
10623 assert(D && "no decl found");
10624 if (D->isInvalidDecl()) return QualType();
10626 // FIXME: Doesn't account for ObjCInterfaceDecl!
10628 if (isa<UsingDecl>(D)) {
10629 UsingDecl *Using = cast<UsingDecl>(D);
10630 assert(Using->hasTypename() &&
10631 "UnresolvedUsingTypenameDecl transformed to non-typename using");
10633 // A valid resolved using typename decl points to exactly one type decl.
10634 assert(++Using->shadow_begin() == Using->shadow_end());
10635 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
10638 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
10639 "UnresolvedUsingTypenameDecl transformed to non-using decl");
10640 Ty = cast<UnresolvedUsingTypenameDecl>(D);
10643 return SemaRef.Context.getTypeDeclType(Ty);
10646 template<typename Derived>
10647 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
10648 SourceLocation Loc) {
10649 return SemaRef.BuildTypeofExprType(E, Loc);
10652 template<typename Derived>
10653 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
10654 return SemaRef.Context.getTypeOfType(Underlying);
10657 template<typename Derived>
10658 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
10659 SourceLocation Loc) {
10660 return SemaRef.BuildDecltypeType(E, Loc);
10663 template<typename Derived>
10664 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
10665 UnaryTransformType::UTTKind UKind,
10666 SourceLocation Loc) {
10667 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
10670 template<typename Derived>
10671 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
10672 TemplateName Template,
10673 SourceLocation TemplateNameLoc,
10674 TemplateArgumentListInfo &TemplateArgs) {
10675 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
10678 template<typename Derived>
10679 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
10680 SourceLocation KWLoc) {
10681 return SemaRef.BuildAtomicType(ValueType, KWLoc);
10684 template<typename Derived>
10686 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10688 TemplateDecl *Template) {
10689 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
10693 template<typename Derived>
10695 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10696 const IdentifierInfo &Name,
10697 SourceLocation NameLoc,
10698 QualType ObjectType,
10699 NamedDecl *FirstQualifierInScope) {
10700 UnqualifiedId TemplateName;
10701 TemplateName.setIdentifier(&Name, NameLoc);
10702 Sema::TemplateTy Template;
10703 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10704 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10705 SS, TemplateKWLoc, TemplateName,
10706 ParsedType::make(ObjectType),
10707 /*EnteringContext=*/false,
10709 return Template.get();
10712 template<typename Derived>
10714 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10715 OverloadedOperatorKind Operator,
10716 SourceLocation NameLoc,
10717 QualType ObjectType) {
10718 UnqualifiedId Name;
10719 // FIXME: Bogus location information.
10720 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
10721 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
10722 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10723 Sema::TemplateTy Template;
10724 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10725 SS, TemplateKWLoc, Name,
10726 ParsedType::make(ObjectType),
10727 /*EnteringContext=*/false,
10729 return Template.get();
10732 template<typename Derived>
10734 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
10735 SourceLocation OpLoc,
10739 Expr *Callee = OrigCallee->IgnoreParenCasts();
10740 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
10742 if (First->getObjectKind() == OK_ObjCProperty) {
10743 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10744 if (BinaryOperator::isAssignmentOp(Opc))
10745 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
10747 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
10748 if (Result.isInvalid())
10749 return ExprError();
10750 First = Result.get();
10753 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
10754 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
10755 if (Result.isInvalid())
10756 return ExprError();
10757 Second = Result.get();
10760 // Determine whether this should be a builtin operation.
10761 if (Op == OO_Subscript) {
10762 if (!First->getType()->isOverloadableType() &&
10763 !Second->getType()->isOverloadableType())
10764 return getSema().CreateBuiltinArraySubscriptExpr(First,
10765 Callee->getLocStart(),
10767 } else if (Op == OO_Arrow) {
10768 // -> is never a builtin operation.
10769 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
10770 } else if (Second == nullptr || isPostIncDec) {
10771 if (!First->getType()->isOverloadableType()) {
10772 // The argument is not of overloadable type, so try to create a
10773 // built-in unary operation.
10774 UnaryOperatorKind Opc
10775 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10777 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
10780 if (!First->getType()->isOverloadableType() &&
10781 !Second->getType()->isOverloadableType()) {
10782 // Neither of the arguments is an overloadable type, so try to
10783 // create a built-in binary operation.
10784 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10786 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
10787 if (Result.isInvalid())
10788 return ExprError();
10794 // Compute the transformed set of functions (and function templates) to be
10795 // used during overload resolution.
10796 UnresolvedSet<16> Functions;
10798 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
10799 assert(ULE->requiresADL());
10800 Functions.append(ULE->decls_begin(), ULE->decls_end());
10802 // If we've resolved this to a particular non-member function, just call
10803 // that function. If we resolved it to a member function,
10804 // CreateOverloaded* will find that function for us.
10805 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
10806 if (!isa<CXXMethodDecl>(ND))
10807 Functions.addDecl(ND);
10810 // Add any functions found via argument-dependent lookup.
10811 Expr *Args[2] = { First, Second };
10812 unsigned NumArgs = 1 + (Second != nullptr);
10814 // Create the overloaded operator invocation for unary operators.
10815 if (NumArgs == 1 || isPostIncDec) {
10816 UnaryOperatorKind Opc
10817 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10818 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
10821 if (Op == OO_Subscript) {
10822 SourceLocation LBrace;
10823 SourceLocation RBrace;
10825 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
10826 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
10827 LBrace = SourceLocation::getFromRawEncoding(
10828 NameLoc.CXXOperatorName.BeginOpNameLoc);
10829 RBrace = SourceLocation::getFromRawEncoding(
10830 NameLoc.CXXOperatorName.EndOpNameLoc);
10832 LBrace = Callee->getLocStart();
10836 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
10840 // Create the overloaded operator invocation for binary operators.
10841 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10843 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
10844 if (Result.isInvalid())
10845 return ExprError();
10850 template<typename Derived>
10852 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
10853 SourceLocation OperatorLoc,
10856 TypeSourceInfo *ScopeType,
10857 SourceLocation CCLoc,
10858 SourceLocation TildeLoc,
10859 PseudoDestructorTypeStorage Destroyed) {
10860 QualType BaseType = Base->getType();
10861 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
10862 (!isArrow && !BaseType->getAs<RecordType>()) ||
10863 (isArrow && BaseType->getAs<PointerType>() &&
10864 !BaseType->getAs<PointerType>()->getPointeeType()
10865 ->template getAs<RecordType>())){
10866 // This pseudo-destructor expression is still a pseudo-destructor.
10867 return SemaRef.BuildPseudoDestructorExpr(
10868 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
10869 CCLoc, TildeLoc, Destroyed);
10872 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
10873 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
10874 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
10875 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
10876 NameInfo.setNamedTypeInfo(DestroyedType);
10878 // The scope type is now known to be a valid nested name specifier
10879 // component. Tack it on to the end of the nested name specifier.
10881 if (!ScopeType->getType()->getAs<TagType>()) {
10882 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
10883 diag::err_expected_class_or_namespace)
10884 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
10885 return ExprError();
10887 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
10891 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10892 return getSema().BuildMemberReferenceExpr(Base, BaseType,
10893 OperatorLoc, isArrow,
10895 /*FIXME: FirstQualifier*/ nullptr,
10897 /*TemplateArgs*/ nullptr);
10900 template<typename Derived>
10902 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
10903 SourceLocation Loc = S->getLocStart();
10904 CapturedDecl *CD = S->getCapturedDecl();
10905 unsigned NumParams = CD->getNumParams();
10906 unsigned ContextParamPos = CD->getContextParamPosition();
10907 SmallVector<Sema::CapturedParamNameType, 4> Params;
10908 for (unsigned I = 0; I < NumParams; ++I) {
10909 if (I != ContextParamPos) {
10912 CD->getParam(I)->getName(),
10913 getDerived().TransformType(CD->getParam(I)->getType())));
10915 Params.push_back(std::make_pair(StringRef(), QualType()));
10918 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
10919 S->getCapturedRegionKind(), Params);
10922 Sema::CompoundScopeRAII CompoundScope(getSema());
10923 Body = getDerived().TransformStmt(S->getCapturedStmt());
10926 if (Body.isInvalid()) {
10927 getSema().ActOnCapturedRegionError();
10928 return StmtError();
10931 return getSema().ActOnCapturedRegionEnd(Body.get());
10934 } // end namespace clang