1 //===- ExprCXX.h - Classes for representing expressions ---------*- 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.
8 //===----------------------------------------------------------------------===//
11 /// Defines the clang::Expr interface and subclasses for C++ expressions.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_AST_EXPRCXX_H
16 #define LLVM_CLANG_AST_EXPRCXX_H
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclarationName.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/NestedNameSpecifier.h"
24 #include "clang/AST/OperationKinds.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/TemplateBase.h"
27 #include "clang/AST/Type.h"
28 #include "clang/AST/UnresolvedSet.h"
29 #include "clang/Basic/ExceptionSpecificationType.h"
30 #include "clang/Basic/ExpressionTraits.h"
31 #include "clang/Basic/LLVM.h"
32 #include "clang/Basic/Lambda.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/OperatorKinds.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TypeTraits.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/None.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/PointerUnion.h"
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/ADT/iterator_range.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/TrailingObjects.h"
58 class NonTypeTemplateParmDecl;
59 class TemplateParameterList;
61 //===--------------------------------------------------------------------===//
63 //===--------------------------------------------------------------------===//
65 /// A call to an overloaded operator written using operator
68 /// Represents a call to an overloaded operator written using operator
69 /// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
70 /// normal call, this AST node provides better information about the
71 /// syntactic representation of the call.
73 /// In a C++ template, this expression node kind will be used whenever
74 /// any of the arguments are type-dependent. In this case, the
75 /// function itself will be a (possibly empty) set of functions and
76 /// function templates that were found by name lookup at template
78 class CXXOperatorCallExpr final : public CallExpr {
79 friend class ASTStmtReader;
80 friend class ASTStmtWriter;
84 // CXXOperatorCallExpr has some trailing objects belonging
85 // to CallExpr. See CallExpr for the details.
87 SourceRange getSourceRangeImpl() const LLVM_READONLY;
89 CXXOperatorCallExpr(OverloadedOperatorKind OpKind, Expr *Fn,
90 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
91 SourceLocation OperatorLoc, FPOptions FPFeatures,
94 CXXOperatorCallExpr(unsigned NumArgs, EmptyShell Empty);
97 static CXXOperatorCallExpr *
98 Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn,
99 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
100 SourceLocation OperatorLoc, FPOptions FPFeatures,
101 ADLCallKind UsesADL = NotADL);
103 static CXXOperatorCallExpr *CreateEmpty(const ASTContext &Ctx,
104 unsigned NumArgs, EmptyShell Empty);
106 /// Returns the kind of overloaded operator that this expression refers to.
107 OverloadedOperatorKind getOperator() const {
108 return static_cast<OverloadedOperatorKind>(
109 CXXOperatorCallExprBits.OperatorKind);
112 static bool isAssignmentOp(OverloadedOperatorKind Opc) {
113 return Opc == OO_Equal || Opc == OO_StarEqual || Opc == OO_SlashEqual ||
114 Opc == OO_PercentEqual || Opc == OO_PlusEqual ||
115 Opc == OO_MinusEqual || Opc == OO_LessLessEqual ||
116 Opc == OO_GreaterGreaterEqual || Opc == OO_AmpEqual ||
117 Opc == OO_CaretEqual || Opc == OO_PipeEqual;
119 bool isAssignmentOp() const { return isAssignmentOp(getOperator()); }
121 /// Is this written as an infix binary operator?
122 bool isInfixBinaryOp() const;
124 /// Returns the location of the operator symbol in the expression.
126 /// When \c getOperator()==OO_Call, this is the location of the right
127 /// parentheses; when \c getOperator()==OO_Subscript, this is the location
128 /// of the right bracket.
129 SourceLocation getOperatorLoc() const { return getRParenLoc(); }
131 SourceLocation getExprLoc() const LLVM_READONLY {
132 OverloadedOperatorKind Operator = getOperator();
133 return (Operator < OO_Plus || Operator >= OO_Arrow ||
134 Operator == OO_PlusPlus || Operator == OO_MinusMinus)
139 SourceLocation getBeginLoc() const { return Range.getBegin(); }
140 SourceLocation getEndLoc() const { return Range.getEnd(); }
141 SourceRange getSourceRange() const { return Range; }
143 static bool classof(const Stmt *T) {
144 return T->getStmtClass() == CXXOperatorCallExprClass;
147 // Set the FP contractability status of this operator. Only meaningful for
148 // operations on floating point types.
149 void setFPFeatures(FPOptions F) {
150 CXXOperatorCallExprBits.FPFeatures = F.getInt();
152 FPOptions getFPFeatures() const {
153 return FPOptions(CXXOperatorCallExprBits.FPFeatures);
156 // Get the FP contractability status of this operator. Only meaningful for
157 // operations on floating point types.
158 bool isFPContractableWithinStatement() const {
159 return getFPFeatures().allowFPContractWithinStatement();
163 /// Represents a call to a member function that
164 /// may be written either with member call syntax (e.g., "obj.func()"
165 /// or "objptr->func()") or with normal function-call syntax
166 /// ("func()") within a member function that ends up calling a member
167 /// function. The callee in either case is a MemberExpr that contains
168 /// both the object argument and the member function, while the
169 /// arguments are the arguments within the parentheses (not including
170 /// the object argument).
171 class CXXMemberCallExpr final : public CallExpr {
172 // CXXMemberCallExpr has some trailing objects belonging
173 // to CallExpr. See CallExpr for the details.
175 CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
176 ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs);
178 CXXMemberCallExpr(unsigned NumArgs, EmptyShell Empty);
181 static CXXMemberCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
182 ArrayRef<Expr *> Args, QualType Ty,
183 ExprValueKind VK, SourceLocation RP,
184 unsigned MinNumArgs = 0);
186 static CXXMemberCallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
189 /// Retrieves the implicit object argument for the member call.
191 /// For example, in "x.f(5)", this returns the sub-expression "x".
192 Expr *getImplicitObjectArgument() const;
194 /// Retrieves the declaration of the called method.
195 CXXMethodDecl *getMethodDecl() const;
197 /// Retrieves the CXXRecordDecl for the underlying type of
198 /// the implicit object argument.
200 /// Note that this is may not be the same declaration as that of the class
201 /// context of the CXXMethodDecl which this function is calling.
202 /// FIXME: Returns 0 for member pointer call exprs.
203 CXXRecordDecl *getRecordDecl() const;
205 SourceLocation getExprLoc() const LLVM_READONLY {
206 SourceLocation CLoc = getCallee()->getExprLoc();
210 return getBeginLoc();
213 static bool classof(const Stmt *T) {
214 return T->getStmtClass() == CXXMemberCallExprClass;
218 /// Represents a call to a CUDA kernel function.
219 class CUDAKernelCallExpr final : public CallExpr {
220 enum { CONFIG, END_PREARG };
222 // CUDAKernelCallExpr has some trailing objects belonging
223 // to CallExpr. See CallExpr for the details.
225 CUDAKernelCallExpr(Expr *Fn, CallExpr *Config, ArrayRef<Expr *> Args,
226 QualType Ty, ExprValueKind VK, SourceLocation RP,
227 unsigned MinNumArgs);
229 CUDAKernelCallExpr(unsigned NumArgs, EmptyShell Empty);
232 static CUDAKernelCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
233 CallExpr *Config, ArrayRef<Expr *> Args,
234 QualType Ty, ExprValueKind VK,
235 SourceLocation RP, unsigned MinNumArgs = 0);
237 static CUDAKernelCallExpr *CreateEmpty(const ASTContext &Ctx,
238 unsigned NumArgs, EmptyShell Empty);
240 const CallExpr *getConfig() const {
241 return cast_or_null<CallExpr>(getPreArg(CONFIG));
243 CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
245 /// Sets the kernel configuration expression.
247 /// Note that this method cannot be called if config has already been set to a
249 void setConfig(CallExpr *E) {
250 assert(!getConfig() &&
251 "Cannot call setConfig if config is not null");
252 setPreArg(CONFIG, E);
253 setInstantiationDependent(isInstantiationDependent() ||
254 E->isInstantiationDependent());
255 setContainsUnexpandedParameterPack(containsUnexpandedParameterPack() ||
256 E->containsUnexpandedParameterPack());
259 static bool classof(const Stmt *T) {
260 return T->getStmtClass() == CUDAKernelCallExprClass;
264 /// Abstract class common to all of the C++ "named"/"keyword" casts.
266 /// This abstract class is inherited by all of the classes
267 /// representing "named" casts: CXXStaticCastExpr for \c static_cast,
268 /// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
269 /// reinterpret_cast, and CXXConstCastExpr for \c const_cast.
270 class CXXNamedCastExpr : public ExplicitCastExpr {
272 // the location of the casting op
275 // the location of the right parenthesis
276 SourceLocation RParenLoc;
279 SourceRange AngleBrackets;
282 friend class ASTStmtReader;
284 CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
285 CastKind kind, Expr *op, unsigned PathSize,
286 TypeSourceInfo *writtenTy, SourceLocation l,
287 SourceLocation RParenLoc,
288 SourceRange AngleBrackets)
289 : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
290 RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
292 explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
293 : ExplicitCastExpr(SC, Shell, PathSize) {}
296 const char *getCastName() const;
298 /// Retrieve the location of the cast operator keyword, e.g.,
300 SourceLocation getOperatorLoc() const { return Loc; }
302 /// Retrieve the location of the closing parenthesis.
303 SourceLocation getRParenLoc() const { return RParenLoc; }
305 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
306 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
307 SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
309 static bool classof(const Stmt *T) {
310 switch (T->getStmtClass()) {
311 case CXXStaticCastExprClass:
312 case CXXDynamicCastExprClass:
313 case CXXReinterpretCastExprClass:
314 case CXXConstCastExprClass:
322 /// A C++ \c static_cast expression (C++ [expr.static.cast]).
324 /// This expression node represents a C++ static cast, e.g.,
325 /// \c static_cast<int>(1.0).
326 class CXXStaticCastExpr final
327 : public CXXNamedCastExpr,
328 private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *> {
329 CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
330 unsigned pathSize, TypeSourceInfo *writtenTy,
331 SourceLocation l, SourceLocation RParenLoc,
332 SourceRange AngleBrackets)
333 : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
334 writtenTy, l, RParenLoc, AngleBrackets) {}
336 explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
337 : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) {}
340 friend class CastExpr;
341 friend TrailingObjects;
343 static CXXStaticCastExpr *Create(const ASTContext &Context, QualType T,
344 ExprValueKind VK, CastKind K, Expr *Op,
345 const CXXCastPath *Path,
346 TypeSourceInfo *Written, SourceLocation L,
347 SourceLocation RParenLoc,
348 SourceRange AngleBrackets);
349 static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
352 static bool classof(const Stmt *T) {
353 return T->getStmtClass() == CXXStaticCastExprClass;
357 /// A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
359 /// This expression node represents a dynamic cast, e.g.,
360 /// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
361 /// check to determine how to perform the type conversion.
362 class CXXDynamicCastExpr final
363 : public CXXNamedCastExpr,
364 private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> {
365 CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
366 Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
367 SourceLocation l, SourceLocation RParenLoc,
368 SourceRange AngleBrackets)
369 : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
370 writtenTy, l, RParenLoc, AngleBrackets) {}
372 explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
373 : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) {}
376 friend class CastExpr;
377 friend TrailingObjects;
379 static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
380 ExprValueKind VK, CastKind Kind, Expr *Op,
381 const CXXCastPath *Path,
382 TypeSourceInfo *Written, SourceLocation L,
383 SourceLocation RParenLoc,
384 SourceRange AngleBrackets);
386 static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
389 bool isAlwaysNull() const;
391 static bool classof(const Stmt *T) {
392 return T->getStmtClass() == CXXDynamicCastExprClass;
396 /// A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
398 /// This expression node represents a reinterpret cast, e.g.,
399 /// @c reinterpret_cast<int>(VoidPtr).
401 /// A reinterpret_cast provides a differently-typed view of a value but
402 /// (in Clang, as in most C++ implementations) performs no actual work at
404 class CXXReinterpretCastExpr final
405 : public CXXNamedCastExpr,
406 private llvm::TrailingObjects<CXXReinterpretCastExpr,
407 CXXBaseSpecifier *> {
408 CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
409 Expr *op, unsigned pathSize,
410 TypeSourceInfo *writtenTy, SourceLocation l,
411 SourceLocation RParenLoc,
412 SourceRange AngleBrackets)
413 : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
414 pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
416 CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
417 : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) {}
420 friend class CastExpr;
421 friend TrailingObjects;
423 static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
424 ExprValueKind VK, CastKind Kind,
425 Expr *Op, const CXXCastPath *Path,
426 TypeSourceInfo *WrittenTy, SourceLocation L,
427 SourceLocation RParenLoc,
428 SourceRange AngleBrackets);
429 static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
432 static bool classof(const Stmt *T) {
433 return T->getStmtClass() == CXXReinterpretCastExprClass;
437 /// A C++ \c const_cast expression (C++ [expr.const.cast]).
439 /// This expression node represents a const cast, e.g.,
440 /// \c const_cast<char*>(PtrToConstChar).
442 /// A const_cast can remove type qualifiers but does not change the underlying
444 class CXXConstCastExpr final
445 : public CXXNamedCastExpr,
446 private llvm::TrailingObjects<CXXConstCastExpr, CXXBaseSpecifier *> {
447 CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
448 TypeSourceInfo *writtenTy, SourceLocation l,
449 SourceLocation RParenLoc, SourceRange AngleBrackets)
450 : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
451 0, writtenTy, l, RParenLoc, AngleBrackets) {}
453 explicit CXXConstCastExpr(EmptyShell Empty)
454 : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) {}
457 friend class CastExpr;
458 friend TrailingObjects;
460 static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
461 ExprValueKind VK, Expr *Op,
462 TypeSourceInfo *WrittenTy, SourceLocation L,
463 SourceLocation RParenLoc,
464 SourceRange AngleBrackets);
465 static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
467 static bool classof(const Stmt *T) {
468 return T->getStmtClass() == CXXConstCastExprClass;
472 /// A call to a literal operator (C++11 [over.literal])
473 /// written as a user-defined literal (C++11 [lit.ext]).
475 /// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
476 /// is semantically equivalent to a normal call, this AST node provides better
477 /// information about the syntactic representation of the literal.
479 /// Since literal operators are never found by ADL and can only be declared at
480 /// namespace scope, a user-defined literal is never dependent.
481 class UserDefinedLiteral final : public CallExpr {
482 friend class ASTStmtReader;
483 friend class ASTStmtWriter;
485 /// The location of a ud-suffix within the literal.
486 SourceLocation UDSuffixLoc;
488 // UserDefinedLiteral has some trailing objects belonging
489 // to CallExpr. See CallExpr for the details.
491 UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
492 ExprValueKind VK, SourceLocation LitEndLoc,
493 SourceLocation SuffixLoc);
495 UserDefinedLiteral(unsigned NumArgs, EmptyShell Empty);
498 static UserDefinedLiteral *Create(const ASTContext &Ctx, Expr *Fn,
499 ArrayRef<Expr *> Args, QualType Ty,
500 ExprValueKind VK, SourceLocation LitEndLoc,
501 SourceLocation SuffixLoc);
503 static UserDefinedLiteral *CreateEmpty(const ASTContext &Ctx,
504 unsigned NumArgs, EmptyShell Empty);
506 /// The kind of literal operator which is invoked.
507 enum LiteralOperatorKind {
508 /// Raw form: operator "" X (const char *)
511 /// Raw form: operator "" X<cs...> ()
514 /// operator "" X (unsigned long long)
517 /// operator "" X (long double)
520 /// operator "" X (const CharT *, size_t)
523 /// operator "" X (CharT)
527 /// Returns the kind of literal operator invocation
528 /// which this expression represents.
529 LiteralOperatorKind getLiteralOperatorKind() const;
531 /// If this is not a raw user-defined literal, get the
532 /// underlying cooked literal (representing the literal with the suffix
534 Expr *getCookedLiteral();
535 const Expr *getCookedLiteral() const {
536 return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
539 SourceLocation getBeginLoc() const {
540 if (getLiteralOperatorKind() == LOK_Template)
541 return getRParenLoc();
542 return getArg(0)->getBeginLoc();
545 SourceLocation getEndLoc() const { return getRParenLoc(); }
547 /// Returns the location of a ud-suffix in the expression.
549 /// For a string literal, there may be multiple identical suffixes. This
550 /// returns the first.
551 SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
553 /// Returns the ud-suffix specified for this literal.
554 const IdentifierInfo *getUDSuffix() const;
556 static bool classof(const Stmt *S) {
557 return S->getStmtClass() == UserDefinedLiteralClass;
561 /// A boolean literal, per ([C++ lex.bool] Boolean literals).
562 class CXXBoolLiteralExpr : public Expr {
564 CXXBoolLiteralExpr(bool Val, QualType Ty, SourceLocation Loc)
565 : Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
567 CXXBoolLiteralExprBits.Value = Val;
568 CXXBoolLiteralExprBits.Loc = Loc;
571 explicit CXXBoolLiteralExpr(EmptyShell Empty)
572 : Expr(CXXBoolLiteralExprClass, Empty) {}
574 bool getValue() const { return CXXBoolLiteralExprBits.Value; }
575 void setValue(bool V) { CXXBoolLiteralExprBits.Value = V; }
577 SourceLocation getBeginLoc() const { return getLocation(); }
578 SourceLocation getEndLoc() const { return getLocation(); }
580 SourceLocation getLocation() const { return CXXBoolLiteralExprBits.Loc; }
581 void setLocation(SourceLocation L) { CXXBoolLiteralExprBits.Loc = L; }
583 static bool classof(const Stmt *T) {
584 return T->getStmtClass() == CXXBoolLiteralExprClass;
588 child_range children() {
589 return child_range(child_iterator(), child_iterator());
593 /// The null pointer literal (C++11 [lex.nullptr])
595 /// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
596 class CXXNullPtrLiteralExpr : public Expr {
598 CXXNullPtrLiteralExpr(QualType Ty, SourceLocation Loc)
599 : Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false,
600 false, false, false) {
601 CXXNullPtrLiteralExprBits.Loc = Loc;
604 explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
605 : Expr(CXXNullPtrLiteralExprClass, Empty) {}
607 SourceLocation getBeginLoc() const { return getLocation(); }
608 SourceLocation getEndLoc() const { return getLocation(); }
610 SourceLocation getLocation() const { return CXXNullPtrLiteralExprBits.Loc; }
611 void setLocation(SourceLocation L) { CXXNullPtrLiteralExprBits.Loc = L; }
613 static bool classof(const Stmt *T) {
614 return T->getStmtClass() == CXXNullPtrLiteralExprClass;
617 child_range children() {
618 return child_range(child_iterator(), child_iterator());
622 /// Implicit construction of a std::initializer_list<T> object from an
623 /// array temporary within list-initialization (C++11 [dcl.init.list]p5).
624 class CXXStdInitializerListExpr : public Expr {
625 Stmt *SubExpr = nullptr;
627 CXXStdInitializerListExpr(EmptyShell Empty)
628 : Expr(CXXStdInitializerListExprClass, Empty) {}
631 friend class ASTReader;
632 friend class ASTStmtReader;
634 CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
635 : Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
636 Ty->isDependentType(), SubExpr->isValueDependent(),
637 SubExpr->isInstantiationDependent(),
638 SubExpr->containsUnexpandedParameterPack()),
641 Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
642 const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
644 SourceLocation getBeginLoc() const LLVM_READONLY {
645 return SubExpr->getBeginLoc();
648 SourceLocation getEndLoc() const LLVM_READONLY {
649 return SubExpr->getEndLoc();
652 /// Retrieve the source range of the expression.
653 SourceRange getSourceRange() const LLVM_READONLY {
654 return SubExpr->getSourceRange();
657 static bool classof(const Stmt *S) {
658 return S->getStmtClass() == CXXStdInitializerListExprClass;
661 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
664 /// A C++ \c typeid expression (C++ [expr.typeid]), which gets
665 /// the \c type_info that corresponds to the supplied type, or the (possibly
666 /// dynamic) type of the supplied expression.
668 /// This represents code like \c typeid(int) or \c typeid(*objPtr)
669 class CXXTypeidExpr : public Expr {
671 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
675 CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
676 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
677 // typeid is never type-dependent (C++ [temp.dep.expr]p4)
679 // typeid is value-dependent if the type or expression are
681 Operand->getType()->isDependentType(),
682 Operand->getType()->isInstantiationDependentType(),
683 Operand->getType()->containsUnexpandedParameterPack()),
684 Operand(Operand), Range(R) {}
686 CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
687 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
688 // typeid is never type-dependent (C++ [temp.dep.expr]p4)
690 // typeid is value-dependent if the type or expression are
692 Operand->isTypeDependent() || Operand->isValueDependent(),
693 Operand->isInstantiationDependent(),
694 Operand->containsUnexpandedParameterPack()),
695 Operand(Operand), Range(R) {}
697 CXXTypeidExpr(EmptyShell Empty, bool isExpr)
698 : Expr(CXXTypeidExprClass, Empty) {
700 Operand = (Expr*)nullptr;
702 Operand = (TypeSourceInfo*)nullptr;
705 /// Determine whether this typeid has a type operand which is potentially
706 /// evaluated, per C++11 [expr.typeid]p3.
707 bool isPotentiallyEvaluated() const;
709 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
711 /// Retrieves the type operand of this typeid() expression after
712 /// various required adjustments (removing reference types, cv-qualifiers).
713 QualType getTypeOperand(ASTContext &Context) const;
715 /// Retrieve source information for the type operand.
716 TypeSourceInfo *getTypeOperandSourceInfo() const {
717 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
718 return Operand.get<TypeSourceInfo *>();
721 void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
722 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
726 Expr *getExprOperand() const {
727 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
728 return static_cast<Expr*>(Operand.get<Stmt *>());
731 void setExprOperand(Expr *E) {
732 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
736 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
737 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
738 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
739 void setSourceRange(SourceRange R) { Range = R; }
741 static bool classof(const Stmt *T) {
742 return T->getStmtClass() == CXXTypeidExprClass;
746 child_range children() {
748 return child_range(child_iterator(), child_iterator());
749 auto **begin = reinterpret_cast<Stmt **>(&Operand);
750 return child_range(begin, begin + 1);
754 /// A member reference to an MSPropertyDecl.
756 /// This expression always has pseudo-object type, and therefore it is
757 /// typically not encountered in a fully-typechecked expression except
758 /// within the syntactic form of a PseudoObjectExpr.
759 class MSPropertyRefExpr : public Expr {
761 MSPropertyDecl *TheDecl;
762 SourceLocation MemberLoc;
764 NestedNameSpecifierLoc QualifierLoc;
767 friend class ASTStmtReader;
769 MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
770 QualType ty, ExprValueKind VK,
771 NestedNameSpecifierLoc qualifierLoc,
772 SourceLocation nameLoc)
773 : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
774 /*type-dependent*/ false, baseExpr->isValueDependent(),
775 baseExpr->isInstantiationDependent(),
776 baseExpr->containsUnexpandedParameterPack()),
777 BaseExpr(baseExpr), TheDecl(decl),
778 MemberLoc(nameLoc), IsArrow(isArrow),
779 QualifierLoc(qualifierLoc) {}
781 MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
783 SourceRange getSourceRange() const LLVM_READONLY {
784 return SourceRange(getBeginLoc(), getEndLoc());
787 bool isImplicitAccess() const {
788 return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
791 SourceLocation getBeginLoc() const {
792 if (!isImplicitAccess())
793 return BaseExpr->getBeginLoc();
794 else if (QualifierLoc)
795 return QualifierLoc.getBeginLoc();
800 SourceLocation getEndLoc() const { return getMemberLoc(); }
802 child_range children() {
803 return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
806 static bool classof(const Stmt *T) {
807 return T->getStmtClass() == MSPropertyRefExprClass;
810 Expr *getBaseExpr() const { return BaseExpr; }
811 MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
812 bool isArrow() const { return IsArrow; }
813 SourceLocation getMemberLoc() const { return MemberLoc; }
814 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
817 /// MS property subscript expression.
818 /// MSVC supports 'property' attribute and allows to apply it to the
819 /// declaration of an empty array in a class or structure definition.
822 /// __declspec(property(get=GetX, put=PutX)) int x[];
824 /// The above statement indicates that x[] can be used with one or more array
825 /// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and
826 /// p->x[a][b] = i will be turned into p->PutX(a, b, i).
827 /// This is a syntactic pseudo-object expression.
828 class MSPropertySubscriptExpr : public Expr {
829 friend class ASTStmtReader;
831 enum { BASE_EXPR, IDX_EXPR, NUM_SUBEXPRS = 2 };
833 Stmt *SubExprs[NUM_SUBEXPRS];
834 SourceLocation RBracketLoc;
836 void setBase(Expr *Base) { SubExprs[BASE_EXPR] = Base; }
837 void setIdx(Expr *Idx) { SubExprs[IDX_EXPR] = Idx; }
840 MSPropertySubscriptExpr(Expr *Base, Expr *Idx, QualType Ty, ExprValueKind VK,
841 ExprObjectKind OK, SourceLocation RBracketLoc)
842 : Expr(MSPropertySubscriptExprClass, Ty, VK, OK, Idx->isTypeDependent(),
843 Idx->isValueDependent(), Idx->isInstantiationDependent(),
844 Idx->containsUnexpandedParameterPack()),
845 RBracketLoc(RBracketLoc) {
846 SubExprs[BASE_EXPR] = Base;
847 SubExprs[IDX_EXPR] = Idx;
850 /// Create an empty array subscript expression.
851 explicit MSPropertySubscriptExpr(EmptyShell Shell)
852 : Expr(MSPropertySubscriptExprClass, Shell) {}
854 Expr *getBase() { return cast<Expr>(SubExprs[BASE_EXPR]); }
855 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE_EXPR]); }
857 Expr *getIdx() { return cast<Expr>(SubExprs[IDX_EXPR]); }
858 const Expr *getIdx() const { return cast<Expr>(SubExprs[IDX_EXPR]); }
860 SourceLocation getBeginLoc() const LLVM_READONLY {
861 return getBase()->getBeginLoc();
864 SourceLocation getEndLoc() const LLVM_READONLY { return RBracketLoc; }
866 SourceLocation getRBracketLoc() const { return RBracketLoc; }
867 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
869 SourceLocation getExprLoc() const LLVM_READONLY {
870 return getBase()->getExprLoc();
873 static bool classof(const Stmt *T) {
874 return T->getStmtClass() == MSPropertySubscriptExprClass;
878 child_range children() {
879 return child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
883 /// A Microsoft C++ @c __uuidof expression, which gets
884 /// the _GUID that corresponds to the supplied type or expression.
886 /// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
887 class CXXUuidofExpr : public Expr {
889 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
894 CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, StringRef UuidStr,
896 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary, false,
897 Operand->getType()->isDependentType(),
898 Operand->getType()->isInstantiationDependentType(),
899 Operand->getType()->containsUnexpandedParameterPack()),
900 Operand(Operand), UuidStr(UuidStr), Range(R) {}
902 CXXUuidofExpr(QualType Ty, Expr *Operand, StringRef UuidStr, SourceRange R)
903 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary, false,
904 Operand->isTypeDependent(), Operand->isInstantiationDependent(),
905 Operand->containsUnexpandedParameterPack()),
906 Operand(Operand), UuidStr(UuidStr), Range(R) {}
908 CXXUuidofExpr(EmptyShell Empty, bool isExpr)
909 : Expr(CXXUuidofExprClass, Empty) {
911 Operand = (Expr*)nullptr;
913 Operand = (TypeSourceInfo*)nullptr;
916 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
918 /// Retrieves the type operand of this __uuidof() expression after
919 /// various required adjustments (removing reference types, cv-qualifiers).
920 QualType getTypeOperand(ASTContext &Context) const;
922 /// Retrieve source information for the type operand.
923 TypeSourceInfo *getTypeOperandSourceInfo() const {
924 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
925 return Operand.get<TypeSourceInfo *>();
928 void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
929 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
933 Expr *getExprOperand() const {
934 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
935 return static_cast<Expr*>(Operand.get<Stmt *>());
938 void setExprOperand(Expr *E) {
939 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
943 void setUuidStr(StringRef US) { UuidStr = US; }
944 StringRef getUuidStr() const { return UuidStr; }
946 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
947 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
948 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
949 void setSourceRange(SourceRange R) { Range = R; }
951 static bool classof(const Stmt *T) {
952 return T->getStmtClass() == CXXUuidofExprClass;
956 child_range children() {
958 return child_range(child_iterator(), child_iterator());
959 auto **begin = reinterpret_cast<Stmt **>(&Operand);
960 return child_range(begin, begin + 1);
964 /// Represents the \c this expression in C++.
966 /// This is a pointer to the object on which the current member function is
967 /// executing (C++ [expr.prim]p3). Example:
973 /// void test() { this->bar(); }
976 class CXXThisExpr : public Expr {
978 CXXThisExpr(SourceLocation L, QualType Ty, bool IsImplicit)
979 : Expr(CXXThisExprClass, Ty, VK_RValue, OK_Ordinary,
980 // 'this' is type-dependent if the class type of the enclosing
981 // member function is dependent (C++ [temp.dep.expr]p2)
982 Ty->isDependentType(), Ty->isDependentType(),
983 Ty->isInstantiationDependentType(),
984 /*ContainsUnexpandedParameterPack=*/false) {
985 CXXThisExprBits.IsImplicit = IsImplicit;
986 CXXThisExprBits.Loc = L;
989 CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
991 SourceLocation getLocation() const { return CXXThisExprBits.Loc; }
992 void setLocation(SourceLocation L) { CXXThisExprBits.Loc = L; }
994 SourceLocation getBeginLoc() const { return getLocation(); }
995 SourceLocation getEndLoc() const { return getLocation(); }
997 bool isImplicit() const { return CXXThisExprBits.IsImplicit; }
998 void setImplicit(bool I) { CXXThisExprBits.IsImplicit = I; }
1000 static bool classof(const Stmt *T) {
1001 return T->getStmtClass() == CXXThisExprClass;
1005 child_range children() {
1006 return child_range(child_iterator(), child_iterator());
1010 /// A C++ throw-expression (C++ [except.throw]).
1012 /// This handles 'throw' (for re-throwing the current exception) and
1013 /// 'throw' assignment-expression. When assignment-expression isn't
1014 /// present, Op will be null.
1015 class CXXThrowExpr : public Expr {
1016 friend class ASTStmtReader;
1018 /// The optional expression in the throw statement.
1022 // \p Ty is the void type which is used as the result type of the
1023 // expression. The \p Loc is the location of the throw keyword.
1024 // \p Operand is the expression in the throw statement, and can be
1025 // null if not present.
1026 CXXThrowExpr(Expr *Operand, QualType Ty, SourceLocation Loc,
1027 bool IsThrownVariableInScope)
1028 : Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
1029 Operand && Operand->isInstantiationDependent(),
1030 Operand && Operand->containsUnexpandedParameterPack()),
1032 CXXThrowExprBits.ThrowLoc = Loc;
1033 CXXThrowExprBits.IsThrownVariableInScope = IsThrownVariableInScope;
1035 CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
1037 const Expr *getSubExpr() const { return cast_or_null<Expr>(Operand); }
1038 Expr *getSubExpr() { return cast_or_null<Expr>(Operand); }
1040 SourceLocation getThrowLoc() const { return CXXThrowExprBits.ThrowLoc; }
1042 /// Determines whether the variable thrown by this expression (if any!)
1043 /// is within the innermost try block.
1045 /// This information is required to determine whether the NRVO can apply to
1047 bool isThrownVariableInScope() const {
1048 return CXXThrowExprBits.IsThrownVariableInScope;
1051 SourceLocation getBeginLoc() const { return getThrowLoc(); }
1052 SourceLocation getEndLoc() const LLVM_READONLY {
1054 return getThrowLoc();
1055 return getSubExpr()->getEndLoc();
1058 static bool classof(const Stmt *T) {
1059 return T->getStmtClass() == CXXThrowExprClass;
1063 child_range children() {
1064 return child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1068 /// A default argument (C++ [dcl.fct.default]).
1070 /// This wraps up a function call argument that was created from the
1071 /// corresponding parameter's default argument, when the call did not
1072 /// explicitly supply arguments for all of the parameters.
1073 class CXXDefaultArgExpr final : public Expr {
1074 friend class ASTStmtReader;
1076 /// The parameter whose default is being used.
1079 CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param)
1081 Param->hasUnparsedDefaultArg()
1082 ? Param->getType().getNonReferenceType()
1083 : Param->getDefaultArg()->getType(),
1084 Param->getDefaultArg()->getValueKind(),
1085 Param->getDefaultArg()->getObjectKind(), false, false, false,
1088 CXXDefaultArgExprBits.Loc = Loc;
1092 CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
1094 // \p Param is the parameter whose default argument is used by this
1096 static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
1097 ParmVarDecl *Param) {
1098 return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param);
1101 // Retrieve the parameter that the argument was created from.
1102 const ParmVarDecl *getParam() const { return Param; }
1103 ParmVarDecl *getParam() { return Param; }
1105 // Retrieve the actual argument to the function call.
1106 const Expr *getExpr() const { return getParam()->getDefaultArg(); }
1107 Expr *getExpr() { return getParam()->getDefaultArg(); }
1109 /// Retrieve the location where this default argument was actually used.
1110 SourceLocation getUsedLocation() const { return CXXDefaultArgExprBits.Loc; }
1112 /// Default argument expressions have no representation in the
1113 /// source, so they have an empty source range.
1114 SourceLocation getBeginLoc() const { return SourceLocation(); }
1115 SourceLocation getEndLoc() const { return SourceLocation(); }
1117 SourceLocation getExprLoc() const { return getUsedLocation(); }
1119 static bool classof(const Stmt *T) {
1120 return T->getStmtClass() == CXXDefaultArgExprClass;
1124 child_range children() {
1125 return child_range(child_iterator(), child_iterator());
1129 /// A use of a default initializer in a constructor or in aggregate
1132 /// This wraps a use of a C++ default initializer (technically,
1133 /// a brace-or-equal-initializer for a non-static data member) when it
1134 /// is implicitly used in a mem-initializer-list in a constructor
1135 /// (C++11 [class.base.init]p8) or in aggregate initialization
1136 /// (C++1y [dcl.init.aggr]p7).
1137 class CXXDefaultInitExpr : public Expr {
1138 friend class ASTReader;
1139 friend class ASTStmtReader;
1141 /// The field whose default is being used.
1144 CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
1145 FieldDecl *Field, QualType Ty);
1147 CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
1150 /// \p Field is the non-static data member whose default initializer is used
1151 /// by this expression.
1152 static CXXDefaultInitExpr *Create(const ASTContext &Ctx, SourceLocation Loc,
1154 return new (Ctx) CXXDefaultInitExpr(Ctx, Loc, Field, Field->getType());
1157 /// Get the field whose initializer will be used.
1158 FieldDecl *getField() { return Field; }
1159 const FieldDecl *getField() const { return Field; }
1161 /// Get the initialization expression that will be used.
1162 const Expr *getExpr() const {
1163 assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
1164 return Field->getInClassInitializer();
1167 assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
1168 return Field->getInClassInitializer();
1171 SourceLocation getBeginLoc() const { return CXXDefaultInitExprBits.Loc; }
1172 SourceLocation getEndLoc() const { return CXXDefaultInitExprBits.Loc; }
1174 static bool classof(const Stmt *T) {
1175 return T->getStmtClass() == CXXDefaultInitExprClass;
1179 child_range children() {
1180 return child_range(child_iterator(), child_iterator());
1184 /// Represents a C++ temporary.
1185 class CXXTemporary {
1186 /// The destructor that needs to be called.
1187 const CXXDestructorDecl *Destructor;
1189 explicit CXXTemporary(const CXXDestructorDecl *destructor)
1190 : Destructor(destructor) {}
1193 static CXXTemporary *Create(const ASTContext &C,
1194 const CXXDestructorDecl *Destructor);
1196 const CXXDestructorDecl *getDestructor() const { return Destructor; }
1198 void setDestructor(const CXXDestructorDecl *Dtor) {
1203 /// Represents binding an expression to a temporary.
1205 /// This ensures the destructor is called for the temporary. It should only be
1206 /// needed for non-POD, non-trivially destructable class types. For example:
1210 /// S() { } // User defined constructor makes S non-POD.
1211 /// ~S() { } // User defined destructor makes it non-trivial.
1214 /// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1217 class CXXBindTemporaryExpr : public Expr {
1218 CXXTemporary *Temp = nullptr;
1219 Stmt *SubExpr = nullptr;
1221 CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
1222 : Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
1223 VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
1224 SubExpr->isValueDependent(),
1225 SubExpr->isInstantiationDependent(),
1226 SubExpr->containsUnexpandedParameterPack()),
1227 Temp(temp), SubExpr(SubExpr) {}
1230 CXXBindTemporaryExpr(EmptyShell Empty)
1231 : Expr(CXXBindTemporaryExprClass, Empty) {}
1233 static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
1236 CXXTemporary *getTemporary() { return Temp; }
1237 const CXXTemporary *getTemporary() const { return Temp; }
1238 void setTemporary(CXXTemporary *T) { Temp = T; }
1240 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1241 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1242 void setSubExpr(Expr *E) { SubExpr = E; }
1244 SourceLocation getBeginLoc() const LLVM_READONLY {
1245 return SubExpr->getBeginLoc();
1248 SourceLocation getEndLoc() const LLVM_READONLY {
1249 return SubExpr->getEndLoc();
1252 // Implement isa/cast/dyncast/etc.
1253 static bool classof(const Stmt *T) {
1254 return T->getStmtClass() == CXXBindTemporaryExprClass;
1258 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1261 /// Represents a call to a C++ constructor.
1262 class CXXConstructExpr : public Expr {
1263 friend class ASTStmtReader;
1266 enum ConstructionKind {
1274 /// A pointer to the constructor which will be ultimately called.
1275 CXXConstructorDecl *Constructor;
1277 SourceRange ParenOrBraceRange;
1279 /// The number of arguments.
1282 // We would like to stash the arguments of the constructor call after
1283 // CXXConstructExpr. However CXXConstructExpr is used as a base class of
1284 // CXXTemporaryObjectExpr which makes the use of llvm::TrailingObjects
1287 // Instead we manually stash the trailing object after the full object
1288 // containing CXXConstructExpr (that is either CXXConstructExpr or
1289 // CXXTemporaryObjectExpr).
1291 // The trailing objects are:
1293 // * An array of getNumArgs() "Stmt *" for the arguments of the
1294 // constructor call.
1296 /// Return a pointer to the start of the trailing arguments.
1297 /// Defined just after CXXTemporaryObjectExpr.
1298 inline Stmt **getTrailingArgs();
1299 const Stmt *const *getTrailingArgs() const {
1300 return const_cast<CXXConstructExpr *>(this)->getTrailingArgs();
1304 /// Build a C++ construction expression.
1305 CXXConstructExpr(StmtClass SC, QualType Ty, SourceLocation Loc,
1306 CXXConstructorDecl *Ctor, bool Elidable,
1307 ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1308 bool ListInitialization, bool StdInitListInitialization,
1309 bool ZeroInitialization, ConstructionKind ConstructKind,
1310 SourceRange ParenOrBraceRange);
1312 /// Build an empty C++ construction expression.
1313 CXXConstructExpr(StmtClass SC, EmptyShell Empty, unsigned NumArgs);
1315 /// Return the size in bytes of the trailing objects. Used by
1316 /// CXXTemporaryObjectExpr to allocate the right amount of storage.
1317 static unsigned sizeOfTrailingObjects(unsigned NumArgs) {
1318 return NumArgs * sizeof(Stmt *);
1322 /// Create a C++ construction expression.
1323 static CXXConstructExpr *
1324 Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
1325 CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
1326 bool HadMultipleCandidates, bool ListInitialization,
1327 bool StdInitListInitialization, bool ZeroInitialization,
1328 ConstructionKind ConstructKind, SourceRange ParenOrBraceRange);
1330 /// Create an empty C++ construction expression.
1331 static CXXConstructExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs);
1333 /// Get the constructor that this expression will (ultimately) call.
1334 CXXConstructorDecl *getConstructor() const { return Constructor; }
1336 SourceLocation getLocation() const { return CXXConstructExprBits.Loc; }
1337 void setLocation(SourceLocation Loc) { CXXConstructExprBits.Loc = Loc; }
1339 /// Whether this construction is elidable.
1340 bool isElidable() const { return CXXConstructExprBits.Elidable; }
1341 void setElidable(bool E) { CXXConstructExprBits.Elidable = E; }
1343 /// Whether the referred constructor was resolved from
1344 /// an overloaded set having size greater than 1.
1345 bool hadMultipleCandidates() const {
1346 return CXXConstructExprBits.HadMultipleCandidates;
1348 void setHadMultipleCandidates(bool V) {
1349 CXXConstructExprBits.HadMultipleCandidates = V;
1352 /// Whether this constructor call was written as list-initialization.
1353 bool isListInitialization() const {
1354 return CXXConstructExprBits.ListInitialization;
1356 void setListInitialization(bool V) {
1357 CXXConstructExprBits.ListInitialization = V;
1360 /// Whether this constructor call was written as list-initialization,
1361 /// but was interpreted as forming a std::initializer_list<T> from the list
1362 /// and passing that as a single constructor argument.
1363 /// See C++11 [over.match.list]p1 bullet 1.
1364 bool isStdInitListInitialization() const {
1365 return CXXConstructExprBits.StdInitListInitialization;
1367 void setStdInitListInitialization(bool V) {
1368 CXXConstructExprBits.StdInitListInitialization = V;
1371 /// Whether this construction first requires
1372 /// zero-initialization before the initializer is called.
1373 bool requiresZeroInitialization() const {
1374 return CXXConstructExprBits.ZeroInitialization;
1376 void setRequiresZeroInitialization(bool ZeroInit) {
1377 CXXConstructExprBits.ZeroInitialization = ZeroInit;
1380 /// Determine whether this constructor is actually constructing
1381 /// a base class (rather than a complete object).
1382 ConstructionKind getConstructionKind() const {
1383 return static_cast<ConstructionKind>(CXXConstructExprBits.ConstructionKind);
1385 void setConstructionKind(ConstructionKind CK) {
1386 CXXConstructExprBits.ConstructionKind = CK;
1389 using arg_iterator = ExprIterator;
1390 using const_arg_iterator = ConstExprIterator;
1391 using arg_range = llvm::iterator_range<arg_iterator>;
1392 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
1394 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
1395 const_arg_range arguments() const {
1396 return const_arg_range(arg_begin(), arg_end());
1399 arg_iterator arg_begin() { return getTrailingArgs(); }
1400 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
1401 const_arg_iterator arg_begin() const { return getTrailingArgs(); }
1402 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
1404 Expr **getArgs() { return reinterpret_cast<Expr **>(getTrailingArgs()); }
1405 const Expr *const *getArgs() const {
1406 return reinterpret_cast<const Expr *const *>(getTrailingArgs());
1409 /// Return the number of arguments to the constructor call.
1410 unsigned getNumArgs() const { return NumArgs; }
1412 /// Return the specified argument.
1413 Expr *getArg(unsigned Arg) {
1414 assert(Arg < getNumArgs() && "Arg access out of range!");
1415 return getArgs()[Arg];
1417 const Expr *getArg(unsigned Arg) const {
1418 assert(Arg < getNumArgs() && "Arg access out of range!");
1419 return getArgs()[Arg];
1422 /// Set the specified argument.
1423 void setArg(unsigned Arg, Expr *ArgExpr) {
1424 assert(Arg < getNumArgs() && "Arg access out of range!");
1425 getArgs()[Arg] = ArgExpr;
1428 SourceLocation getBeginLoc() const LLVM_READONLY;
1429 SourceLocation getEndLoc() const LLVM_READONLY;
1430 SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
1431 void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
1433 static bool classof(const Stmt *T) {
1434 return T->getStmtClass() == CXXConstructExprClass ||
1435 T->getStmtClass() == CXXTemporaryObjectExprClass;
1439 child_range children() {
1440 return child_range(getTrailingArgs(), getTrailingArgs() + getNumArgs());
1444 /// Represents a call to an inherited base class constructor from an
1445 /// inheriting constructor. This call implicitly forwards the arguments from
1446 /// the enclosing context (an inheriting constructor) to the specified inherited
1447 /// base class constructor.
1448 class CXXInheritedCtorInitExpr : public Expr {
1450 CXXConstructorDecl *Constructor = nullptr;
1452 /// The location of the using declaration.
1455 /// Whether this is the construction of a virtual base.
1456 unsigned ConstructsVirtualBase : 1;
1458 /// Whether the constructor is inherited from a virtual base class of the
1459 /// class that we construct.
1460 unsigned InheritedFromVirtualBase : 1;
1463 friend class ASTStmtReader;
1465 /// Construct a C++ inheriting construction expression.
1466 CXXInheritedCtorInitExpr(SourceLocation Loc, QualType T,
1467 CXXConstructorDecl *Ctor, bool ConstructsVirtualBase,
1468 bool InheritedFromVirtualBase)
1469 : Expr(CXXInheritedCtorInitExprClass, T, VK_RValue, OK_Ordinary, false,
1470 false, false, false),
1471 Constructor(Ctor), Loc(Loc),
1472 ConstructsVirtualBase(ConstructsVirtualBase),
1473 InheritedFromVirtualBase(InheritedFromVirtualBase) {
1474 assert(!T->isDependentType());
1477 /// Construct an empty C++ inheriting construction expression.
1478 explicit CXXInheritedCtorInitExpr(EmptyShell Empty)
1479 : Expr(CXXInheritedCtorInitExprClass, Empty),
1480 ConstructsVirtualBase(false), InheritedFromVirtualBase(false) {}
1482 /// Get the constructor that this expression will call.
1483 CXXConstructorDecl *getConstructor() const { return Constructor; }
1485 /// Determine whether this constructor is actually constructing
1486 /// a base class (rather than a complete object).
1487 bool constructsVBase() const { return ConstructsVirtualBase; }
1488 CXXConstructExpr::ConstructionKind getConstructionKind() const {
1489 return ConstructsVirtualBase ? CXXConstructExpr::CK_VirtualBase
1490 : CXXConstructExpr::CK_NonVirtualBase;
1493 /// Determine whether the inherited constructor is inherited from a
1494 /// virtual base of the object we construct. If so, we are not responsible
1495 /// for calling the inherited constructor (the complete object constructor
1496 /// does that), and so we don't need to pass any arguments.
1497 bool inheritedFromVBase() const { return InheritedFromVirtualBase; }
1499 SourceLocation getLocation() const LLVM_READONLY { return Loc; }
1500 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1501 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1503 static bool classof(const Stmt *T) {
1504 return T->getStmtClass() == CXXInheritedCtorInitExprClass;
1507 child_range children() {
1508 return child_range(child_iterator(), child_iterator());
1512 /// Represents an explicit C++ type conversion that uses "functional"
1513 /// notation (C++ [expr.type.conv]).
1519 class CXXFunctionalCastExpr final
1520 : public ExplicitCastExpr,
1521 private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *> {
1522 SourceLocation LParenLoc;
1523 SourceLocation RParenLoc;
1525 CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1526 TypeSourceInfo *writtenTy,
1527 CastKind kind, Expr *castExpr, unsigned pathSize,
1528 SourceLocation lParenLoc, SourceLocation rParenLoc)
1529 : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
1530 castExpr, pathSize, writtenTy),
1531 LParenLoc(lParenLoc), RParenLoc(rParenLoc) {}
1533 explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
1534 : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) {}
1537 friend class CastExpr;
1538 friend TrailingObjects;
1540 static CXXFunctionalCastExpr *Create(const ASTContext &Context, QualType T,
1542 TypeSourceInfo *Written,
1543 CastKind Kind, Expr *Op,
1544 const CXXCastPath *Path,
1545 SourceLocation LPLoc,
1546 SourceLocation RPLoc);
1547 static CXXFunctionalCastExpr *CreateEmpty(const ASTContext &Context,
1550 SourceLocation getLParenLoc() const { return LParenLoc; }
1551 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1552 SourceLocation getRParenLoc() const { return RParenLoc; }
1553 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1555 /// Determine whether this expression models list-initialization.
1556 bool isListInitialization() const { return LParenLoc.isInvalid(); }
1558 SourceLocation getBeginLoc() const LLVM_READONLY;
1559 SourceLocation getEndLoc() const LLVM_READONLY;
1561 static bool classof(const Stmt *T) {
1562 return T->getStmtClass() == CXXFunctionalCastExprClass;
1566 /// Represents a C++ functional cast expression that builds a
1567 /// temporary object.
1569 /// This expression type represents a C++ "functional" cast
1570 /// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1571 /// constructor to build a temporary object. With N == 1 arguments the
1572 /// functional cast expression will be represented by CXXFunctionalCastExpr.
1575 /// struct X { X(int, float); }
1578 /// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1581 class CXXTemporaryObjectExpr final : public CXXConstructExpr {
1582 friend class ASTStmtReader;
1584 // CXXTemporaryObjectExpr has some trailing objects belonging
1585 // to CXXConstructExpr. See the comment inside CXXConstructExpr
1586 // for more details.
1588 TypeSourceInfo *TSI;
1590 CXXTemporaryObjectExpr(CXXConstructorDecl *Cons, QualType Ty,
1591 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1592 SourceRange ParenOrBraceRange,
1593 bool HadMultipleCandidates, bool ListInitialization,
1594 bool StdInitListInitialization,
1595 bool ZeroInitialization);
1597 CXXTemporaryObjectExpr(EmptyShell Empty, unsigned NumArgs);
1600 static CXXTemporaryObjectExpr *
1601 Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
1602 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1603 SourceRange ParenOrBraceRange, bool HadMultipleCandidates,
1604 bool ListInitialization, bool StdInitListInitialization,
1605 bool ZeroInitialization);
1607 static CXXTemporaryObjectExpr *CreateEmpty(const ASTContext &Ctx,
1610 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
1612 SourceLocation getBeginLoc() const LLVM_READONLY;
1613 SourceLocation getEndLoc() const LLVM_READONLY;
1615 static bool classof(const Stmt *T) {
1616 return T->getStmtClass() == CXXTemporaryObjectExprClass;
1620 Stmt **CXXConstructExpr::getTrailingArgs() {
1621 if (auto *E = dyn_cast<CXXTemporaryObjectExpr>(this))
1622 return reinterpret_cast<Stmt **>(E + 1);
1623 assert((getStmtClass() == CXXConstructExprClass) &&
1624 "Unexpected class deriving from CXXConstructExpr!");
1625 return reinterpret_cast<Stmt **>(this + 1);
1628 /// A C++ lambda expression, which produces a function object
1629 /// (of unspecified type) that can be invoked later.
1633 /// void low_pass_filter(std::vector<double> &values, double cutoff) {
1634 /// values.erase(std::remove_if(values.begin(), values.end(),
1635 /// [=](double value) { return value > cutoff; });
1639 /// C++11 lambda expressions can capture local variables, either by copying
1640 /// the values of those local variables at the time the function
1641 /// object is constructed (not when it is called!) or by holding a
1642 /// reference to the local variable. These captures can occur either
1643 /// implicitly or can be written explicitly between the square
1644 /// brackets ([...]) that start the lambda expression.
1646 /// C++1y introduces a new form of "capture" called an init-capture that
1647 /// includes an initializing expression (rather than capturing a variable),
1648 /// and which can never occur implicitly.
1649 class LambdaExpr final : public Expr,
1650 private llvm::TrailingObjects<LambdaExpr, Stmt *> {
1651 /// The source range that covers the lambda introducer ([...]).
1652 SourceRange IntroducerRange;
1654 /// The source location of this lambda's capture-default ('=' or '&').
1655 SourceLocation CaptureDefaultLoc;
1657 /// The number of captures.
1658 unsigned NumCaptures : 16;
1660 /// The default capture kind, which is a value of type
1661 /// LambdaCaptureDefault.
1662 unsigned CaptureDefault : 2;
1664 /// Whether this lambda had an explicit parameter list vs. an
1665 /// implicit (and empty) parameter list.
1666 unsigned ExplicitParams : 1;
1668 /// Whether this lambda had the result type explicitly specified.
1669 unsigned ExplicitResultType : 1;
1671 /// The location of the closing brace ('}') that completes
1674 /// The location of the brace is also available by looking up the
1675 /// function call operator in the lambda class. However, it is
1676 /// stored here to improve the performance of getSourceRange(), and
1677 /// to avoid having to deserialize the function call operator from a
1678 /// module file just to determine the source range.
1679 SourceLocation ClosingBrace;
1681 /// Construct a lambda expression.
1682 LambdaExpr(QualType T, SourceRange IntroducerRange,
1683 LambdaCaptureDefault CaptureDefault,
1684 SourceLocation CaptureDefaultLoc, ArrayRef<LambdaCapture> Captures,
1685 bool ExplicitParams, bool ExplicitResultType,
1686 ArrayRef<Expr *> CaptureInits, SourceLocation ClosingBrace,
1687 bool ContainsUnexpandedParameterPack);
1689 /// Construct an empty lambda expression.
1690 LambdaExpr(EmptyShell Empty, unsigned NumCaptures)
1691 : Expr(LambdaExprClass, Empty), NumCaptures(NumCaptures),
1692 CaptureDefault(LCD_None), ExplicitParams(false),
1693 ExplicitResultType(false) {
1694 getStoredStmts()[NumCaptures] = nullptr;
1697 Stmt **getStoredStmts() { return getTrailingObjects<Stmt *>(); }
1699 Stmt *const *getStoredStmts() const { return getTrailingObjects<Stmt *>(); }
1702 friend class ASTStmtReader;
1703 friend class ASTStmtWriter;
1704 friend TrailingObjects;
1706 /// Construct a new lambda expression.
1708 Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange,
1709 LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc,
1710 ArrayRef<LambdaCapture> Captures, bool ExplicitParams,
1711 bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1712 SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack);
1714 /// Construct a new lambda expression that will be deserialized from
1715 /// an external source.
1716 static LambdaExpr *CreateDeserialized(const ASTContext &C,
1717 unsigned NumCaptures);
1719 /// Determine the default capture kind for this lambda.
1720 LambdaCaptureDefault getCaptureDefault() const {
1721 return static_cast<LambdaCaptureDefault>(CaptureDefault);
1724 /// Retrieve the location of this lambda's capture-default, if any.
1725 SourceLocation getCaptureDefaultLoc() const {
1726 return CaptureDefaultLoc;
1729 /// Determine whether one of this lambda's captures is an init-capture.
1730 bool isInitCapture(const LambdaCapture *Capture) const;
1732 /// An iterator that walks over the captures of the lambda,
1733 /// both implicit and explicit.
1734 using capture_iterator = const LambdaCapture *;
1736 /// An iterator over a range of lambda captures.
1737 using capture_range = llvm::iterator_range<capture_iterator>;
1739 /// Retrieve this lambda's captures.
1740 capture_range captures() const;
1742 /// Retrieve an iterator pointing to the first lambda capture.
1743 capture_iterator capture_begin() const;
1745 /// Retrieve an iterator pointing past the end of the
1746 /// sequence of lambda captures.
1747 capture_iterator capture_end() const;
1749 /// Determine the number of captures in this lambda.
1750 unsigned capture_size() const { return NumCaptures; }
1752 /// Retrieve this lambda's explicit captures.
1753 capture_range explicit_captures() const;
1755 /// Retrieve an iterator pointing to the first explicit
1757 capture_iterator explicit_capture_begin() const;
1759 /// Retrieve an iterator pointing past the end of the sequence of
1760 /// explicit lambda captures.
1761 capture_iterator explicit_capture_end() const;
1763 /// Retrieve this lambda's implicit captures.
1764 capture_range implicit_captures() const;
1766 /// Retrieve an iterator pointing to the first implicit
1768 capture_iterator implicit_capture_begin() const;
1770 /// Retrieve an iterator pointing past the end of the sequence of
1771 /// implicit lambda captures.
1772 capture_iterator implicit_capture_end() const;
1774 /// Iterator that walks over the capture initialization
1776 using capture_init_iterator = Expr **;
1778 /// Const iterator that walks over the capture initialization
1780 using const_capture_init_iterator = Expr *const *;
1782 /// Retrieve the initialization expressions for this lambda's captures.
1783 llvm::iterator_range<capture_init_iterator> capture_inits() {
1784 return llvm::make_range(capture_init_begin(), capture_init_end());
1787 /// Retrieve the initialization expressions for this lambda's captures.
1788 llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
1789 return llvm::make_range(capture_init_begin(), capture_init_end());
1792 /// Retrieve the first initialization argument for this
1793 /// lambda expression (which initializes the first capture field).
1794 capture_init_iterator capture_init_begin() {
1795 return reinterpret_cast<Expr **>(getStoredStmts());
1798 /// Retrieve the first initialization argument for this
1799 /// lambda expression (which initializes the first capture field).
1800 const_capture_init_iterator capture_init_begin() const {
1801 return reinterpret_cast<Expr *const *>(getStoredStmts());
1804 /// Retrieve the iterator pointing one past the last
1805 /// initialization argument for this lambda expression.
1806 capture_init_iterator capture_init_end() {
1807 return capture_init_begin() + NumCaptures;
1810 /// Retrieve the iterator pointing one past the last
1811 /// initialization argument for this lambda expression.
1812 const_capture_init_iterator capture_init_end() const {
1813 return capture_init_begin() + NumCaptures;
1816 /// Retrieve the source range covering the lambda introducer,
1817 /// which contains the explicit capture list surrounded by square
1818 /// brackets ([...]).
1819 SourceRange getIntroducerRange() const { return IntroducerRange; }
1821 /// Retrieve the class that corresponds to the lambda.
1823 /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
1824 /// captures in its fields and provides the various operations permitted
1825 /// on a lambda (copying, calling).
1826 CXXRecordDecl *getLambdaClass() const;
1828 /// Retrieve the function call operator associated with this
1829 /// lambda expression.
1830 CXXMethodDecl *getCallOperator() const;
1832 /// If this is a generic lambda expression, retrieve the template
1833 /// parameter list associated with it, or else return null.
1834 TemplateParameterList *getTemplateParameterList() const;
1836 /// Whether this is a generic lambda.
1837 bool isGenericLambda() const { return getTemplateParameterList(); }
1839 /// Retrieve the body of the lambda.
1840 CompoundStmt *getBody() const;
1842 /// Determine whether the lambda is mutable, meaning that any
1843 /// captures values can be modified.
1844 bool isMutable() const;
1846 /// Determine whether this lambda has an explicit parameter
1847 /// list vs. an implicit (empty) parameter list.
1848 bool hasExplicitParameters() const { return ExplicitParams; }
1850 /// Whether this lambda had its result type explicitly specified.
1851 bool hasExplicitResultType() const { return ExplicitResultType; }
1853 static bool classof(const Stmt *T) {
1854 return T->getStmtClass() == LambdaExprClass;
1857 SourceLocation getBeginLoc() const LLVM_READONLY {
1858 return IntroducerRange.getBegin();
1861 SourceLocation getEndLoc() const LLVM_READONLY { return ClosingBrace; }
1863 child_range children() {
1864 // Includes initialization exprs plus body stmt
1865 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
1869 /// An expression "T()" which creates a value-initialized rvalue of type
1870 /// T, which is a non-class type. See (C++98 [5.2.3p2]).
1871 class CXXScalarValueInitExpr : public Expr {
1872 friend class ASTStmtReader;
1874 TypeSourceInfo *TypeInfo;
1877 /// Create an explicitly-written scalar-value initialization
1879 CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
1880 SourceLocation RParenLoc)
1881 : Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary, false,
1882 false, Type->isInstantiationDependentType(),
1883 Type->containsUnexpandedParameterPack()),
1884 TypeInfo(TypeInfo) {
1885 CXXScalarValueInitExprBits.RParenLoc = RParenLoc;
1888 explicit CXXScalarValueInitExpr(EmptyShell Shell)
1889 : Expr(CXXScalarValueInitExprClass, Shell) {}
1891 TypeSourceInfo *getTypeSourceInfo() const {
1895 SourceLocation getRParenLoc() const {
1896 return CXXScalarValueInitExprBits.RParenLoc;
1899 SourceLocation getBeginLoc() const LLVM_READONLY;
1900 SourceLocation getEndLoc() const { return getRParenLoc(); }
1902 static bool classof(const Stmt *T) {
1903 return T->getStmtClass() == CXXScalarValueInitExprClass;
1907 child_range children() {
1908 return child_range(child_iterator(), child_iterator());
1912 /// Represents a new-expression for memory allocation and constructor
1913 /// calls, e.g: "new CXXNewExpr(foo)".
1914 class CXXNewExpr final
1916 private llvm::TrailingObjects<CXXNewExpr, Stmt *, SourceRange> {
1917 friend class ASTStmtReader;
1918 friend class ASTStmtWriter;
1919 friend TrailingObjects;
1921 /// Points to the allocation function used.
1922 FunctionDecl *OperatorNew;
1924 /// Points to the deallocation function used in case of error. May be null.
1925 FunctionDecl *OperatorDelete;
1927 /// The allocated type-source information, as written in the source.
1928 TypeSourceInfo *AllocatedTypeInfo;
1930 /// Range of the entire new expression.
1933 /// Source-range of a paren-delimited initializer.
1934 SourceRange DirectInitRange;
1936 // CXXNewExpr is followed by several optional trailing objects.
1937 // They are in order:
1939 // * An optional "Stmt *" for the array size expression.
1940 // Present if and ony if isArray().
1942 // * An optional "Stmt *" for the init expression.
1943 // Present if and only if hasInitializer().
1945 // * An array of getNumPlacementArgs() "Stmt *" for the placement new
1946 // arguments, if any.
1948 // * An optional SourceRange for the range covering the parenthesized type-id
1949 // if the allocated type was expressed as a parenthesized type-id.
1950 // Present if and only if isParenTypeId().
1951 unsigned arraySizeOffset() const { return 0; }
1952 unsigned initExprOffset() const { return arraySizeOffset() + isArray(); }
1953 unsigned placementNewArgsOffset() const {
1954 return initExprOffset() + hasInitializer();
1957 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
1958 return isArray() + hasInitializer() + getNumPlacementArgs();
1961 unsigned numTrailingObjects(OverloadToken<SourceRange>) const {
1962 return isParenTypeId();
1966 enum InitializationStyle {
1967 /// New-expression has no initializer as written.
1970 /// New-expression has a C++98 paren-delimited initializer.
1973 /// New-expression has a C++11 list-initializer.
1978 /// Build a c++ new expression.
1979 CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
1980 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
1981 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
1982 SourceRange TypeIdParens, Expr *ArraySize,
1983 InitializationStyle InitializationStyle, Expr *Initializer,
1984 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
1985 SourceRange DirectInitRange);
1987 /// Build an empty c++ new expression.
1988 CXXNewExpr(EmptyShell Empty, bool IsArray, unsigned NumPlacementArgs,
1989 bool IsParenTypeId);
1992 /// Create a c++ new expression.
1994 Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,
1995 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
1996 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
1997 SourceRange TypeIdParens, Expr *ArraySize,
1998 InitializationStyle InitializationStyle, Expr *Initializer,
1999 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2000 SourceRange DirectInitRange);
2002 /// Create an empty c++ new expression.
2003 static CXXNewExpr *CreateEmpty(const ASTContext &Ctx, bool IsArray,
2004 bool HasInit, unsigned NumPlacementArgs,
2005 bool IsParenTypeId);
2007 QualType getAllocatedType() const {
2008 assert(getType()->isPointerType());
2009 return getType()->getAs<PointerType>()->getPointeeType();
2012 TypeSourceInfo *getAllocatedTypeSourceInfo() const {
2013 return AllocatedTypeInfo;
2016 /// True if the allocation result needs to be null-checked.
2018 /// C++11 [expr.new]p13:
2019 /// If the allocation function returns null, initialization shall
2020 /// not be done, the deallocation function shall not be called,
2021 /// and the value of the new-expression shall be null.
2024 /// If the allocation function is a reserved placement allocation
2025 /// function that returns null, the behavior is undefined.
2027 /// An allocation function is not allowed to return null unless it
2028 /// has a non-throwing exception-specification. The '03 rule is
2029 /// identical except that the definition of a non-throwing
2030 /// exception specification is just "is it throw()?".
2031 bool shouldNullCheckAllocation() const;
2033 FunctionDecl *getOperatorNew() const { return OperatorNew; }
2034 void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
2035 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2036 void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
2038 bool isArray() const { return CXXNewExprBits.IsArray; }
2040 Expr *getArraySize() {
2042 ? cast<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()])
2045 const Expr *getArraySize() const {
2047 ? cast<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()])
2051 unsigned getNumPlacementArgs() const {
2052 return CXXNewExprBits.NumPlacementArgs;
2055 Expr **getPlacementArgs() {
2056 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>() +
2057 placementNewArgsOffset());
2060 Expr *getPlacementArg(unsigned I) {
2061 assert((I < getNumPlacementArgs()) && "Index out of range!");
2062 return getPlacementArgs()[I];
2064 const Expr *getPlacementArg(unsigned I) const {
2065 return const_cast<CXXNewExpr *>(this)->getPlacementArg(I);
2068 bool isParenTypeId() const { return CXXNewExprBits.IsParenTypeId; }
2069 SourceRange getTypeIdParens() const {
2070 return isParenTypeId() ? getTrailingObjects<SourceRange>()[0]
2074 bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
2076 /// Whether this new-expression has any initializer at all.
2077 bool hasInitializer() const {
2078 return CXXNewExprBits.StoredInitializationStyle > 0;
2081 /// The kind of initializer this new-expression has.
2082 InitializationStyle getInitializationStyle() const {
2083 if (CXXNewExprBits.StoredInitializationStyle == 0)
2085 return static_cast<InitializationStyle>(
2086 CXXNewExprBits.StoredInitializationStyle - 1);
2089 /// The initializer of this new-expression.
2090 Expr *getInitializer() {
2091 return hasInitializer()
2092 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2095 const Expr *getInitializer() const {
2096 return hasInitializer()
2097 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2101 /// Returns the CXXConstructExpr from this new-expression, or null.
2102 const CXXConstructExpr *getConstructExpr() const {
2103 return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
2106 /// Indicates whether the required alignment should be implicitly passed to
2107 /// the allocation function.
2108 bool passAlignment() const { return CXXNewExprBits.ShouldPassAlignment; }
2110 /// Answers whether the usual array deallocation function for the
2111 /// allocated type expects the size of the allocation as a
2113 bool doesUsualArrayDeleteWantSize() const {
2114 return CXXNewExprBits.UsualArrayDeleteWantsSize;
2117 using arg_iterator = ExprIterator;
2118 using const_arg_iterator = ConstExprIterator;
2120 llvm::iterator_range<arg_iterator> placement_arguments() {
2121 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2124 llvm::iterator_range<const_arg_iterator> placement_arguments() const {
2125 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2128 arg_iterator placement_arg_begin() {
2129 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2131 arg_iterator placement_arg_end() {
2132 return placement_arg_begin() + getNumPlacementArgs();
2134 const_arg_iterator placement_arg_begin() const {
2135 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2137 const_arg_iterator placement_arg_end() const {
2138 return placement_arg_begin() + getNumPlacementArgs();
2141 using raw_arg_iterator = Stmt **;
2143 raw_arg_iterator raw_arg_begin() { return getTrailingObjects<Stmt *>(); }
2144 raw_arg_iterator raw_arg_end() {
2145 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2147 const_arg_iterator raw_arg_begin() const {
2148 return getTrailingObjects<Stmt *>();
2150 const_arg_iterator raw_arg_end() const {
2151 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2154 SourceLocation getBeginLoc() const { return Range.getBegin(); }
2155 SourceLocation getEndLoc() const { return Range.getEnd(); }
2157 SourceRange getDirectInitRange() const { return DirectInitRange; }
2158 SourceRange getSourceRange() const { return Range; }
2160 static bool classof(const Stmt *T) {
2161 return T->getStmtClass() == CXXNewExprClass;
2165 child_range children() { return child_range(raw_arg_begin(), raw_arg_end()); }
2168 /// Represents a \c delete expression for memory deallocation and
2169 /// destructor calls, e.g. "delete[] pArray".
2170 class CXXDeleteExpr : public Expr {
2171 friend class ASTStmtReader;
2173 /// Points to the operator delete overload that is used. Could be a member.
2174 FunctionDecl *OperatorDelete = nullptr;
2176 /// The pointer expression to be deleted.
2177 Stmt *Argument = nullptr;
2180 CXXDeleteExpr(QualType Ty, bool GlobalDelete, bool ArrayForm,
2181 bool ArrayFormAsWritten, bool UsualArrayDeleteWantsSize,
2182 FunctionDecl *OperatorDelete, Expr *Arg, SourceLocation Loc)
2183 : Expr(CXXDeleteExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
2184 Arg->isInstantiationDependent(),
2185 Arg->containsUnexpandedParameterPack()),
2186 OperatorDelete(OperatorDelete), Argument(Arg) {
2187 CXXDeleteExprBits.GlobalDelete = GlobalDelete;
2188 CXXDeleteExprBits.ArrayForm = ArrayForm;
2189 CXXDeleteExprBits.ArrayFormAsWritten = ArrayFormAsWritten;
2190 CXXDeleteExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;
2191 CXXDeleteExprBits.Loc = Loc;
2194 explicit CXXDeleteExpr(EmptyShell Shell) : Expr(CXXDeleteExprClass, Shell) {}
2196 bool isGlobalDelete() const { return CXXDeleteExprBits.GlobalDelete; }
2197 bool isArrayForm() const { return CXXDeleteExprBits.ArrayForm; }
2198 bool isArrayFormAsWritten() const {
2199 return CXXDeleteExprBits.ArrayFormAsWritten;
2202 /// Answers whether the usual array deallocation function for the
2203 /// allocated type expects the size of the allocation as a
2204 /// parameter. This can be true even if the actual deallocation
2205 /// function that we're using doesn't want a size.
2206 bool doesUsualArrayDeleteWantSize() const {
2207 return CXXDeleteExprBits.UsualArrayDeleteWantsSize;
2210 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2212 Expr *getArgument() { return cast<Expr>(Argument); }
2213 const Expr *getArgument() const { return cast<Expr>(Argument); }
2215 /// Retrieve the type being destroyed.
2217 /// If the type being destroyed is a dependent type which may or may not
2218 /// be a pointer, return an invalid type.
2219 QualType getDestroyedType() const;
2221 SourceLocation getBeginLoc() const { return CXXDeleteExprBits.Loc; }
2222 SourceLocation getEndLoc() const LLVM_READONLY {
2223 return Argument->getEndLoc();
2226 static bool classof(const Stmt *T) {
2227 return T->getStmtClass() == CXXDeleteExprClass;
2231 child_range children() { return child_range(&Argument, &Argument + 1); }
2234 /// Stores the type being destroyed by a pseudo-destructor expression.
2235 class PseudoDestructorTypeStorage {
2236 /// Either the type source information or the name of the type, if
2237 /// it couldn't be resolved due to type-dependence.
2238 llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
2240 /// The starting source location of the pseudo-destructor type.
2241 SourceLocation Location;
2244 PseudoDestructorTypeStorage() = default;
2246 PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
2247 : Type(II), Location(Loc) {}
2249 PseudoDestructorTypeStorage(TypeSourceInfo *Info);
2251 TypeSourceInfo *getTypeSourceInfo() const {
2252 return Type.dyn_cast<TypeSourceInfo *>();
2255 IdentifierInfo *getIdentifier() const {
2256 return Type.dyn_cast<IdentifierInfo *>();
2259 SourceLocation getLocation() const { return Location; }
2262 /// Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
2264 /// A pseudo-destructor is an expression that looks like a member access to a
2265 /// destructor of a scalar type, except that scalar types don't have
2266 /// destructors. For example:
2270 /// void f(int *p) {
2275 /// Pseudo-destructors typically occur when instantiating templates such as:
2278 /// template<typename T>
2279 /// void destroy(T* ptr) {
2284 /// for scalar types. A pseudo-destructor expression has no run-time semantics
2285 /// beyond evaluating the base expression.
2286 class CXXPseudoDestructorExpr : public Expr {
2287 friend class ASTStmtReader;
2289 /// The base expression (that is being destroyed).
2290 Stmt *Base = nullptr;
2292 /// Whether the operator was an arrow ('->'); otherwise, it was a
2296 /// The location of the '.' or '->' operator.
2297 SourceLocation OperatorLoc;
2299 /// The nested-name-specifier that follows the operator, if present.
2300 NestedNameSpecifierLoc QualifierLoc;
2302 /// The type that precedes the '::' in a qualified pseudo-destructor
2304 TypeSourceInfo *ScopeType = nullptr;
2306 /// The location of the '::' in a qualified pseudo-destructor
2308 SourceLocation ColonColonLoc;
2310 /// The location of the '~'.
2311 SourceLocation TildeLoc;
2313 /// The type being destroyed, or its name if we were unable to
2314 /// resolve the name.
2315 PseudoDestructorTypeStorage DestroyedType;
2318 CXXPseudoDestructorExpr(const ASTContext &Context,
2319 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2320 NestedNameSpecifierLoc QualifierLoc,
2321 TypeSourceInfo *ScopeType,
2322 SourceLocation ColonColonLoc,
2323 SourceLocation TildeLoc,
2324 PseudoDestructorTypeStorage DestroyedType);
2326 explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2327 : Expr(CXXPseudoDestructorExprClass, Shell), IsArrow(false) {}
2329 Expr *getBase() const { return cast<Expr>(Base); }
2331 /// Determines whether this member expression actually had
2332 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2334 bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2336 /// Retrieves the nested-name-specifier that qualifies the type name,
2337 /// with source-location information.
2338 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2340 /// If the member name was qualified, retrieves the
2341 /// nested-name-specifier that precedes the member name. Otherwise, returns
2343 NestedNameSpecifier *getQualifier() const {
2344 return QualifierLoc.getNestedNameSpecifier();
2347 /// Determine whether this pseudo-destructor expression was written
2348 /// using an '->' (otherwise, it used a '.').
2349 bool isArrow() const { return IsArrow; }
2351 /// Retrieve the location of the '.' or '->' operator.
2352 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2354 /// Retrieve the scope type in a qualified pseudo-destructor
2357 /// Pseudo-destructor expressions can have extra qualification within them
2358 /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2359 /// Here, if the object type of the expression is (or may be) a scalar type,
2360 /// \p T may also be a scalar type and, therefore, cannot be part of a
2361 /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2362 /// destructor expression.
2363 TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2365 /// Retrieve the location of the '::' in a qualified pseudo-destructor
2367 SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2369 /// Retrieve the location of the '~'.
2370 SourceLocation getTildeLoc() const { return TildeLoc; }
2372 /// Retrieve the source location information for the type
2373 /// being destroyed.
2375 /// This type-source information is available for non-dependent
2376 /// pseudo-destructor expressions and some dependent pseudo-destructor
2377 /// expressions. Returns null if we only have the identifier for a
2378 /// dependent pseudo-destructor expression.
2379 TypeSourceInfo *getDestroyedTypeInfo() const {
2380 return DestroyedType.getTypeSourceInfo();
2383 /// In a dependent pseudo-destructor expression for which we do not
2384 /// have full type information on the destroyed type, provides the name
2385 /// of the destroyed type.
2386 IdentifierInfo *getDestroyedTypeIdentifier() const {
2387 return DestroyedType.getIdentifier();
2390 /// Retrieve the type being destroyed.
2391 QualType getDestroyedType() const;
2393 /// Retrieve the starting location of the type being destroyed.
2394 SourceLocation getDestroyedTypeLoc() const {
2395 return DestroyedType.getLocation();
2398 /// Set the name of destroyed type for a dependent pseudo-destructor
2400 void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2401 DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2404 /// Set the destroyed type.
2405 void setDestroyedType(TypeSourceInfo *Info) {
2406 DestroyedType = PseudoDestructorTypeStorage(Info);
2409 SourceLocation getBeginLoc() const LLVM_READONLY {
2410 return Base->getBeginLoc();
2412 SourceLocation getEndLoc() const LLVM_READONLY;
2414 static bool classof(const Stmt *T) {
2415 return T->getStmtClass() == CXXPseudoDestructorExprClass;
2419 child_range children() { return child_range(&Base, &Base + 1); }
2422 /// A type trait used in the implementation of various C++11 and
2423 /// Library TR1 trait templates.
2426 /// __is_pod(int) == true
2427 /// __is_enum(std::string) == false
2428 /// __is_trivially_constructible(vector<int>, int*, int*)
2430 class TypeTraitExpr final
2432 private llvm::TrailingObjects<TypeTraitExpr, TypeSourceInfo *> {
2433 /// The location of the type trait keyword.
2436 /// The location of the closing parenthesis.
2437 SourceLocation RParenLoc;
2439 // Note: The TypeSourceInfos for the arguments are allocated after the
2442 TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2443 ArrayRef<TypeSourceInfo *> Args,
2444 SourceLocation RParenLoc,
2447 TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) {}
2449 size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
2450 return getNumArgs();
2454 friend class ASTStmtReader;
2455 friend class ASTStmtWriter;
2456 friend TrailingObjects;
2458 /// Create a new type trait expression.
2459 static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2460 SourceLocation Loc, TypeTrait Kind,
2461 ArrayRef<TypeSourceInfo *> Args,
2462 SourceLocation RParenLoc,
2465 static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
2468 /// Determine which type trait this expression uses.
2469 TypeTrait getTrait() const {
2470 return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2473 bool getValue() const {
2474 assert(!isValueDependent());
2475 return TypeTraitExprBits.Value;
2478 /// Determine the number of arguments to this type trait.
2479 unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2481 /// Retrieve the Ith argument.
2482 TypeSourceInfo *getArg(unsigned I) const {
2483 assert(I < getNumArgs() && "Argument out-of-range");
2484 return getArgs()[I];
2487 /// Retrieve the argument types.
2488 ArrayRef<TypeSourceInfo *> getArgs() const {
2489 return llvm::makeArrayRef(getTrailingObjects<TypeSourceInfo *>(),
2493 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2494 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2496 static bool classof(const Stmt *T) {
2497 return T->getStmtClass() == TypeTraitExprClass;
2501 child_range children() {
2502 return child_range(child_iterator(), child_iterator());
2506 /// An Embarcadero array type trait, as used in the implementation of
2507 /// __array_rank and __array_extent.
2511 /// __array_rank(int[10][20]) == 2
2512 /// __array_extent(int, 1) == 20
2514 class ArrayTypeTraitExpr : public Expr {
2515 /// The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2518 /// The value of the type trait. Unspecified if dependent.
2521 /// The array dimension being queried, or -1 if not used.
2524 /// The location of the type trait keyword.
2527 /// The location of the closing paren.
2528 SourceLocation RParen;
2530 /// The type being queried.
2531 TypeSourceInfo *QueriedType = nullptr;
2534 friend class ASTStmtReader;
2536 ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2537 TypeSourceInfo *queried, uint64_t value,
2538 Expr *dimension, SourceLocation rparen, QualType ty)
2539 : Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2540 false, queried->getType()->isDependentType(),
2541 (queried->getType()->isInstantiationDependentType() ||
2542 (dimension && dimension->isInstantiationDependent())),
2543 queried->getType()->containsUnexpandedParameterPack()),
2544 ATT(att), Value(value), Dimension(dimension),
2545 Loc(loc), RParen(rparen), QueriedType(queried) {}
2547 explicit ArrayTypeTraitExpr(EmptyShell Empty)
2548 : Expr(ArrayTypeTraitExprClass, Empty), ATT(0) {}
2550 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2551 SourceLocation getEndLoc() const LLVM_READONLY { return RParen; }
2553 ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2555 QualType getQueriedType() const { return QueriedType->getType(); }
2557 TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2559 uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
2561 Expr *getDimensionExpression() const { return Dimension; }
2563 static bool classof(const Stmt *T) {
2564 return T->getStmtClass() == ArrayTypeTraitExprClass;
2568 child_range children() {
2569 return child_range(child_iterator(), child_iterator());
2573 /// An expression trait intrinsic.
2577 /// __is_lvalue_expr(std::cout) == true
2578 /// __is_lvalue_expr(1) == false
2580 class ExpressionTraitExpr : public Expr {
2581 /// The trait. A ExpressionTrait enum in MSVC compatible unsigned.
2584 /// The value of the type trait. Unspecified if dependent.
2587 /// The location of the type trait keyword.
2590 /// The location of the closing paren.
2591 SourceLocation RParen;
2593 /// The expression being queried.
2594 Expr* QueriedExpression = nullptr;
2597 friend class ASTStmtReader;
2599 ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
2600 Expr *queried, bool value,
2601 SourceLocation rparen, QualType resultType)
2602 : Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2603 false, // Not type-dependent
2604 // Value-dependent if the argument is type-dependent.
2605 queried->isTypeDependent(),
2606 queried->isInstantiationDependent(),
2607 queried->containsUnexpandedParameterPack()),
2608 ET(et), Value(value), Loc(loc), RParen(rparen),
2609 QueriedExpression(queried) {}
2611 explicit ExpressionTraitExpr(EmptyShell Empty)
2612 : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false) {}
2614 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2615 SourceLocation getEndLoc() const LLVM_READONLY { return RParen; }
2617 ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2619 Expr *getQueriedExpression() const { return QueriedExpression; }
2621 bool getValue() const { return Value; }
2623 static bool classof(const Stmt *T) {
2624 return T->getStmtClass() == ExpressionTraitExprClass;
2628 child_range children() {
2629 return child_range(child_iterator(), child_iterator());
2633 /// A reference to an overloaded function set, either an
2634 /// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2635 class OverloadExpr : public Expr {
2636 friend class ASTStmtReader;
2637 friend class ASTStmtWriter;
2639 /// The common name of these declarations.
2640 DeclarationNameInfo NameInfo;
2642 /// The nested-name-specifier that qualifies the name, if any.
2643 NestedNameSpecifierLoc QualifierLoc;
2646 OverloadExpr(StmtClass SC, const ASTContext &Context,
2647 NestedNameSpecifierLoc QualifierLoc,
2648 SourceLocation TemplateKWLoc,
2649 const DeclarationNameInfo &NameInfo,
2650 const TemplateArgumentListInfo *TemplateArgs,
2651 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2652 bool KnownDependent, bool KnownInstantiationDependent,
2653 bool KnownContainsUnexpandedParameterPack);
2655 OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,
2656 bool HasTemplateKWAndArgsInfo);
2658 /// Return the results. Defined after UnresolvedMemberExpr.
2659 inline DeclAccessPair *getTrailingResults();
2660 const DeclAccessPair *getTrailingResults() const {
2661 return const_cast<OverloadExpr *>(this)->getTrailingResults();
2664 /// Return the optional template keyword and arguments info.
2665 /// Defined after UnresolvedMemberExpr.
2666 inline ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo();
2667 const ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo() const {
2668 return const_cast<OverloadExpr *>(this)
2669 ->getTrailingASTTemplateKWAndArgsInfo();
2672 /// Return the optional template arguments. Defined after
2673 /// UnresolvedMemberExpr.
2674 inline TemplateArgumentLoc *getTrailingTemplateArgumentLoc();
2675 const TemplateArgumentLoc *getTrailingTemplateArgumentLoc() const {
2676 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
2679 bool hasTemplateKWAndArgsInfo() const {
2680 return OverloadExprBits.HasTemplateKWAndArgsInfo;
2685 OverloadExpr *Expression;
2686 bool IsAddressOfOperand;
2687 bool HasFormOfMemberPointer;
2690 /// Finds the overloaded expression in the given expression \p E of
2693 /// \return the expression (which must be there) and true if it has
2694 /// the particular form of a member pointer expression
2695 static FindResult find(Expr *E) {
2696 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
2700 E = E->IgnoreParens();
2701 if (isa<UnaryOperator>(E)) {
2702 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
2703 E = cast<UnaryOperator>(E)->getSubExpr();
2704 auto *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2706 Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2707 Result.IsAddressOfOperand = true;
2708 Result.Expression = Ovl;
2710 Result.HasFormOfMemberPointer = false;
2711 Result.IsAddressOfOperand = false;
2712 Result.Expression = cast<OverloadExpr>(E);
2718 /// Gets the naming class of this lookup, if any.
2719 /// Defined after UnresolvedMemberExpr.
2720 inline CXXRecordDecl *getNamingClass();
2721 const CXXRecordDecl *getNamingClass() const {
2722 return const_cast<OverloadExpr *>(this)->getNamingClass();
2725 using decls_iterator = UnresolvedSetImpl::iterator;
2727 decls_iterator decls_begin() const {
2728 return UnresolvedSetIterator(getTrailingResults());
2730 decls_iterator decls_end() const {
2731 return UnresolvedSetIterator(getTrailingResults() + getNumDecls());
2733 llvm::iterator_range<decls_iterator> decls() const {
2734 return llvm::make_range(decls_begin(), decls_end());
2737 /// Gets the number of declarations in the unresolved set.
2738 unsigned getNumDecls() const { return OverloadExprBits.NumResults; }
2740 /// Gets the full name info.
2741 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2743 /// Gets the name looked up.
2744 DeclarationName getName() const { return NameInfo.getName(); }
2746 /// Gets the location of the name.
2747 SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
2749 /// Fetches the nested-name qualifier, if one was given.
2750 NestedNameSpecifier *getQualifier() const {
2751 return QualifierLoc.getNestedNameSpecifier();
2754 /// Fetches the nested-name qualifier with source-location
2755 /// information, if one was given.
2756 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2758 /// Retrieve the location of the template keyword preceding
2759 /// this name, if any.
2760 SourceLocation getTemplateKeywordLoc() const {
2761 if (!hasTemplateKWAndArgsInfo())
2762 return SourceLocation();
2763 return getTrailingASTTemplateKWAndArgsInfo()->TemplateKWLoc;
2766 /// Retrieve the location of the left angle bracket starting the
2767 /// explicit template argument list following the name, if any.
2768 SourceLocation getLAngleLoc() const {
2769 if (!hasTemplateKWAndArgsInfo())
2770 return SourceLocation();
2771 return getTrailingASTTemplateKWAndArgsInfo()->LAngleLoc;
2774 /// Retrieve the location of the right angle bracket ending the
2775 /// explicit template argument list following the name, if any.
2776 SourceLocation getRAngleLoc() const {
2777 if (!hasTemplateKWAndArgsInfo())
2778 return SourceLocation();
2779 return getTrailingASTTemplateKWAndArgsInfo()->RAngleLoc;
2782 /// Determines whether the name was preceded by the template keyword.
2783 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2785 /// Determines whether this expression had explicit template arguments.
2786 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2788 TemplateArgumentLoc const *getTemplateArgs() const {
2789 if (!hasExplicitTemplateArgs())
2791 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
2794 unsigned getNumTemplateArgs() const {
2795 if (!hasExplicitTemplateArgs())
2798 return getTrailingASTTemplateKWAndArgsInfo()->NumTemplateArgs;
2801 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2802 return {getTemplateArgs(), getNumTemplateArgs()};
2805 /// Copies the template arguments into the given structure.
2806 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2807 if (hasExplicitTemplateArgs())
2808 getTrailingASTTemplateKWAndArgsInfo()->copyInto(getTemplateArgs(), List);
2811 static bool classof(const Stmt *T) {
2812 return T->getStmtClass() == UnresolvedLookupExprClass ||
2813 T->getStmtClass() == UnresolvedMemberExprClass;
2817 /// A reference to a name which we were able to look up during
2818 /// parsing but could not resolve to a specific declaration.
2820 /// This arises in several ways:
2821 /// * we might be waiting for argument-dependent lookup;
2822 /// * the name might resolve to an overloaded function;
2824 /// * the lookup might have included a function template.
2826 /// These never include UnresolvedUsingValueDecls, which are always class
2827 /// members and therefore appear only in UnresolvedMemberLookupExprs.
2828 class UnresolvedLookupExpr final
2829 : public OverloadExpr,
2830 private llvm::TrailingObjects<UnresolvedLookupExpr, DeclAccessPair,
2831 ASTTemplateKWAndArgsInfo,
2832 TemplateArgumentLoc> {
2833 friend class ASTStmtReader;
2834 friend class OverloadExpr;
2835 friend TrailingObjects;
2837 /// The naming class (C++ [class.access.base]p5) of the lookup, if
2838 /// any. This can generally be recalculated from the context chain,
2839 /// but that can be fairly expensive for unqualified lookups.
2840 CXXRecordDecl *NamingClass;
2842 // UnresolvedLookupExpr is followed by several trailing objects.
2843 // They are in order:
2845 // * An array of getNumResults() DeclAccessPair for the results. These are
2846 // undesugared, which is to say, they may include UsingShadowDecls.
2847 // Access is relative to the naming class.
2849 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
2850 // template keyword and arguments. Present if and only if
2851 // hasTemplateKWAndArgsInfo().
2853 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
2854 // location information for the explicitly specified template arguments.
2856 UnresolvedLookupExpr(const ASTContext &Context, CXXRecordDecl *NamingClass,
2857 NestedNameSpecifierLoc QualifierLoc,
2858 SourceLocation TemplateKWLoc,
2859 const DeclarationNameInfo &NameInfo, bool RequiresADL,
2861 const TemplateArgumentListInfo *TemplateArgs,
2862 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
2864 UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
2865 bool HasTemplateKWAndArgsInfo);
2867 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
2868 return getNumDecls();
2871 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2872 return hasTemplateKWAndArgsInfo();
2876 static UnresolvedLookupExpr *
2877 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
2878 NestedNameSpecifierLoc QualifierLoc,
2879 const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
2880 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
2882 static UnresolvedLookupExpr *
2883 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
2884 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
2885 const DeclarationNameInfo &NameInfo, bool RequiresADL,
2886 const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
2887 UnresolvedSetIterator End);
2889 static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
2890 unsigned NumResults,
2891 bool HasTemplateKWAndArgsInfo,
2892 unsigned NumTemplateArgs);
2894 /// True if this declaration should be extended by
2895 /// argument-dependent lookup.
2896 bool requiresADL() const { return UnresolvedLookupExprBits.RequiresADL; }
2898 /// True if this lookup is overloaded.
2899 bool isOverloaded() const { return UnresolvedLookupExprBits.Overloaded; }
2901 /// Gets the 'naming class' (in the sense of C++0x
2902 /// [class.access.base]p5) of the lookup. This is the scope
2903 /// that was looked in to find these results.
2904 CXXRecordDecl *getNamingClass() { return NamingClass; }
2905 const CXXRecordDecl *getNamingClass() const { return NamingClass; }
2907 SourceLocation getBeginLoc() const LLVM_READONLY {
2908 if (NestedNameSpecifierLoc l = getQualifierLoc())
2909 return l.getBeginLoc();
2910 return getNameInfo().getBeginLoc();
2913 SourceLocation getEndLoc() const LLVM_READONLY {
2914 if (hasExplicitTemplateArgs())
2915 return getRAngleLoc();
2916 return getNameInfo().getEndLoc();
2919 child_range children() {
2920 return child_range(child_iterator(), child_iterator());
2923 static bool classof(const Stmt *T) {
2924 return T->getStmtClass() == UnresolvedLookupExprClass;
2928 /// A qualified reference to a name whose declaration cannot
2929 /// yet be resolved.
2931 /// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
2932 /// it expresses a reference to a declaration such as
2933 /// X<T>::value. The difference, however, is that an
2934 /// DependentScopeDeclRefExpr node is used only within C++ templates when
2935 /// the qualification (e.g., X<T>::) refers to a dependent type. In
2936 /// this case, X<T>::value cannot resolve to a declaration because the
2937 /// declaration will differ from one instantiation of X<T> to the
2938 /// next. Therefore, DependentScopeDeclRefExpr keeps track of the
2939 /// qualifier (X<T>::) and the name of the entity being referenced
2940 /// ("value"). Such expressions will instantiate to a DeclRefExpr once the
2941 /// declaration can be found.
2942 class DependentScopeDeclRefExpr final
2944 private llvm::TrailingObjects<DependentScopeDeclRefExpr,
2945 ASTTemplateKWAndArgsInfo,
2946 TemplateArgumentLoc> {
2947 friend class ASTStmtReader;
2948 friend class ASTStmtWriter;
2949 friend TrailingObjects;
2951 /// The nested-name-specifier that qualifies this unresolved
2952 /// declaration name.
2953 NestedNameSpecifierLoc QualifierLoc;
2955 /// The name of the entity we will be referencing.
2956 DeclarationNameInfo NameInfo;
2958 DependentScopeDeclRefExpr(QualType Ty, NestedNameSpecifierLoc QualifierLoc,
2959 SourceLocation TemplateKWLoc,
2960 const DeclarationNameInfo &NameInfo,
2961 const TemplateArgumentListInfo *Args);
2963 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2964 return hasTemplateKWAndArgsInfo();
2967 bool hasTemplateKWAndArgsInfo() const {
2968 return DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo;
2972 static DependentScopeDeclRefExpr *
2973 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
2974 SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
2975 const TemplateArgumentListInfo *TemplateArgs);
2977 static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &Context,
2978 bool HasTemplateKWAndArgsInfo,
2979 unsigned NumTemplateArgs);
2981 /// Retrieve the name that this expression refers to.
2982 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2984 /// Retrieve the name that this expression refers to.
2985 DeclarationName getDeclName() const { return NameInfo.getName(); }
2987 /// Retrieve the location of the name within the expression.
2989 /// For example, in "X<T>::value" this is the location of "value".
2990 SourceLocation getLocation() const { return NameInfo.getLoc(); }
2992 /// Retrieve the nested-name-specifier that qualifies the
2993 /// name, with source location information.
2994 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2996 /// Retrieve the nested-name-specifier that qualifies this
2998 NestedNameSpecifier *getQualifier() const {
2999 return QualifierLoc.getNestedNameSpecifier();
3002 /// Retrieve the location of the template keyword preceding
3003 /// this name, if any.
3004 SourceLocation getTemplateKeywordLoc() const {
3005 if (!hasTemplateKWAndArgsInfo())
3006 return SourceLocation();
3007 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3010 /// Retrieve the location of the left angle bracket starting the
3011 /// explicit template argument list following the name, if any.
3012 SourceLocation getLAngleLoc() const {
3013 if (!hasTemplateKWAndArgsInfo())
3014 return SourceLocation();
3015 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3018 /// Retrieve the location of the right angle bracket ending the
3019 /// explicit template argument list following the name, if any.
3020 SourceLocation getRAngleLoc() const {
3021 if (!hasTemplateKWAndArgsInfo())
3022 return SourceLocation();
3023 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3026 /// Determines whether the name was preceded by the template keyword.
3027 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3029 /// Determines whether this lookup had explicit template arguments.
3030 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3032 /// Copies the template arguments (if present) into the given
3034 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3035 if (hasExplicitTemplateArgs())
3036 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3037 getTrailingObjects<TemplateArgumentLoc>(), List);
3040 TemplateArgumentLoc const *getTemplateArgs() const {
3041 if (!hasExplicitTemplateArgs())
3044 return getTrailingObjects<TemplateArgumentLoc>();
3047 unsigned getNumTemplateArgs() const {
3048 if (!hasExplicitTemplateArgs())
3051 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3054 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3055 return {getTemplateArgs(), getNumTemplateArgs()};
3058 /// Note: getBeginLoc() is the start of the whole DependentScopeDeclRefExpr,
3059 /// and differs from getLocation().getStart().
3060 SourceLocation getBeginLoc() const LLVM_READONLY {
3061 return QualifierLoc.getBeginLoc();
3064 SourceLocation getEndLoc() const LLVM_READONLY {
3065 if (hasExplicitTemplateArgs())
3066 return getRAngleLoc();
3067 return getLocation();
3070 static bool classof(const Stmt *T) {
3071 return T->getStmtClass() == DependentScopeDeclRefExprClass;
3074 child_range children() {
3075 return child_range(child_iterator(), child_iterator());
3079 /// Represents an expression -- generally a full-expression -- that
3080 /// introduces cleanups to be run at the end of the sub-expression's
3081 /// evaluation. The most common source of expression-introduced
3082 /// cleanups is temporary objects in C++, but several other kinds of
3083 /// expressions can create cleanups, including basically every
3084 /// call in ARC that returns an Objective-C pointer.
3086 /// This expression also tracks whether the sub-expression contains a
3087 /// potentially-evaluated block literal. The lifetime of a block
3088 /// literal is the extent of the enclosing scope.
3089 class ExprWithCleanups final
3091 private llvm::TrailingObjects<ExprWithCleanups, BlockDecl *> {
3093 /// The type of objects that are kept in the cleanup.
3094 /// It's useful to remember the set of blocks; we could also
3095 /// remember the set of temporaries, but there's currently
3097 using CleanupObject = BlockDecl *;
3100 friend class ASTStmtReader;
3101 friend TrailingObjects;
3103 ExprWithCleanups(EmptyShell, unsigned NumObjects);
3104 ExprWithCleanups(Expr *SubExpr, bool CleanupsHaveSideEffects,
3105 ArrayRef<CleanupObject> Objects);
3108 static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
3109 unsigned numObjects);
3111 static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
3112 bool CleanupsHaveSideEffects,
3113 ArrayRef<CleanupObject> objects);
3115 ArrayRef<CleanupObject> getObjects() const {
3116 return llvm::makeArrayRef(getTrailingObjects<CleanupObject>(),
3120 unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
3122 CleanupObject getObject(unsigned i) const {
3123 assert(i < getNumObjects() && "Index out of range");
3124 return getObjects()[i];
3127 bool cleanupsHaveSideEffects() const {
3128 return ExprWithCleanupsBits.CleanupsHaveSideEffects;
3131 SourceLocation getBeginLoc() const LLVM_READONLY {
3132 return SubExpr->getBeginLoc();
3135 SourceLocation getEndLoc() const LLVM_READONLY {
3136 return SubExpr->getEndLoc();
3139 // Implement isa/cast/dyncast/etc.
3140 static bool classof(const Stmt *T) {
3141 return T->getStmtClass() == ExprWithCleanupsClass;
3145 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
3148 /// Describes an explicit type conversion that uses functional
3149 /// notion but could not be resolved because one or more arguments are
3152 /// The explicit type conversions expressed by
3153 /// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
3154 /// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
3155 /// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
3156 /// type-dependent. For example, this would occur in a template such
3160 /// template<typename T, typename A1>
3161 /// inline T make_a(const A1& a1) {
3166 /// When the returned expression is instantiated, it may resolve to a
3167 /// constructor call, conversion function call, or some kind of type
3169 class CXXUnresolvedConstructExpr final
3171 private llvm::TrailingObjects<CXXUnresolvedConstructExpr, Expr *> {
3172 friend class ASTStmtReader;
3173 friend TrailingObjects;
3175 /// The type being constructed.
3176 TypeSourceInfo *TSI;
3178 /// The location of the left parentheses ('(').
3179 SourceLocation LParenLoc;
3181 /// The location of the right parentheses (')').
3182 SourceLocation RParenLoc;
3184 CXXUnresolvedConstructExpr(TypeSourceInfo *TSI, SourceLocation LParenLoc,
3185 ArrayRef<Expr *> Args, SourceLocation RParenLoc);
3187 CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
3188 : Expr(CXXUnresolvedConstructExprClass, Empty) {
3189 CXXUnresolvedConstructExprBits.NumArgs = NumArgs;
3193 static CXXUnresolvedConstructExpr *Create(const ASTContext &Context,
3194 TypeSourceInfo *Type,
3195 SourceLocation LParenLoc,
3196 ArrayRef<Expr *> Args,
3197 SourceLocation RParenLoc);
3199 static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &Context,
3202 /// Retrieve the type that is being constructed, as specified
3203 /// in the source code.
3204 QualType getTypeAsWritten() const { return TSI->getType(); }
3206 /// Retrieve the type source information for the type being
3208 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
3210 /// Retrieve the location of the left parentheses ('(') that
3211 /// precedes the argument list.
3212 SourceLocation getLParenLoc() const { return LParenLoc; }
3213 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3215 /// Retrieve the location of the right parentheses (')') that
3216 /// follows the argument list.
3217 SourceLocation getRParenLoc() const { return RParenLoc; }
3218 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3220 /// Determine whether this expression models list-initialization.
3221 /// If so, there will be exactly one subexpression, which will be
3222 /// an InitListExpr.
3223 bool isListInitialization() const { return LParenLoc.isInvalid(); }
3225 /// Retrieve the number of arguments.
3226 unsigned arg_size() const { return CXXUnresolvedConstructExprBits.NumArgs; }
3228 using arg_iterator = Expr **;
3229 using arg_range = llvm::iterator_range<arg_iterator>;
3231 arg_iterator arg_begin() { return getTrailingObjects<Expr *>(); }
3232 arg_iterator arg_end() { return arg_begin() + arg_size(); }
3233 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3235 using const_arg_iterator = const Expr* const *;
3236 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
3238 const_arg_iterator arg_begin() const { return getTrailingObjects<Expr *>(); }
3239 const_arg_iterator arg_end() const { return arg_begin() + arg_size(); }
3240 const_arg_range arguments() const {
3241 return const_arg_range(arg_begin(), arg_end());
3244 Expr *getArg(unsigned I) {
3245 assert(I < arg_size() && "Argument index out-of-range");
3246 return arg_begin()[I];
3249 const Expr *getArg(unsigned I) const {
3250 assert(I < arg_size() && "Argument index out-of-range");
3251 return arg_begin()[I];
3254 void setArg(unsigned I, Expr *E) {
3255 assert(I < arg_size() && "Argument index out-of-range");
3259 SourceLocation getBeginLoc() const LLVM_READONLY;
3260 SourceLocation getEndLoc() const LLVM_READONLY {
3261 if (!RParenLoc.isValid() && arg_size() > 0)
3262 return getArg(arg_size() - 1)->getEndLoc();
3266 static bool classof(const Stmt *T) {
3267 return T->getStmtClass() == CXXUnresolvedConstructExprClass;
3271 child_range children() {
3272 auto **begin = reinterpret_cast<Stmt **>(arg_begin());
3273 return child_range(begin, begin + arg_size());
3277 /// Represents a C++ member access expression where the actual
3278 /// member referenced could not be resolved because the base
3279 /// expression or the member name was dependent.
3281 /// Like UnresolvedMemberExprs, these can be either implicit or
3282 /// explicit accesses. It is only possible to get one of these with
3283 /// an implicit access if a qualifier is provided.
3284 class CXXDependentScopeMemberExpr final
3286 private llvm::TrailingObjects<CXXDependentScopeMemberExpr,
3287 ASTTemplateKWAndArgsInfo,
3288 TemplateArgumentLoc, NamedDecl *> {
3289 friend class ASTStmtReader;
3290 friend class ASTStmtWriter;
3291 friend TrailingObjects;
3293 /// The expression for the base pointer or class reference,
3294 /// e.g., the \c x in x.f. Can be null in implicit accesses.
3297 /// The type of the base expression. Never null, even for
3298 /// implicit accesses.
3301 /// The nested-name-specifier that precedes the member name, if any.
3302 /// FIXME: This could be in principle store as a trailing object.
3303 /// However the performance impact of doing so should be investigated first.
3304 NestedNameSpecifierLoc QualifierLoc;
3306 /// The member to which this member expression refers, which
3307 /// can be name, overloaded operator, or destructor.
3309 /// FIXME: could also be a template-id
3310 DeclarationNameInfo MemberNameInfo;
3312 // CXXDependentScopeMemberExpr is followed by several trailing objects,
3313 // some of which optional. They are in order:
3315 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3316 // template keyword and arguments. Present if and only if
3317 // hasTemplateKWAndArgsInfo().
3319 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing location
3320 // information for the explicitly specified template arguments.
3322 // * An optional NamedDecl *. In a qualified member access expression such
3323 // as t->Base::f, this member stores the resolves of name lookup in the
3324 // context of the member access expression, to be used at instantiation
3325 // time. Present if and only if hasFirstQualifierFoundInScope().
3327 bool hasTemplateKWAndArgsInfo() const {
3328 return CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo;
3331 bool hasFirstQualifierFoundInScope() const {
3332 return CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope;
3335 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3336 return hasTemplateKWAndArgsInfo();
3339 unsigned numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
3340 return getNumTemplateArgs();
3343 unsigned numTrailingObjects(OverloadToken<NamedDecl *>) const {
3344 return hasFirstQualifierFoundInScope();
3347 CXXDependentScopeMemberExpr(const ASTContext &Ctx, Expr *Base,
3348 QualType BaseType, bool IsArrow,
3349 SourceLocation OperatorLoc,
3350 NestedNameSpecifierLoc QualifierLoc,
3351 SourceLocation TemplateKWLoc,
3352 NamedDecl *FirstQualifierFoundInScope,
3353 DeclarationNameInfo MemberNameInfo,
3354 const TemplateArgumentListInfo *TemplateArgs);
3356 CXXDependentScopeMemberExpr(EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
3357 bool HasFirstQualifierFoundInScope);
3360 static CXXDependentScopeMemberExpr *
3361 Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
3362 SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
3363 SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
3364 DeclarationNameInfo MemberNameInfo,
3365 const TemplateArgumentListInfo *TemplateArgs);
3367 static CXXDependentScopeMemberExpr *
3368 CreateEmpty(const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
3369 unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope);
3371 /// True if this is an implicit access, i.e. one in which the
3372 /// member being accessed was not written in the source. The source
3373 /// location of the operator is invalid in this case.
3374 bool isImplicitAccess() const {
3377 return cast<Expr>(Base)->isImplicitCXXThis();
3380 /// Retrieve the base object of this member expressions,
3381 /// e.g., the \c x in \c x.m.
3382 Expr *getBase() const {
3383 assert(!isImplicitAccess());
3384 return cast<Expr>(Base);
3387 QualType getBaseType() const { return BaseType; }
3389 /// Determine whether this member expression used the '->'
3390 /// operator; otherwise, it used the '.' operator.
3391 bool isArrow() const { return CXXDependentScopeMemberExprBits.IsArrow; }
3393 /// Retrieve the location of the '->' or '.' operator.
3394 SourceLocation getOperatorLoc() const {
3395 return CXXDependentScopeMemberExprBits.OperatorLoc;
3398 /// Retrieve the nested-name-specifier that qualifies the member name.
3399 NestedNameSpecifier *getQualifier() const {
3400 return QualifierLoc.getNestedNameSpecifier();
3403 /// Retrieve the nested-name-specifier that qualifies the member
3404 /// name, with source location information.
3405 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3407 /// Retrieve the first part of the nested-name-specifier that was
3408 /// found in the scope of the member access expression when the member access
3409 /// was initially parsed.
3411 /// This function only returns a useful result when member access expression
3412 /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
3413 /// returned by this function describes what was found by unqualified name
3414 /// lookup for the identifier "Base" within the scope of the member access
3415 /// expression itself. At template instantiation time, this information is
3416 /// combined with the results of name lookup into the type of the object
3417 /// expression itself (the class type of x).
3418 NamedDecl *getFirstQualifierFoundInScope() const {
3419 if (!hasFirstQualifierFoundInScope())
3421 return *getTrailingObjects<NamedDecl *>();
3424 /// Retrieve the name of the member that this expression refers to.
3425 const DeclarationNameInfo &getMemberNameInfo() const {
3426 return MemberNameInfo;
3429 /// Retrieve the name of the member that this expression refers to.
3430 DeclarationName getMember() const { return MemberNameInfo.getName(); }
3432 // Retrieve the location of the name of the member that this
3433 // expression refers to.
3434 SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
3436 /// Retrieve the location of the template keyword preceding the
3437 /// member name, if any.
3438 SourceLocation getTemplateKeywordLoc() const {
3439 if (!hasTemplateKWAndArgsInfo())
3440 return SourceLocation();
3441 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3444 /// Retrieve the location of the left angle bracket starting the
3445 /// explicit template argument list following the member name, if any.
3446 SourceLocation getLAngleLoc() const {
3447 if (!hasTemplateKWAndArgsInfo())
3448 return SourceLocation();
3449 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3452 /// Retrieve the location of the right angle bracket ending the
3453 /// explicit template argument list following the member name, if any.
3454 SourceLocation getRAngleLoc() const {
3455 if (!hasTemplateKWAndArgsInfo())
3456 return SourceLocation();
3457 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3460 /// Determines whether the member name was preceded by the template keyword.
3461 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3463 /// Determines whether this member expression actually had a C++
3464 /// template argument list explicitly specified, e.g., x.f<int>.
3465 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3467 /// Copies the template arguments (if present) into the given
3469 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3470 if (hasExplicitTemplateArgs())
3471 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3472 getTrailingObjects<TemplateArgumentLoc>(), List);
3475 /// Retrieve the template arguments provided as part of this
3477 const TemplateArgumentLoc *getTemplateArgs() const {
3478 if (!hasExplicitTemplateArgs())
3481 return getTrailingObjects<TemplateArgumentLoc>();
3484 /// Retrieve the number of template arguments provided as part of this
3486 unsigned getNumTemplateArgs() const {
3487 if (!hasExplicitTemplateArgs())
3490 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3493 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3494 return {getTemplateArgs(), getNumTemplateArgs()};
3497 SourceLocation getBeginLoc() const LLVM_READONLY {
3498 if (!isImplicitAccess())
3499 return Base->getBeginLoc();
3501 return getQualifierLoc().getBeginLoc();
3502 return MemberNameInfo.getBeginLoc();
3505 SourceLocation getEndLoc() const LLVM_READONLY {
3506 if (hasExplicitTemplateArgs())
3507 return getRAngleLoc();
3508 return MemberNameInfo.getEndLoc();
3511 static bool classof(const Stmt *T) {
3512 return T->getStmtClass() == CXXDependentScopeMemberExprClass;
3516 child_range children() {
3517 if (isImplicitAccess())
3518 return child_range(child_iterator(), child_iterator());
3519 return child_range(&Base, &Base + 1);
3523 /// Represents a C++ member access expression for which lookup
3524 /// produced a set of overloaded functions.
3526 /// The member access may be explicit or implicit:
3530 /// int explicitAccess() { return this->a + this->A::b; }
3531 /// int implicitAccess() { return a + A::b; }
3535 /// In the final AST, an explicit access always becomes a MemberExpr.
3536 /// An implicit access may become either a MemberExpr or a
3537 /// DeclRefExpr, depending on whether the member is static.
3538 class UnresolvedMemberExpr final
3539 : public OverloadExpr,
3540 private llvm::TrailingObjects<UnresolvedMemberExpr, DeclAccessPair,
3541 ASTTemplateKWAndArgsInfo,
3542 TemplateArgumentLoc> {
3543 friend class ASTStmtReader;
3544 friend class OverloadExpr;
3545 friend TrailingObjects;
3547 /// The expression for the base pointer or class reference,
3548 /// e.g., the \c x in x.f.
3550 /// This can be null if this is an 'unbased' member expression.
3553 /// The type of the base expression; never null.
3556 /// The location of the '->' or '.' operator.
3557 SourceLocation OperatorLoc;
3559 // UnresolvedMemberExpr is followed by several trailing objects.
3560 // They are in order:
3562 // * An array of getNumResults() DeclAccessPair for the results. These are
3563 // undesugared, which is to say, they may include UsingShadowDecls.
3564 // Access is relative to the naming class.
3566 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3567 // template keyword and arguments. Present if and only if
3568 // hasTemplateKWAndArgsInfo().
3570 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
3571 // location information for the explicitly specified template arguments.
3573 UnresolvedMemberExpr(const ASTContext &Context, bool HasUnresolvedUsing,
3574 Expr *Base, QualType BaseType, bool IsArrow,
3575 SourceLocation OperatorLoc,
3576 NestedNameSpecifierLoc QualifierLoc,
3577 SourceLocation TemplateKWLoc,
3578 const DeclarationNameInfo &MemberNameInfo,
3579 const TemplateArgumentListInfo *TemplateArgs,
3580 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3582 UnresolvedMemberExpr(EmptyShell Empty, unsigned NumResults,
3583 bool HasTemplateKWAndArgsInfo);
3585 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3586 return getNumDecls();
3589 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3590 return hasTemplateKWAndArgsInfo();
3594 static UnresolvedMemberExpr *
3595 Create(const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
3596 QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
3597 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3598 const DeclarationNameInfo &MemberNameInfo,
3599 const TemplateArgumentListInfo *TemplateArgs,
3600 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3602 static UnresolvedMemberExpr *CreateEmpty(const ASTContext &Context,
3603 unsigned NumResults,
3604 bool HasTemplateKWAndArgsInfo,
3605 unsigned NumTemplateArgs);
3607 /// True if this is an implicit access, i.e., one in which the
3608 /// member being accessed was not written in the source.
3610 /// The source location of the operator is invalid in this case.
3611 bool isImplicitAccess() const;
3613 /// Retrieve the base object of this member expressions,
3614 /// e.g., the \c x in \c x.m.
3616 assert(!isImplicitAccess());
3617 return cast<Expr>(Base);
3619 const Expr *getBase() const {
3620 assert(!isImplicitAccess());
3621 return cast<Expr>(Base);
3624 QualType getBaseType() const { return BaseType; }
3626 /// Determine whether the lookup results contain an unresolved using
3628 bool hasUnresolvedUsing() const {
3629 return UnresolvedMemberExprBits.HasUnresolvedUsing;
3632 /// Determine whether this member expression used the '->'
3633 /// operator; otherwise, it used the '.' operator.
3634 bool isArrow() const { return UnresolvedMemberExprBits.IsArrow; }
3636 /// Retrieve the location of the '->' or '.' operator.
3637 SourceLocation getOperatorLoc() const { return OperatorLoc; }
3639 /// Retrieve the naming class of this lookup.
3640 CXXRecordDecl *getNamingClass();
3641 const CXXRecordDecl *getNamingClass() const {
3642 return const_cast<UnresolvedMemberExpr *>(this)->getNamingClass();
3645 /// Retrieve the full name info for the member that this expression
3647 const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
3649 /// Retrieve the name of the member that this expression refers to.
3650 DeclarationName getMemberName() const { return getName(); }
3652 /// Retrieve the location of the name of the member that this
3653 /// expression refers to.
3654 SourceLocation getMemberLoc() const { return getNameLoc(); }
3656 /// Return the preferred location (the member name) for the arrow when
3657 /// diagnosing a problem with this expression.
3658 SourceLocation getExprLoc() const LLVM_READONLY { return getMemberLoc(); }
3660 SourceLocation getBeginLoc() const LLVM_READONLY {
3661 if (!isImplicitAccess())
3662 return Base->getBeginLoc();
3663 if (NestedNameSpecifierLoc l = getQualifierLoc())
3664 return l.getBeginLoc();
3665 return getMemberNameInfo().getBeginLoc();
3668 SourceLocation getEndLoc() const LLVM_READONLY {
3669 if (hasExplicitTemplateArgs())
3670 return getRAngleLoc();
3671 return getMemberNameInfo().getEndLoc();
3674 static bool classof(const Stmt *T) {
3675 return T->getStmtClass() == UnresolvedMemberExprClass;
3679 child_range children() {
3680 if (isImplicitAccess())
3681 return child_range(child_iterator(), child_iterator());
3682 return child_range(&Base, &Base + 1);
3686 DeclAccessPair *OverloadExpr::getTrailingResults() {
3687 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3688 return ULE->getTrailingObjects<DeclAccessPair>();
3689 return cast<UnresolvedMemberExpr>(this)->getTrailingObjects<DeclAccessPair>();
3692 ASTTemplateKWAndArgsInfo *OverloadExpr::getTrailingASTTemplateKWAndArgsInfo() {
3693 if (!hasTemplateKWAndArgsInfo())
3696 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3697 return ULE->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3698 return cast<UnresolvedMemberExpr>(this)
3699 ->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3702 TemplateArgumentLoc *OverloadExpr::getTrailingTemplateArgumentLoc() {
3703 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3704 return ULE->getTrailingObjects<TemplateArgumentLoc>();
3705 return cast<UnresolvedMemberExpr>(this)
3706 ->getTrailingObjects<TemplateArgumentLoc>();
3709 CXXRecordDecl *OverloadExpr::getNamingClass() {
3710 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3711 return ULE->getNamingClass();
3712 return cast<UnresolvedMemberExpr>(this)->getNamingClass();
3715 /// Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
3717 /// The noexcept expression tests whether a given expression might throw. Its
3718 /// result is a boolean constant.
3719 class CXXNoexceptExpr : public Expr {
3720 friend class ASTStmtReader;
3726 CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
3727 SourceLocation Keyword, SourceLocation RParen)
3728 : Expr(CXXNoexceptExprClass, Ty, VK_RValue, OK_Ordinary,
3729 /*TypeDependent*/ false,
3730 /*ValueDependent*/ Val == CT_Dependent,
3731 Val == CT_Dependent || Operand->isInstantiationDependent(),
3732 Operand->containsUnexpandedParameterPack()),
3733 Operand(Operand), Range(Keyword, RParen) {
3734 CXXNoexceptExprBits.Value = Val == CT_Cannot;
3737 CXXNoexceptExpr(EmptyShell Empty) : Expr(CXXNoexceptExprClass, Empty) {}
3739 Expr *getOperand() const { return static_cast<Expr *>(Operand); }
3741 SourceLocation getBeginLoc() const { return Range.getBegin(); }
3742 SourceLocation getEndLoc() const { return Range.getEnd(); }
3743 SourceRange getSourceRange() const { return Range; }
3745 bool getValue() const { return CXXNoexceptExprBits.Value; }
3747 static bool classof(const Stmt *T) {
3748 return T->getStmtClass() == CXXNoexceptExprClass;
3752 child_range children() { return child_range(&Operand, &Operand + 1); }
3755 /// Represents a C++11 pack expansion that produces a sequence of
3758 /// A pack expansion expression contains a pattern (which itself is an
3759 /// expression) followed by an ellipsis. For example:
3762 /// template<typename F, typename ...Types>
3763 /// void forward(F f, Types &&...args) {
3764 /// f(static_cast<Types&&>(args)...);
3768 /// Here, the argument to the function object \c f is a pack expansion whose
3769 /// pattern is \c static_cast<Types&&>(args). When the \c forward function
3770 /// template is instantiated, the pack expansion will instantiate to zero or
3771 /// or more function arguments to the function object \c f.
3772 class PackExpansionExpr : public Expr {
3773 friend class ASTStmtReader;
3774 friend class ASTStmtWriter;
3776 SourceLocation EllipsisLoc;
3778 /// The number of expansions that will be produced by this pack
3779 /// expansion expression, if known.
3781 /// When zero, the number of expansions is not known. Otherwise, this value
3782 /// is the number of expansions + 1.
3783 unsigned NumExpansions;
3788 PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
3789 Optional<unsigned> NumExpansions)
3790 : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
3791 Pattern->getObjectKind(), /*TypeDependent=*/true,
3792 /*ValueDependent=*/true, /*InstantiationDependent=*/true,
3793 /*ContainsUnexpandedParameterPack=*/false),
3794 EllipsisLoc(EllipsisLoc),
3795 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0),
3798 PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) {}
3800 /// Retrieve the pattern of the pack expansion.
3801 Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
3803 /// Retrieve the pattern of the pack expansion.
3804 const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
3806 /// Retrieve the location of the ellipsis that describes this pack
3808 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
3810 /// Determine the number of expansions that will be produced when
3811 /// this pack expansion is instantiated, if already known.
3812 Optional<unsigned> getNumExpansions() const {
3814 return NumExpansions - 1;
3819 SourceLocation getBeginLoc() const LLVM_READONLY {
3820 return Pattern->getBeginLoc();
3823 SourceLocation getEndLoc() const LLVM_READONLY { return EllipsisLoc; }
3825 static bool classof(const Stmt *T) {
3826 return T->getStmtClass() == PackExpansionExprClass;
3830 child_range children() {
3831 return child_range(&Pattern, &Pattern + 1);
3835 /// Represents an expression that computes the length of a parameter
3839 /// template<typename ...Types>
3841 /// static const unsigned value = sizeof...(Types);
3844 class SizeOfPackExpr final
3846 private llvm::TrailingObjects<SizeOfPackExpr, TemplateArgument> {
3847 friend class ASTStmtReader;
3848 friend class ASTStmtWriter;
3849 friend TrailingObjects;
3851 /// The location of the \c sizeof keyword.
3852 SourceLocation OperatorLoc;
3854 /// The location of the name of the parameter pack.
3855 SourceLocation PackLoc;
3857 /// The location of the closing parenthesis.
3858 SourceLocation RParenLoc;
3860 /// The length of the parameter pack, if known.
3862 /// When this expression is not value-dependent, this is the length of
3863 /// the pack. When the expression was parsed rather than instantiated
3864 /// (and thus is value-dependent), this is zero.
3866 /// After partial substitution into a sizeof...(X) expression (for instance,
3867 /// within an alias template or during function template argument deduction),
3868 /// we store a trailing array of partially-substituted TemplateArguments,
3869 /// and this is the length of that array.
3872 /// The parameter pack.
3873 NamedDecl *Pack = nullptr;
3875 /// Create an expression that computes the length of
3876 /// the given parameter pack.
3877 SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
3878 SourceLocation PackLoc, SourceLocation RParenLoc,
3879 Optional<unsigned> Length, ArrayRef<TemplateArgument> PartialArgs)
3880 : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
3881 /*TypeDependent=*/false, /*ValueDependent=*/!Length,
3882 /*InstantiationDependent=*/!Length,
3883 /*ContainsUnexpandedParameterPack=*/false),
3884 OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
3885 Length(Length ? *Length : PartialArgs.size()), Pack(Pack) {
3886 assert((!Length || PartialArgs.empty()) &&
3887 "have partial args for non-dependent sizeof... expression");
3888 auto *Args = getTrailingObjects<TemplateArgument>();
3889 std::uninitialized_copy(PartialArgs.begin(), PartialArgs.end(), Args);
3892 /// Create an empty expression.
3893 SizeOfPackExpr(EmptyShell Empty, unsigned NumPartialArgs)
3894 : Expr(SizeOfPackExprClass, Empty), Length(NumPartialArgs) {}
3897 static SizeOfPackExpr *Create(ASTContext &Context, SourceLocation OperatorLoc,
3898 NamedDecl *Pack, SourceLocation PackLoc,
3899 SourceLocation RParenLoc,
3900 Optional<unsigned> Length = None,
3901 ArrayRef<TemplateArgument> PartialArgs = None);
3902 static SizeOfPackExpr *CreateDeserialized(ASTContext &Context,
3903 unsigned NumPartialArgs);
3905 /// Determine the location of the 'sizeof' keyword.
3906 SourceLocation getOperatorLoc() const { return OperatorLoc; }
3908 /// Determine the location of the parameter pack.
3909 SourceLocation getPackLoc() const { return PackLoc; }
3911 /// Determine the location of the right parenthesis.
3912 SourceLocation getRParenLoc() const { return RParenLoc; }
3914 /// Retrieve the parameter pack.
3915 NamedDecl *getPack() const { return Pack; }
3917 /// Retrieve the length of the parameter pack.
3919 /// This routine may only be invoked when the expression is not
3920 /// value-dependent.
3921 unsigned getPackLength() const {
3922 assert(!isValueDependent() &&
3923 "Cannot get the length of a value-dependent pack size expression");
3927 /// Determine whether this represents a partially-substituted sizeof...
3928 /// expression, such as is produced for:
3930 /// template<typename ...Ts> using X = int[sizeof...(Ts)];
3931 /// template<typename ...Us> void f(X<Us..., 1, 2, 3, Us...>);
3932 bool isPartiallySubstituted() const {
3933 return isValueDependent() && Length;
3937 ArrayRef<TemplateArgument> getPartialArguments() const {
3938 assert(isPartiallySubstituted());
3939 const auto *Args = getTrailingObjects<TemplateArgument>();
3940 return llvm::makeArrayRef(Args, Args + Length);
3943 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
3944 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3946 static bool classof(const Stmt *T) {
3947 return T->getStmtClass() == SizeOfPackExprClass;
3951 child_range children() {
3952 return child_range(child_iterator(), child_iterator());
3956 /// Represents a reference to a non-type template parameter
3957 /// that has been substituted with a template argument.
3958 class SubstNonTypeTemplateParmExpr : public Expr {
3959 friend class ASTReader;
3960 friend class ASTStmtReader;
3962 /// The replaced parameter.
3963 NonTypeTemplateParmDecl *Param;
3965 /// The replacement expression.
3968 explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
3969 : Expr(SubstNonTypeTemplateParmExprClass, Empty) {}
3972 SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind,
3974 NonTypeTemplateParmDecl *Param,
3976 : Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary,
3977 Replacement->isTypeDependent(), Replacement->isValueDependent(),
3978 Replacement->isInstantiationDependent(),
3979 Replacement->containsUnexpandedParameterPack()),
3980 Param(Param), Replacement(Replacement) {
3981 SubstNonTypeTemplateParmExprBits.NameLoc = Loc;
3984 SourceLocation getNameLoc() const {
3985 return SubstNonTypeTemplateParmExprBits.NameLoc;
3987 SourceLocation getBeginLoc() const { return getNameLoc(); }
3988 SourceLocation getEndLoc() const { return getNameLoc(); }
3990 Expr *getReplacement() const { return cast<Expr>(Replacement); }
3992 NonTypeTemplateParmDecl *getParameter() const { return Param; }
3994 static bool classof(const Stmt *s) {
3995 return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
3999 child_range children() { return child_range(&Replacement, &Replacement + 1); }
4002 /// Represents a reference to a non-type template parameter pack that
4003 /// has been substituted with a non-template argument pack.
4005 /// When a pack expansion in the source code contains multiple parameter packs
4006 /// and those parameter packs correspond to different levels of template
4007 /// parameter lists, this node is used to represent a non-type template
4008 /// parameter pack from an outer level, which has already had its argument pack
4009 /// substituted but that still lives within a pack expansion that itself
4010 /// could not be instantiated. When actually performing a substitution into
4011 /// that pack expansion (e.g., when all template parameters have corresponding
4012 /// arguments), this type will be replaced with the appropriate underlying
4013 /// expression at the current pack substitution index.
4014 class SubstNonTypeTemplateParmPackExpr : public Expr {
4015 friend class ASTReader;
4016 friend class ASTStmtReader;
4018 /// The non-type template parameter pack itself.
4019 NonTypeTemplateParmDecl *Param;
4021 /// A pointer to the set of template arguments that this
4022 /// parameter pack is instantiated with.
4023 const TemplateArgument *Arguments;
4025 /// The number of template arguments in \c Arguments.
4026 unsigned NumArguments;
4028 /// The location of the non-type template parameter pack reference.
4029 SourceLocation NameLoc;
4031 explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
4032 : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) {}
4035 SubstNonTypeTemplateParmPackExpr(QualType T,
4036 ExprValueKind ValueKind,
4037 NonTypeTemplateParmDecl *Param,
4038 SourceLocation NameLoc,
4039 const TemplateArgument &ArgPack);
4041 /// Retrieve the non-type template parameter pack being substituted.
4042 NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
4044 /// Retrieve the location of the parameter pack name.
4045 SourceLocation getParameterPackLocation() const { return NameLoc; }
4047 /// Retrieve the template argument pack containing the substituted
4048 /// template arguments.
4049 TemplateArgument getArgumentPack() const;
4051 SourceLocation getBeginLoc() const LLVM_READONLY { return NameLoc; }
4052 SourceLocation getEndLoc() const LLVM_READONLY { return NameLoc; }
4054 static bool classof(const Stmt *T) {
4055 return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
4059 child_range children() {
4060 return child_range(child_iterator(), child_iterator());
4064 /// Represents a reference to a function parameter pack that has been
4065 /// substituted but not yet expanded.
4067 /// When a pack expansion contains multiple parameter packs at different levels,
4068 /// this node is used to represent a function parameter pack at an outer level
4069 /// which we have already substituted to refer to expanded parameters, but where
4070 /// the containing pack expansion cannot yet be expanded.
4073 /// template<typename...Ts> struct S {
4074 /// template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
4076 /// template struct S<int, int>;
4078 class FunctionParmPackExpr final
4080 private llvm::TrailingObjects<FunctionParmPackExpr, ParmVarDecl *> {
4081 friend class ASTReader;
4082 friend class ASTStmtReader;
4083 friend TrailingObjects;
4085 /// The function parameter pack which was referenced.
4086 ParmVarDecl *ParamPack;
4088 /// The location of the function parameter pack reference.
4089 SourceLocation NameLoc;
4091 /// The number of expansions of this pack.
4092 unsigned NumParameters;
4094 FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
4095 SourceLocation NameLoc, unsigned NumParams,
4096 ParmVarDecl *const *Params);
4099 static FunctionParmPackExpr *Create(const ASTContext &Context, QualType T,
4100 ParmVarDecl *ParamPack,
4101 SourceLocation NameLoc,
4102 ArrayRef<ParmVarDecl *> Params);
4103 static FunctionParmPackExpr *CreateEmpty(const ASTContext &Context,
4104 unsigned NumParams);
4106 /// Get the parameter pack which this expression refers to.
4107 ParmVarDecl *getParameterPack() const { return ParamPack; }
4109 /// Get the location of the parameter pack.
4110 SourceLocation getParameterPackLocation() const { return NameLoc; }
4112 /// Iterators over the parameters which the parameter pack expanded
4114 using iterator = ParmVarDecl * const *;
4115 iterator begin() const { return getTrailingObjects<ParmVarDecl *>(); }
4116 iterator end() const { return begin() + NumParameters; }
4118 /// Get the number of parameters in this parameter pack.
4119 unsigned getNumExpansions() const { return NumParameters; }
4121 /// Get an expansion of the parameter pack by index.
4122 ParmVarDecl *getExpansion(unsigned I) const { return begin()[I]; }
4124 SourceLocation getBeginLoc() const LLVM_READONLY { return NameLoc; }
4125 SourceLocation getEndLoc() const LLVM_READONLY { return NameLoc; }
4127 static bool classof(const Stmt *T) {
4128 return T->getStmtClass() == FunctionParmPackExprClass;
4131 child_range children() {
4132 return child_range(child_iterator(), child_iterator());
4136 /// Represents a prvalue temporary that is written into memory so that
4137 /// a reference can bind to it.
4139 /// Prvalue expressions are materialized when they need to have an address
4140 /// in memory for a reference to bind to. This happens when binding a
4141 /// reference to the result of a conversion, e.g.,
4144 /// const int &r = 1.0;
4147 /// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
4148 /// then materialized via a \c MaterializeTemporaryExpr, and the reference
4149 /// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
4150 /// (either an lvalue or an xvalue, depending on the kind of reference binding
4151 /// to it), maintaining the invariant that references always bind to glvalues.
4153 /// Reference binding and copy-elision can both extend the lifetime of a
4154 /// temporary. When either happens, the expression will also track the
4155 /// declaration which is responsible for the lifetime extension.
4156 class MaterializeTemporaryExpr : public Expr {
4158 friend class ASTStmtReader;
4159 friend class ASTStmtWriter;
4162 /// The temporary-generating expression whose value will be
4166 /// The declaration which lifetime-extended this reference, if any.
4167 /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
4168 const ValueDecl *ExtendingDecl;
4170 unsigned ManglingNumber;
4172 llvm::PointerUnion<Stmt *, ExtraState *> State;
4174 void initializeExtraState(const ValueDecl *ExtendedBy,
4175 unsigned ManglingNumber);
4178 MaterializeTemporaryExpr(QualType T, Expr *Temporary,
4179 bool BoundToLvalueReference)
4180 : Expr(MaterializeTemporaryExprClass, T,
4181 BoundToLvalueReference? VK_LValue : VK_XValue, OK_Ordinary,
4182 Temporary->isTypeDependent(), Temporary->isValueDependent(),
4183 Temporary->isInstantiationDependent(),
4184 Temporary->containsUnexpandedParameterPack()),
4187 MaterializeTemporaryExpr(EmptyShell Empty)
4188 : Expr(MaterializeTemporaryExprClass, Empty) {}
4190 Stmt *getTemporary() const {
4191 return State.is<Stmt *>() ? State.get<Stmt *>()
4192 : State.get<ExtraState *>()->Temporary;
4195 /// Retrieve the temporary-generating subexpression whose value will
4196 /// be materialized into a glvalue.
4197 Expr *GetTemporaryExpr() const { return static_cast<Expr *>(getTemporary()); }
4199 /// Retrieve the storage duration for the materialized temporary.
4200 StorageDuration getStorageDuration() const {
4201 const ValueDecl *ExtendingDecl = getExtendingDecl();
4203 return SD_FullExpression;
4204 // FIXME: This is not necessarily correct for a temporary materialized
4205 // within a default initializer.
4206 if (isa<FieldDecl>(ExtendingDecl))
4207 return SD_Automatic;
4208 // FIXME: This only works because storage class specifiers are not allowed
4209 // on decomposition declarations.
4210 if (isa<BindingDecl>(ExtendingDecl))
4211 return ExtendingDecl->getDeclContext()->isFunctionOrMethod()
4214 return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
4217 /// Get the declaration which triggered the lifetime-extension of this
4218 /// temporary, if any.
4219 const ValueDecl *getExtendingDecl() const {
4220 return State.is<Stmt *>() ? nullptr
4221 : State.get<ExtraState *>()->ExtendingDecl;
4224 void setExtendingDecl(const ValueDecl *ExtendedBy, unsigned ManglingNumber);
4226 unsigned getManglingNumber() const {
4227 return State.is<Stmt *>() ? 0 : State.get<ExtraState *>()->ManglingNumber;
4230 /// Determine whether this materialized temporary is bound to an
4231 /// lvalue reference; otherwise, it's bound to an rvalue reference.
4232 bool isBoundToLvalueReference() const {
4233 return getValueKind() == VK_LValue;
4236 SourceLocation getBeginLoc() const LLVM_READONLY {
4237 return getTemporary()->getBeginLoc();
4240 SourceLocation getEndLoc() const LLVM_READONLY {
4241 return getTemporary()->getEndLoc();
4244 static bool classof(const Stmt *T) {
4245 return T->getStmtClass() == MaterializeTemporaryExprClass;
4249 child_range children() {
4250 if (State.is<Stmt *>())
4251 return child_range(State.getAddrOfPtr1(), State.getAddrOfPtr1() + 1);
4253 auto ES = State.get<ExtraState *>();
4254 return child_range(&ES->Temporary, &ES->Temporary + 1);
4258 /// Represents a folding of a pack over an operator.
4260 /// This expression is always dependent and represents a pack expansion of the
4265 /// ( expr op ... op expr )
4266 class CXXFoldExpr : public Expr {
4267 friend class ASTStmtReader;
4268 friend class ASTStmtWriter;
4270 SourceLocation LParenLoc;
4271 SourceLocation EllipsisLoc;
4272 SourceLocation RParenLoc;
4274 BinaryOperatorKind Opcode;
4277 CXXFoldExpr(QualType T, SourceLocation LParenLoc, Expr *LHS,
4278 BinaryOperatorKind Opcode, SourceLocation EllipsisLoc, Expr *RHS,
4279 SourceLocation RParenLoc)
4280 : Expr(CXXFoldExprClass, T, VK_RValue, OK_Ordinary,
4281 /*Dependent*/ true, true, true,
4282 /*ContainsUnexpandedParameterPack*/ false),
4283 LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),
4289 CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
4291 Expr *getLHS() const { return static_cast<Expr*>(SubExprs[0]); }
4292 Expr *getRHS() const { return static_cast<Expr*>(SubExprs[1]); }
4294 /// Does this produce a right-associated sequence of operators?
4295 bool isRightFold() const {
4296 return getLHS() && getLHS()->containsUnexpandedParameterPack();
4299 /// Does this produce a left-associated sequence of operators?
4300 bool isLeftFold() const { return !isRightFold(); }
4302 /// Get the pattern, that is, the operand that contains an unexpanded pack.
4303 Expr *getPattern() const { return isLeftFold() ? getRHS() : getLHS(); }
4305 /// Get the operand that doesn't contain a pack, for a binary fold.
4306 Expr *getInit() const { return isLeftFold() ? getLHS() : getRHS(); }
4308 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4309 BinaryOperatorKind getOperator() const { return Opcode; }
4311 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
4313 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4315 static bool classof(const Stmt *T) {
4316 return T->getStmtClass() == CXXFoldExprClass;
4320 child_range children() { return child_range(SubExprs, SubExprs + 2); }
4323 /// Represents an expression that might suspend coroutine execution;
4324 /// either a co_await or co_yield expression.
4326 /// Evaluation of this expression first evaluates its 'ready' expression. If
4327 /// that returns 'false':
4328 /// -- execution of the coroutine is suspended
4329 /// -- the 'suspend' expression is evaluated
4330 /// -- if the 'suspend' expression returns 'false', the coroutine is
4332 /// -- otherwise, control passes back to the resumer.
4333 /// If the coroutine is not suspended, or when it is resumed, the 'resume'
4334 /// expression is evaluated, and its result is the result of the overall
4336 class CoroutineSuspendExpr : public Expr {
4337 friend class ASTStmtReader;
4339 SourceLocation KeywordLoc;
4341 enum SubExpr { Common, Ready, Suspend, Resume, Count };
4343 Stmt *SubExprs[SubExpr::Count];
4344 OpaqueValueExpr *OpaqueValue = nullptr;
4347 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, Expr *Common,
4348 Expr *Ready, Expr *Suspend, Expr *Resume,
4349 OpaqueValueExpr *OpaqueValue)
4350 : Expr(SC, Resume->getType(), Resume->getValueKind(),
4351 Resume->getObjectKind(), Resume->isTypeDependent(),
4352 Resume->isValueDependent(), Common->isInstantiationDependent(),
4353 Common->containsUnexpandedParameterPack()),
4354 KeywordLoc(KeywordLoc), OpaqueValue(OpaqueValue) {
4355 SubExprs[SubExpr::Common] = Common;
4356 SubExprs[SubExpr::Ready] = Ready;
4357 SubExprs[SubExpr::Suspend] = Suspend;
4358 SubExprs[SubExpr::Resume] = Resume;
4361 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, QualType Ty,
4363 : Expr(SC, Ty, VK_RValue, OK_Ordinary, true, true, true,
4364 Common->containsUnexpandedParameterPack()),
4365 KeywordLoc(KeywordLoc) {
4366 assert(Common->isTypeDependent() && Ty->isDependentType() &&
4367 "wrong constructor for non-dependent co_await/co_yield expression");
4368 SubExprs[SubExpr::Common] = Common;
4369 SubExprs[SubExpr::Ready] = nullptr;
4370 SubExprs[SubExpr::Suspend] = nullptr;
4371 SubExprs[SubExpr::Resume] = nullptr;
4374 CoroutineSuspendExpr(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4375 SubExprs[SubExpr::Common] = nullptr;
4376 SubExprs[SubExpr::Ready] = nullptr;
4377 SubExprs[SubExpr::Suspend] = nullptr;
4378 SubExprs[SubExpr::Resume] = nullptr;
4381 SourceLocation getKeywordLoc() const { return KeywordLoc; }
4383 Expr *getCommonExpr() const {
4384 return static_cast<Expr*>(SubExprs[SubExpr::Common]);
4387 /// getOpaqueValue - Return the opaque value placeholder.
4388 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4390 Expr *getReadyExpr() const {
4391 return static_cast<Expr*>(SubExprs[SubExpr::Ready]);
4394 Expr *getSuspendExpr() const {
4395 return static_cast<Expr*>(SubExprs[SubExpr::Suspend]);
4398 Expr *getResumeExpr() const {
4399 return static_cast<Expr*>(SubExprs[SubExpr::Resume]);
4402 SourceLocation getBeginLoc() const LLVM_READONLY { return KeywordLoc; }
4404 SourceLocation getEndLoc() const LLVM_READONLY {
4405 return getCommonExpr()->getEndLoc();
4408 child_range children() {
4409 return child_range(SubExprs, SubExprs + SubExpr::Count);
4412 static bool classof(const Stmt *T) {
4413 return T->getStmtClass() == CoawaitExprClass ||
4414 T->getStmtClass() == CoyieldExprClass;
4418 /// Represents a 'co_await' expression.
4419 class CoawaitExpr : public CoroutineSuspendExpr {
4420 friend class ASTStmtReader;
4423 CoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand, Expr *Ready,
4424 Expr *Suspend, Expr *Resume, OpaqueValueExpr *OpaqueValue,
4425 bool IsImplicit = false)
4426 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Operand, Ready,
4427 Suspend, Resume, OpaqueValue) {
4428 CoawaitBits.IsImplicit = IsImplicit;
4431 CoawaitExpr(SourceLocation CoawaitLoc, QualType Ty, Expr *Operand,
4432 bool IsImplicit = false)
4433 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Ty, Operand) {
4434 CoawaitBits.IsImplicit = IsImplicit;
4437 CoawaitExpr(EmptyShell Empty)
4438 : CoroutineSuspendExpr(CoawaitExprClass, Empty) {}
4440 Expr *getOperand() const {
4441 // FIXME: Dig out the actual operand or store it.
4442 return getCommonExpr();
4445 bool isImplicit() const { return CoawaitBits.IsImplicit; }
4446 void setIsImplicit(bool value = true) { CoawaitBits.IsImplicit = value; }
4448 static bool classof(const Stmt *T) {
4449 return T->getStmtClass() == CoawaitExprClass;
4453 /// Represents a 'co_await' expression while the type of the promise
4455 class DependentCoawaitExpr : public Expr {
4456 friend class ASTStmtReader;
4458 SourceLocation KeywordLoc;
4462 DependentCoawaitExpr(SourceLocation KeywordLoc, QualType Ty, Expr *Op,
4463 UnresolvedLookupExpr *OpCoawait)
4464 : Expr(DependentCoawaitExprClass, Ty, VK_RValue, OK_Ordinary,
4465 /*TypeDependent*/ true, /*ValueDependent*/ true,
4466 /*InstantiationDependent*/ true,
4467 Op->containsUnexpandedParameterPack()),
4468 KeywordLoc(KeywordLoc) {
4469 // NOTE: A co_await expression is dependent on the coroutines promise
4470 // type and may be dependent even when the `Op` expression is not.
4471 assert(Ty->isDependentType() &&
4472 "wrong constructor for non-dependent co_await/co_yield expression");
4474 SubExprs[1] = OpCoawait;
4477 DependentCoawaitExpr(EmptyShell Empty)
4478 : Expr(DependentCoawaitExprClass, Empty) {}
4480 Expr *getOperand() const { return cast<Expr>(SubExprs[0]); }
4482 UnresolvedLookupExpr *getOperatorCoawaitLookup() const {
4483 return cast<UnresolvedLookupExpr>(SubExprs[1]);
4486 SourceLocation getKeywordLoc() const { return KeywordLoc; }
4488 SourceLocation getBeginLoc() const LLVM_READONLY { return KeywordLoc; }
4490 SourceLocation getEndLoc() const LLVM_READONLY {
4491 return getOperand()->getEndLoc();
4494 child_range children() { return child_range(SubExprs, SubExprs + 2); }
4496 static bool classof(const Stmt *T) {
4497 return T->getStmtClass() == DependentCoawaitExprClass;
4501 /// Represents a 'co_yield' expression.
4502 class CoyieldExpr : public CoroutineSuspendExpr {
4503 friend class ASTStmtReader;
4506 CoyieldExpr(SourceLocation CoyieldLoc, Expr *Operand, Expr *Ready,
4507 Expr *Suspend, Expr *Resume, OpaqueValueExpr *OpaqueValue)
4508 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Operand, Ready,
4509 Suspend, Resume, OpaqueValue) {}
4510 CoyieldExpr(SourceLocation CoyieldLoc, QualType Ty, Expr *Operand)
4511 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Ty, Operand) {}
4512 CoyieldExpr(EmptyShell Empty)
4513 : CoroutineSuspendExpr(CoyieldExprClass, Empty) {}
4515 Expr *getOperand() const {
4516 // FIXME: Dig out the actual operand or store it.
4517 return getCommonExpr();
4520 static bool classof(const Stmt *T) {
4521 return T->getStmtClass() == CoyieldExprClass;
4525 } // namespace clang
4527 #endif // LLVM_CLANG_AST_EXPRCXX_H