1//===- ExprCXX.h - Classes for representing expressions ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the clang::Expr interface and subclasses for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPRCXX_H
15#define LLVM_CLANG_AST_EXPRCXX_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ComputeDependence.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/DependenceFlags.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TemplateBase.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/ExpressionTraits.h"
35#include "clang/Basic/LLVM.h"
36#include "clang/Basic/Lambda.h"
37#include "clang/Basic/LangOptions.h"
38#include "clang/Basic/OperatorKinds.h"
39#include "clang/Basic/SourceLocation.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TypeTraits.h"
42#include "llvm/ADT/ArrayRef.h"
43#include "llvm/ADT/PointerUnion.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/StringRef.h"
46#include "llvm/ADT/iterator_range.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/TrailingObjects.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <memory>
54#include <optional>
55#include <variant>
56
57namespace clang {
58
59class ASTContext;
60class DeclAccessPair;
61class IdentifierInfo;
62class LambdaCapture;
63class NonTypeTemplateParmDecl;
64class TemplateParameterList;
65
66//===--------------------------------------------------------------------===//
67// C++ Expressions.
68//===--------------------------------------------------------------------===//
69
70/// A call to an overloaded operator written using operator
71/// syntax.
72///
73/// Represents a call to an overloaded operator written using operator
74/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
75/// normal call, this AST node provides better information about the
76/// syntactic representation of the call.
77///
78/// In a C++ template, this expression node kind will be used whenever
79/// any of the arguments are type-dependent. In this case, the
80/// function itself will be a (possibly empty) set of functions and
81/// function templates that were found by name lookup at template
82/// definition time.
83class CXXOperatorCallExpr final : public CallExpr {
84 friend class ASTStmtReader;
85 friend class ASTStmtWriter;
86
87 SourceRange Range;
88
89 // CXXOperatorCallExpr has some trailing objects belonging
90 // to CallExpr. See CallExpr for the details.
91
92 SourceRange getSourceRangeImpl() const LLVM_READONLY;
93
94 CXXOperatorCallExpr(OverloadedOperatorKind OpKind, Expr *Fn,
95 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
96 SourceLocation OperatorLoc, FPOptionsOverride FPFeatures,
97 ADLCallKind UsesADL);
98
99 CXXOperatorCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
100
101public:
102 static CXXOperatorCallExpr *
103 Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn,
104 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
105 SourceLocation OperatorLoc, FPOptionsOverride FPFeatures,
106 ADLCallKind UsesADL = NotADL);
107
108 static CXXOperatorCallExpr *CreateEmpty(const ASTContext &Ctx,
109 unsigned NumArgs, bool HasFPFeatures,
110 EmptyShell Empty);
111
112 /// Returns the kind of overloaded operator that this expression refers to.
113 OverloadedOperatorKind getOperator() const {
114 return static_cast<OverloadedOperatorKind>(
115 CXXOperatorCallExprBits.OperatorKind);
116 }
117
118 static bool isAssignmentOp(OverloadedOperatorKind Opc) {
119 return Opc == OO_Equal || Opc == OO_StarEqual || Opc == OO_SlashEqual ||
120 Opc == OO_PercentEqual || Opc == OO_PlusEqual ||
121 Opc == OO_MinusEqual || Opc == OO_LessLessEqual ||
122 Opc == OO_GreaterGreaterEqual || Opc == OO_AmpEqual ||
123 Opc == OO_CaretEqual || Opc == OO_PipeEqual;
124 }
125 bool isAssignmentOp() const { return isAssignmentOp(Opc: getOperator()); }
126
127 static bool isComparisonOp(OverloadedOperatorKind Opc) {
128 switch (Opc) {
129 case OO_EqualEqual:
130 case OO_ExclaimEqual:
131 case OO_Greater:
132 case OO_GreaterEqual:
133 case OO_Less:
134 case OO_LessEqual:
135 case OO_Spaceship:
136 return true;
137 default:
138 return false;
139 }
140 }
141 bool isComparisonOp() const { return isComparisonOp(Opc: getOperator()); }
142
143 /// Is this written as an infix binary operator?
144 bool isInfixBinaryOp() const;
145
146 /// Returns the location of the operator symbol in the expression.
147 ///
148 /// When \c getOperator()==OO_Call, this is the location of the right
149 /// parentheses; when \c getOperator()==OO_Subscript, this is the location
150 /// of the right bracket.
151 SourceLocation getOperatorLoc() const { return getRParenLoc(); }
152
153 SourceLocation getExprLoc() const LLVM_READONLY {
154 OverloadedOperatorKind Operator = getOperator();
155 return (Operator < OO_Plus || Operator >= OO_Arrow ||
156 Operator == OO_PlusPlus || Operator == OO_MinusMinus)
157 ? getBeginLoc()
158 : getOperatorLoc();
159 }
160
161 SourceLocation getBeginLoc() const { return Range.getBegin(); }
162 SourceLocation getEndLoc() const { return Range.getEnd(); }
163 SourceRange getSourceRange() const { return Range; }
164
165 static bool classof(const Stmt *T) {
166 return T->getStmtClass() == CXXOperatorCallExprClass;
167 }
168};
169
170/// Represents a call to a member function that
171/// may be written either with member call syntax (e.g., "obj.func()"
172/// or "objptr->func()") or with normal function-call syntax
173/// ("func()") within a member function that ends up calling a member
174/// function. The callee in either case is a MemberExpr that contains
175/// both the object argument and the member function, while the
176/// arguments are the arguments within the parentheses (not including
177/// the object argument).
178class CXXMemberCallExpr final : public CallExpr {
179 // CXXMemberCallExpr has some trailing objects belonging
180 // to CallExpr. See CallExpr for the details.
181
182 CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
183 ExprValueKind VK, SourceLocation RP,
184 FPOptionsOverride FPOptions, unsigned MinNumArgs);
185
186 CXXMemberCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
187
188public:
189 static CXXMemberCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
190 ArrayRef<Expr *> Args, QualType Ty,
191 ExprValueKind VK, SourceLocation RP,
192 FPOptionsOverride FPFeatures,
193 unsigned MinNumArgs = 0);
194
195 static CXXMemberCallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
196 bool HasFPFeatures, EmptyShell Empty);
197
198 /// Retrieve the implicit object argument for the member call.
199 ///
200 /// For example, in "x.f(5)", this returns the sub-expression "x".
201 Expr *getImplicitObjectArgument() const;
202
203 /// Retrieve the type of the object argument.
204 ///
205 /// Note that this always returns a non-pointer type.
206 QualType getObjectType() const;
207
208 /// Retrieve the declaration of the called method.
209 CXXMethodDecl *getMethodDecl() const;
210
211 /// Retrieve the CXXRecordDecl for the underlying type of
212 /// the implicit object argument.
213 ///
214 /// Note that this is may not be the same declaration as that of the class
215 /// context of the CXXMethodDecl which this function is calling.
216 /// FIXME: Returns 0 for member pointer call exprs.
217 CXXRecordDecl *getRecordDecl() const;
218
219 SourceLocation getExprLoc() const LLVM_READONLY {
220 SourceLocation CLoc = getCallee()->getExprLoc();
221 if (CLoc.isValid())
222 return CLoc;
223
224 return getBeginLoc();
225 }
226
227 static bool classof(const Stmt *T) {
228 return T->getStmtClass() == CXXMemberCallExprClass;
229 }
230};
231
232/// Represents a call to a CUDA kernel function.
233class CUDAKernelCallExpr final : public CallExpr {
234 friend class ASTStmtReader;
235
236 enum { CONFIG, END_PREARG };
237
238 // CUDAKernelCallExpr has some trailing objects belonging
239 // to CallExpr. See CallExpr for the details.
240
241 CUDAKernelCallExpr(Expr *Fn, CallExpr *Config, ArrayRef<Expr *> Args,
242 QualType Ty, ExprValueKind VK, SourceLocation RP,
243 FPOptionsOverride FPFeatures, unsigned MinNumArgs);
244
245 CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
246
247public:
248 static CUDAKernelCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
249 CallExpr *Config, ArrayRef<Expr *> Args,
250 QualType Ty, ExprValueKind VK,
251 SourceLocation RP,
252 FPOptionsOverride FPFeatures,
253 unsigned MinNumArgs = 0);
254
255 static CUDAKernelCallExpr *CreateEmpty(const ASTContext &Ctx,
256 unsigned NumArgs, bool HasFPFeatures,
257 EmptyShell Empty);
258
259 const CallExpr *getConfig() const {
260 return cast_or_null<CallExpr>(getPreArg(CONFIG));
261 }
262 CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
263
264 static bool classof(const Stmt *T) {
265 return T->getStmtClass() == CUDAKernelCallExprClass;
266 }
267};
268
269/// A rewritten comparison expression that was originally written using
270/// operator syntax.
271///
272/// In C++20, the following rewrites are performed:
273/// - <tt>a == b</tt> -> <tt>b == a</tt>
274/// - <tt>a != b</tt> -> <tt>!(a == b)</tt>
275/// - <tt>a != b</tt> -> <tt>!(b == a)</tt>
276/// - For \c \@ in \c <, \c <=, \c >, \c >=, \c <=>:
277/// - <tt>a @ b</tt> -> <tt>(a <=> b) @ 0</tt>
278/// - <tt>a @ b</tt> -> <tt>0 @ (b <=> a)</tt>
279///
280/// This expression provides access to both the original syntax and the
281/// rewritten expression.
282///
283/// Note that the rewritten calls to \c ==, \c <=>, and \c \@ are typically
284/// \c CXXOperatorCallExprs, but could theoretically be \c BinaryOperators.
285class CXXRewrittenBinaryOperator : public Expr {
286 friend class ASTStmtReader;
287
288 /// The rewritten semantic form.
289 Stmt *SemanticForm;
290
291public:
292 CXXRewrittenBinaryOperator(Expr *SemanticForm, bool IsReversed)
293 : Expr(CXXRewrittenBinaryOperatorClass, SemanticForm->getType(),
294 SemanticForm->getValueKind(), SemanticForm->getObjectKind()),
295 SemanticForm(SemanticForm) {
296 CXXRewrittenBinaryOperatorBits.IsReversed = IsReversed;
297 setDependence(computeDependence(E: this));
298 }
299 CXXRewrittenBinaryOperator(EmptyShell Empty)
300 : Expr(CXXRewrittenBinaryOperatorClass, Empty), SemanticForm() {}
301
302 /// Get an equivalent semantic form for this expression.
303 Expr *getSemanticForm() { return cast<Expr>(Val: SemanticForm); }
304 const Expr *getSemanticForm() const { return cast<Expr>(Val: SemanticForm); }
305
306 struct DecomposedForm {
307 /// The original opcode, prior to rewriting.
308 BinaryOperatorKind Opcode;
309 /// The original left-hand side.
310 const Expr *LHS;
311 /// The original right-hand side.
312 const Expr *RHS;
313 /// The inner \c == or \c <=> operator expression.
314 const Expr *InnerBinOp;
315 };
316
317 /// Decompose this operator into its syntactic form.
318 DecomposedForm getDecomposedForm() const LLVM_READONLY;
319
320 /// Determine whether this expression was rewritten in reverse form.
321 bool isReversed() const { return CXXRewrittenBinaryOperatorBits.IsReversed; }
322
323 BinaryOperatorKind getOperator() const { return getDecomposedForm().Opcode; }
324 BinaryOperatorKind getOpcode() const { return getOperator(); }
325 static StringRef getOpcodeStr(BinaryOperatorKind Op) {
326 return BinaryOperator::getOpcodeStr(Op);
327 }
328 StringRef getOpcodeStr() const {
329 return BinaryOperator::getOpcodeStr(Op: getOpcode());
330 }
331 bool isComparisonOp() const { return true; }
332 bool isAssignmentOp() const { return false; }
333
334 const Expr *getLHS() const { return getDecomposedForm().LHS; }
335 const Expr *getRHS() const { return getDecomposedForm().RHS; }
336
337 SourceLocation getOperatorLoc() const LLVM_READONLY {
338 return getDecomposedForm().InnerBinOp->getExprLoc();
339 }
340 SourceLocation getExprLoc() const LLVM_READONLY { return getOperatorLoc(); }
341
342 /// Compute the begin and end locations from the decomposed form.
343 /// The locations of the semantic form are not reliable if this is
344 /// a reversed expression.
345 //@{
346 SourceLocation getBeginLoc() const LLVM_READONLY {
347 return getDecomposedForm().LHS->getBeginLoc();
348 }
349 SourceLocation getEndLoc() const LLVM_READONLY {
350 return getDecomposedForm().RHS->getEndLoc();
351 }
352 SourceRange getSourceRange() const LLVM_READONLY {
353 DecomposedForm DF = getDecomposedForm();
354 return SourceRange(DF.LHS->getBeginLoc(), DF.RHS->getEndLoc());
355 }
356 //@}
357
358 child_range children() {
359 return child_range(&SemanticForm, &SemanticForm + 1);
360 }
361
362 static bool classof(const Stmt *T) {
363 return T->getStmtClass() == CXXRewrittenBinaryOperatorClass;
364 }
365};
366
367/// Abstract class common to all of the C++ "named"/"keyword" casts.
368///
369/// This abstract class is inherited by all of the classes
370/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
371/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
372/// reinterpret_cast, CXXConstCastExpr for \c const_cast and
373/// CXXAddrspaceCastExpr for addrspace_cast (in OpenCL).
374class CXXNamedCastExpr : public ExplicitCastExpr {
375private:
376 // the location of the casting op
377 SourceLocation Loc;
378
379 // the location of the right parenthesis
380 SourceLocation RParenLoc;
381
382 // range for '<' '>'
383 SourceRange AngleBrackets;
384
385protected:
386 friend class ASTStmtReader;
387
388 CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK, CastKind kind,
389 Expr *op, unsigned PathSize, bool HasFPFeatures,
390 TypeSourceInfo *writtenTy, SourceLocation l,
391 SourceLocation RParenLoc, SourceRange AngleBrackets)
392 : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, HasFPFeatures,
393 writtenTy),
394 Loc(l), RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
395
396 explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
397 bool HasFPFeatures)
398 : ExplicitCastExpr(SC, Shell, PathSize, HasFPFeatures) {}
399
400public:
401 const char *getCastName() const;
402
403 /// Retrieve the location of the cast operator keyword, e.g.,
404 /// \c static_cast.
405 SourceLocation getOperatorLoc() const { return Loc; }
406
407 /// Retrieve the location of the closing parenthesis.
408 SourceLocation getRParenLoc() const { return RParenLoc; }
409
410 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
411 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
412 SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
413
414 static bool classof(const Stmt *T) {
415 switch (T->getStmtClass()) {
416 case CXXStaticCastExprClass:
417 case CXXDynamicCastExprClass:
418 case CXXReinterpretCastExprClass:
419 case CXXConstCastExprClass:
420 case CXXAddrspaceCastExprClass:
421 return true;
422 default:
423 return false;
424 }
425 }
426};
427
428/// A C++ \c static_cast expression (C++ [expr.static.cast]).
429///
430/// This expression node represents a C++ static cast, e.g.,
431/// \c static_cast<int>(1.0).
432class CXXStaticCastExpr final
433 : public CXXNamedCastExpr,
434 private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *,
435 FPOptionsOverride> {
436 CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
437 unsigned pathSize, TypeSourceInfo *writtenTy,
438 FPOptionsOverride FPO, SourceLocation l,
439 SourceLocation RParenLoc, SourceRange AngleBrackets)
440 : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
441 FPO.requiresTrailingStorage(), writtenTy, l, RParenLoc,
442 AngleBrackets) {
443 if (hasStoredFPFeatures())
444 *getTrailingFPFeatures() = FPO;
445 }
446
447 explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize,
448 bool HasFPFeatures)
449 : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize,
450 HasFPFeatures) {}
451
452 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
453 return path_size();
454 }
455
456public:
457 friend class CastExpr;
458 friend TrailingObjects;
459
460 static CXXStaticCastExpr *
461 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
462 Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written,
463 FPOptionsOverride FPO, SourceLocation L, SourceLocation RParenLoc,
464 SourceRange AngleBrackets);
465 static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
466 unsigned PathSize, bool hasFPFeatures);
467
468 static bool classof(const Stmt *T) {
469 return T->getStmtClass() == CXXStaticCastExprClass;
470 }
471};
472
473/// A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
474///
475/// This expression node represents a dynamic cast, e.g.,
476/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
477/// check to determine how to perform the type conversion.
478class CXXDynamicCastExpr final
479 : public CXXNamedCastExpr,
480 private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> {
481 CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind, Expr *op,
482 unsigned pathSize, TypeSourceInfo *writtenTy,
483 SourceLocation l, SourceLocation RParenLoc,
484 SourceRange AngleBrackets)
485 : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
486 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
487 AngleBrackets) {}
488
489 explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
490 : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize,
491 /*HasFPFeatures*/ false) {}
492
493public:
494 friend class CastExpr;
495 friend TrailingObjects;
496
497 static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
498 ExprValueKind VK, CastKind Kind, Expr *Op,
499 const CXXCastPath *Path,
500 TypeSourceInfo *Written, SourceLocation L,
501 SourceLocation RParenLoc,
502 SourceRange AngleBrackets);
503
504 static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
505 unsigned pathSize);
506
507 bool isAlwaysNull() const;
508
509 static bool classof(const Stmt *T) {
510 return T->getStmtClass() == CXXDynamicCastExprClass;
511 }
512};
513
514/// A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
515///
516/// This expression node represents a reinterpret cast, e.g.,
517/// @c reinterpret_cast<int>(VoidPtr).
518///
519/// A reinterpret_cast provides a differently-typed view of a value but
520/// (in Clang, as in most C++ implementations) performs no actual work at
521/// run time.
522class CXXReinterpretCastExpr final
523 : public CXXNamedCastExpr,
524 private llvm::TrailingObjects<CXXReinterpretCastExpr,
525 CXXBaseSpecifier *> {
526 CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
527 unsigned pathSize, TypeSourceInfo *writtenTy,
528 SourceLocation l, SourceLocation RParenLoc,
529 SourceRange AngleBrackets)
530 : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
531 pathSize, /*HasFPFeatures*/ false, writtenTy, l,
532 RParenLoc, AngleBrackets) {}
533
534 CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
535 : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize,
536 /*HasFPFeatures*/ false) {}
537
538public:
539 friend class CastExpr;
540 friend TrailingObjects;
541
542 static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
543 ExprValueKind VK, CastKind Kind,
544 Expr *Op, const CXXCastPath *Path,
545 TypeSourceInfo *WrittenTy, SourceLocation L,
546 SourceLocation RParenLoc,
547 SourceRange AngleBrackets);
548 static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
549 unsigned pathSize);
550
551 static bool classof(const Stmt *T) {
552 return T->getStmtClass() == CXXReinterpretCastExprClass;
553 }
554};
555
556/// A C++ \c const_cast expression (C++ [expr.const.cast]).
557///
558/// This expression node represents a const cast, e.g.,
559/// \c const_cast<char*>(PtrToConstChar).
560///
561/// A const_cast can remove type qualifiers but does not change the underlying
562/// value.
563class CXXConstCastExpr final
564 : public CXXNamedCastExpr,
565 private llvm::TrailingObjects<CXXConstCastExpr, CXXBaseSpecifier *> {
566 CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
567 TypeSourceInfo *writtenTy, SourceLocation l,
568 SourceLocation RParenLoc, SourceRange AngleBrackets)
569 : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op, 0,
570 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
571 AngleBrackets) {}
572
573 explicit CXXConstCastExpr(EmptyShell Empty)
574 : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0,
575 /*HasFPFeatures*/ false) {}
576
577public:
578 friend class CastExpr;
579 friend TrailingObjects;
580
581 static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
582 ExprValueKind VK, Expr *Op,
583 TypeSourceInfo *WrittenTy, SourceLocation L,
584 SourceLocation RParenLoc,
585 SourceRange AngleBrackets);
586 static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
587
588 static bool classof(const Stmt *T) {
589 return T->getStmtClass() == CXXConstCastExprClass;
590 }
591};
592
593/// A C++ addrspace_cast expression (currently only enabled for OpenCL).
594///
595/// This expression node represents a cast between pointers to objects in
596/// different address spaces e.g.,
597/// \c addrspace_cast<global int*>(PtrToGenericInt).
598///
599/// A addrspace_cast can cast address space type qualifiers but does not change
600/// the underlying value.
601class CXXAddrspaceCastExpr final
602 : public CXXNamedCastExpr,
603 private llvm::TrailingObjects<CXXAddrspaceCastExpr, CXXBaseSpecifier *> {
604 CXXAddrspaceCastExpr(QualType ty, ExprValueKind VK, CastKind Kind, Expr *op,
605 TypeSourceInfo *writtenTy, SourceLocation l,
606 SourceLocation RParenLoc, SourceRange AngleBrackets)
607 : CXXNamedCastExpr(CXXAddrspaceCastExprClass, ty, VK, Kind, op, 0,
608 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
609 AngleBrackets) {}
610
611 explicit CXXAddrspaceCastExpr(EmptyShell Empty)
612 : CXXNamedCastExpr(CXXAddrspaceCastExprClass, Empty, 0,
613 /*HasFPFeatures*/ false) {}
614
615public:
616 friend class CastExpr;
617 friend TrailingObjects;
618
619 static CXXAddrspaceCastExpr *
620 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind,
621 Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L,
622 SourceLocation RParenLoc, SourceRange AngleBrackets);
623 static CXXAddrspaceCastExpr *CreateEmpty(const ASTContext &Context);
624
625 static bool classof(const Stmt *T) {
626 return T->getStmtClass() == CXXAddrspaceCastExprClass;
627 }
628};
629
630/// A call to a literal operator (C++11 [over.literal])
631/// written as a user-defined literal (C++11 [lit.ext]).
632///
633/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
634/// is semantically equivalent to a normal call, this AST node provides better
635/// information about the syntactic representation of the literal.
636///
637/// Since literal operators are never found by ADL and can only be declared at
638/// namespace scope, a user-defined literal is never dependent.
639class UserDefinedLiteral final : public CallExpr {
640 friend class ASTStmtReader;
641 friend class ASTStmtWriter;
642
643 /// The location of a ud-suffix within the literal.
644 SourceLocation UDSuffixLoc;
645
646 // UserDefinedLiteral has some trailing objects belonging
647 // to CallExpr. See CallExpr for the details.
648
649 UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
650 ExprValueKind VK, SourceLocation LitEndLoc,
651 SourceLocation SuffixLoc, FPOptionsOverride FPFeatures);
652
653 UserDefinedLiteral(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
654
655public:
656 static UserDefinedLiteral *Create(const ASTContext &Ctx, Expr *Fn,
657 ArrayRef<Expr *> Args, QualType Ty,
658 ExprValueKind VK, SourceLocation LitEndLoc,
659 SourceLocation SuffixLoc,
660 FPOptionsOverride FPFeatures);
661
662 static UserDefinedLiteral *CreateEmpty(const ASTContext &Ctx,
663 unsigned NumArgs, bool HasFPOptions,
664 EmptyShell Empty);
665
666 /// The kind of literal operator which is invoked.
667 enum LiteralOperatorKind {
668 /// Raw form: operator "" X (const char *)
669 LOK_Raw,
670
671 /// Raw form: operator "" X<cs...> ()
672 LOK_Template,
673
674 /// operator "" X (unsigned long long)
675 LOK_Integer,
676
677 /// operator "" X (long double)
678 LOK_Floating,
679
680 /// operator "" X (const CharT *, size_t)
681 LOK_String,
682
683 /// operator "" X (CharT)
684 LOK_Character
685 };
686
687 /// Returns the kind of literal operator invocation
688 /// which this expression represents.
689 LiteralOperatorKind getLiteralOperatorKind() const;
690
691 /// If this is not a raw user-defined literal, get the
692 /// underlying cooked literal (representing the literal with the suffix
693 /// removed).
694 Expr *getCookedLiteral();
695 const Expr *getCookedLiteral() const {
696 return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
697 }
698
699 SourceLocation getBeginLoc() const {
700 if (getLiteralOperatorKind() == LOK_Template)
701 return getRParenLoc();
702 return getArg(0)->getBeginLoc();
703 }
704
705 SourceLocation getEndLoc() const { return getRParenLoc(); }
706
707 /// Returns the location of a ud-suffix in the expression.
708 ///
709 /// For a string literal, there may be multiple identical suffixes. This
710 /// returns the first.
711 SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
712
713 /// Returns the ud-suffix specified for this literal.
714 const IdentifierInfo *getUDSuffix() const;
715
716 static bool classof(const Stmt *S) {
717 return S->getStmtClass() == UserDefinedLiteralClass;
718 }
719};
720
721/// A boolean literal, per ([C++ lex.bool] Boolean literals).
722class CXXBoolLiteralExpr : public Expr {
723public:
724 CXXBoolLiteralExpr(bool Val, QualType Ty, SourceLocation Loc)
725 : Expr(CXXBoolLiteralExprClass, Ty, VK_PRValue, OK_Ordinary) {
726 CXXBoolLiteralExprBits.Value = Val;
727 CXXBoolLiteralExprBits.Loc = Loc;
728 setDependence(ExprDependence::None);
729 }
730
731 explicit CXXBoolLiteralExpr(EmptyShell Empty)
732 : Expr(CXXBoolLiteralExprClass, Empty) {}
733
734 static CXXBoolLiteralExpr *Create(const ASTContext &C, bool Val, QualType Ty,
735 SourceLocation Loc) {
736 return new (C) CXXBoolLiteralExpr(Val, Ty, Loc);
737 }
738
739 bool getValue() const { return CXXBoolLiteralExprBits.Value; }
740 void setValue(bool V) { CXXBoolLiteralExprBits.Value = V; }
741
742 SourceLocation getBeginLoc() const { return getLocation(); }
743 SourceLocation getEndLoc() const { return getLocation(); }
744
745 SourceLocation getLocation() const { return CXXBoolLiteralExprBits.Loc; }
746 void setLocation(SourceLocation L) { CXXBoolLiteralExprBits.Loc = L; }
747
748 static bool classof(const Stmt *T) {
749 return T->getStmtClass() == CXXBoolLiteralExprClass;
750 }
751
752 // Iterators
753 child_range children() {
754 return child_range(child_iterator(), child_iterator());
755 }
756
757 const_child_range children() const {
758 return const_child_range(const_child_iterator(), const_child_iterator());
759 }
760};
761
762/// The null pointer literal (C++11 [lex.nullptr])
763///
764/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
765/// This also implements the null pointer literal in C23 (C23 6.4.1) which is
766/// intended to have the same semantics as the feature in C++.
767class CXXNullPtrLiteralExpr : public Expr {
768public:
769 CXXNullPtrLiteralExpr(QualType Ty, SourceLocation Loc)
770 : Expr(CXXNullPtrLiteralExprClass, Ty, VK_PRValue, OK_Ordinary) {
771 CXXNullPtrLiteralExprBits.Loc = Loc;
772 setDependence(ExprDependence::None);
773 }
774
775 explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
776 : Expr(CXXNullPtrLiteralExprClass, Empty) {}
777
778 SourceLocation getBeginLoc() const { return getLocation(); }
779 SourceLocation getEndLoc() const { return getLocation(); }
780
781 SourceLocation getLocation() const { return CXXNullPtrLiteralExprBits.Loc; }
782 void setLocation(SourceLocation L) { CXXNullPtrLiteralExprBits.Loc = L; }
783
784 static bool classof(const Stmt *T) {
785 return T->getStmtClass() == CXXNullPtrLiteralExprClass;
786 }
787
788 child_range children() {
789 return child_range(child_iterator(), child_iterator());
790 }
791
792 const_child_range children() const {
793 return const_child_range(const_child_iterator(), const_child_iterator());
794 }
795};
796
797/// Implicit construction of a std::initializer_list<T> object from an
798/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
799class CXXStdInitializerListExpr : public Expr {
800 Stmt *SubExpr = nullptr;
801
802 CXXStdInitializerListExpr(EmptyShell Empty)
803 : Expr(CXXStdInitializerListExprClass, Empty) {}
804
805public:
806 friend class ASTReader;
807 friend class ASTStmtReader;
808
809 CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
810 : Expr(CXXStdInitializerListExprClass, Ty, VK_PRValue, OK_Ordinary),
811 SubExpr(SubExpr) {
812 setDependence(computeDependence(E: this));
813 }
814
815 Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
816 const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
817
818 SourceLocation getBeginLoc() const LLVM_READONLY {
819 return SubExpr->getBeginLoc();
820 }
821
822 SourceLocation getEndLoc() const LLVM_READONLY {
823 return SubExpr->getEndLoc();
824 }
825
826 /// Retrieve the source range of the expression.
827 SourceRange getSourceRange() const LLVM_READONLY {
828 return SubExpr->getSourceRange();
829 }
830
831 static bool classof(const Stmt *S) {
832 return S->getStmtClass() == CXXStdInitializerListExprClass;
833 }
834
835 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
836
837 const_child_range children() const {
838 return const_child_range(&SubExpr, &SubExpr + 1);
839 }
840};
841
842/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
843/// the \c type_info that corresponds to the supplied type, or the (possibly
844/// dynamic) type of the supplied expression.
845///
846/// This represents code like \c typeid(int) or \c typeid(*objPtr)
847class CXXTypeidExpr : public Expr {
848 friend class ASTStmtReader;
849
850private:
851 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
852 SourceRange Range;
853
854public:
855 CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
856 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
857 Range(R) {
858 setDependence(computeDependence(E: this));
859 }
860
861 CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
862 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
863 Range(R) {
864 setDependence(computeDependence(E: this));
865 }
866
867 CXXTypeidExpr(EmptyShell Empty, bool isExpr)
868 : Expr(CXXTypeidExprClass, Empty) {
869 if (isExpr)
870 Operand = (Expr*)nullptr;
871 else
872 Operand = (TypeSourceInfo*)nullptr;
873 }
874
875 /// Determine whether this typeid has a type operand which is potentially
876 /// evaluated, per C++11 [expr.typeid]p3.
877 bool isPotentiallyEvaluated() const;
878
879 /// Best-effort check if the expression operand refers to a most derived
880 /// object. This is not a strong guarantee.
881 bool isMostDerived(const ASTContext &Context) const;
882
883 bool isTypeOperand() const { return isa<TypeSourceInfo *>(Val: Operand); }
884
885 /// Retrieves the type operand of this typeid() expression after
886 /// various required adjustments (removing reference types, cv-qualifiers).
887 QualType getTypeOperand(const ASTContext &Context) const;
888
889 /// Retrieve source information for the type operand.
890 TypeSourceInfo *getTypeOperandSourceInfo() const {
891 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
892 return cast<TypeSourceInfo *>(Val: Operand);
893 }
894 Expr *getExprOperand() const {
895 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
896 return static_cast<Expr *>(cast<Stmt *>(Val: Operand));
897 }
898
899 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
900 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
901 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
902 void setSourceRange(SourceRange R) { Range = R; }
903
904 static bool classof(const Stmt *T) {
905 return T->getStmtClass() == CXXTypeidExprClass;
906 }
907
908 // Iterators
909 child_range children() {
910 if (isTypeOperand())
911 return child_range(child_iterator(), child_iterator());
912 auto **begin = reinterpret_cast<Stmt **>(&Operand);
913 return child_range(begin, begin + 1);
914 }
915
916 const_child_range children() const {
917 if (isTypeOperand())
918 return const_child_range(const_child_iterator(), const_child_iterator());
919
920 auto **begin =
921 reinterpret_cast<Stmt **>(&const_cast<CXXTypeidExpr *>(this)->Operand);
922 return const_child_range(begin, begin + 1);
923 }
924
925 /// Whether this is of a form like "typeid(*ptr)" that can throw a
926 /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
927 bool hasNullCheck() const;
928};
929
930/// A member reference to an MSPropertyDecl.
931///
932/// This expression always has pseudo-object type, and therefore it is
933/// typically not encountered in a fully-typechecked expression except
934/// within the syntactic form of a PseudoObjectExpr.
935class MSPropertyRefExpr : public Expr {
936 Expr *BaseExpr;
937 MSPropertyDecl *TheDecl;
938 SourceLocation MemberLoc;
939 bool IsArrow;
940 NestedNameSpecifierLoc QualifierLoc;
941
942public:
943 friend class ASTStmtReader;
944
945 MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
946 QualType ty, ExprValueKind VK,
947 NestedNameSpecifierLoc qualifierLoc, SourceLocation nameLoc)
948 : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary), BaseExpr(baseExpr),
949 TheDecl(decl), MemberLoc(nameLoc), IsArrow(isArrow),
950 QualifierLoc(qualifierLoc) {
951 setDependence(computeDependence(E: this));
952 }
953
954 MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
955
956 SourceRange getSourceRange() const LLVM_READONLY {
957 return SourceRange(getBeginLoc(), getEndLoc());
958 }
959
960 bool isImplicitAccess() const {
961 return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
962 }
963
964 SourceLocation getBeginLoc() const {
965 if (!isImplicitAccess())
966 return BaseExpr->getBeginLoc();
967 else if (QualifierLoc)
968 return QualifierLoc.getBeginLoc();
969 else
970 return MemberLoc;
971 }
972
973 SourceLocation getEndLoc() const { return getMemberLoc(); }
974
975 child_range children() {
976 return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
977 }
978
979 const_child_range children() const {
980 auto Children = const_cast<MSPropertyRefExpr *>(this)->children();
981 return const_child_range(Children.begin(), Children.end());
982 }
983
984 static bool classof(const Stmt *T) {
985 return T->getStmtClass() == MSPropertyRefExprClass;
986 }
987
988 Expr *getBaseExpr() const { return BaseExpr; }
989 MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
990 bool isArrow() const { return IsArrow; }
991 SourceLocation getMemberLoc() const { return MemberLoc; }
992 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
993};
994
995/// MS property subscript expression.
996/// MSVC supports 'property' attribute and allows to apply it to the
997/// declaration of an empty array in a class or structure definition.
998/// For example:
999/// \code
1000/// __declspec(property(get=GetX, put=PutX)) int x[];
1001/// \endcode
1002/// The above statement indicates that x[] can be used with one or more array
1003/// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and
1004/// p->x[a][b] = i will be turned into p->PutX(a, b, i).
1005/// This is a syntactic pseudo-object expression.
1006class MSPropertySubscriptExpr : public Expr {
1007 friend class ASTStmtReader;
1008
1009 enum { BASE_EXPR, IDX_EXPR, NUM_SUBEXPRS = 2 };
1010
1011 Stmt *SubExprs[NUM_SUBEXPRS];
1012 SourceLocation RBracketLoc;
1013
1014 void setBase(Expr *Base) { SubExprs[BASE_EXPR] = Base; }
1015 void setIdx(Expr *Idx) { SubExprs[IDX_EXPR] = Idx; }
1016
1017public:
1018 MSPropertySubscriptExpr(Expr *Base, Expr *Idx, QualType Ty, ExprValueKind VK,
1019 ExprObjectKind OK, SourceLocation RBracketLoc)
1020 : Expr(MSPropertySubscriptExprClass, Ty, VK, OK),
1021 RBracketLoc(RBracketLoc) {
1022 SubExprs[BASE_EXPR] = Base;
1023 SubExprs[IDX_EXPR] = Idx;
1024 setDependence(computeDependence(E: this));
1025 }
1026
1027 /// Create an empty array subscript expression.
1028 explicit MSPropertySubscriptExpr(EmptyShell Shell)
1029 : Expr(MSPropertySubscriptExprClass, Shell) {}
1030
1031 Expr *getBase() { return cast<Expr>(Val: SubExprs[BASE_EXPR]); }
1032 const Expr *getBase() const { return cast<Expr>(Val: SubExprs[BASE_EXPR]); }
1033
1034 Expr *getIdx() { return cast<Expr>(Val: SubExprs[IDX_EXPR]); }
1035 const Expr *getIdx() const { return cast<Expr>(Val: SubExprs[IDX_EXPR]); }
1036
1037 SourceLocation getBeginLoc() const LLVM_READONLY {
1038 return getBase()->getBeginLoc();
1039 }
1040
1041 SourceLocation getEndLoc() const LLVM_READONLY { return RBracketLoc; }
1042
1043 SourceLocation getRBracketLoc() const { return RBracketLoc; }
1044 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1045
1046 SourceLocation getExprLoc() const LLVM_READONLY {
1047 return getBase()->getExprLoc();
1048 }
1049
1050 static bool classof(const Stmt *T) {
1051 return T->getStmtClass() == MSPropertySubscriptExprClass;
1052 }
1053
1054 // Iterators
1055 child_range children() {
1056 return child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
1057 }
1058
1059 const_child_range children() const {
1060 return const_child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
1061 }
1062};
1063
1064/// A Microsoft C++ @c __uuidof expression, which gets
1065/// the _GUID that corresponds to the supplied type or expression.
1066///
1067/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
1068class CXXUuidofExpr : public Expr {
1069 friend class ASTStmtReader;
1070
1071private:
1072 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
1073 MSGuidDecl *Guid;
1074 SourceRange Range;
1075
1076public:
1077 CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, MSGuidDecl *Guid,
1078 SourceRange R)
1079 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
1080 Guid(Guid), Range(R) {
1081 setDependence(computeDependence(E: this));
1082 }
1083
1084 CXXUuidofExpr(QualType Ty, Expr *Operand, MSGuidDecl *Guid, SourceRange R)
1085 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
1086 Guid(Guid), Range(R) {
1087 setDependence(computeDependence(E: this));
1088 }
1089
1090 CXXUuidofExpr(EmptyShell Empty, bool isExpr)
1091 : Expr(CXXUuidofExprClass, Empty) {
1092 if (isExpr)
1093 Operand = (Expr*)nullptr;
1094 else
1095 Operand = (TypeSourceInfo*)nullptr;
1096 }
1097
1098 bool isTypeOperand() const { return isa<TypeSourceInfo *>(Val: Operand); }
1099
1100 /// Retrieves the type operand of this __uuidof() expression after
1101 /// various required adjustments (removing reference types, cv-qualifiers).
1102 QualType getTypeOperand(ASTContext &Context) const;
1103
1104 /// Retrieve source information for the type operand.
1105 TypeSourceInfo *getTypeOperandSourceInfo() const {
1106 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
1107 return cast<TypeSourceInfo *>(Val: Operand);
1108 }
1109 Expr *getExprOperand() const {
1110 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
1111 return static_cast<Expr *>(cast<Stmt *>(Val: Operand));
1112 }
1113
1114 MSGuidDecl *getGuidDecl() const { return Guid; }
1115
1116 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
1117 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
1118 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1119 void setSourceRange(SourceRange R) { Range = R; }
1120
1121 static bool classof(const Stmt *T) {
1122 return T->getStmtClass() == CXXUuidofExprClass;
1123 }
1124
1125 // Iterators
1126 child_range children() {
1127 if (isTypeOperand())
1128 return child_range(child_iterator(), child_iterator());
1129 auto **begin = reinterpret_cast<Stmt **>(&Operand);
1130 return child_range(begin, begin + 1);
1131 }
1132
1133 const_child_range children() const {
1134 if (isTypeOperand())
1135 return const_child_range(const_child_iterator(), const_child_iterator());
1136 auto **begin =
1137 reinterpret_cast<Stmt **>(&const_cast<CXXUuidofExpr *>(this)->Operand);
1138 return const_child_range(begin, begin + 1);
1139 }
1140};
1141
1142/// Represents the \c this expression in C++.
1143///
1144/// This is a pointer to the object on which the current member function is
1145/// executing (C++ [expr.prim]p3). Example:
1146///
1147/// \code
1148/// class Foo {
1149/// public:
1150/// void bar();
1151/// void test() { this->bar(); }
1152/// };
1153/// \endcode
1154class CXXThisExpr : public Expr {
1155 CXXThisExpr(SourceLocation L, QualType Ty, bool IsImplicit, ExprValueKind VK)
1156 : Expr(CXXThisExprClass, Ty, VK, OK_Ordinary) {
1157 CXXThisExprBits.IsImplicit = IsImplicit;
1158 CXXThisExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
1159 CXXThisExprBits.Loc = L;
1160 setDependence(computeDependence(E: this));
1161 }
1162
1163 CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
1164
1165public:
1166 static CXXThisExpr *Create(const ASTContext &Ctx, SourceLocation L,
1167 QualType Ty, bool IsImplicit);
1168
1169 static CXXThisExpr *CreateEmpty(const ASTContext &Ctx);
1170
1171 SourceLocation getLocation() const { return CXXThisExprBits.Loc; }
1172 void setLocation(SourceLocation L) { CXXThisExprBits.Loc = L; }
1173
1174 SourceLocation getBeginLoc() const { return getLocation(); }
1175 SourceLocation getEndLoc() const { return getLocation(); }
1176
1177 bool isImplicit() const { return CXXThisExprBits.IsImplicit; }
1178 void setImplicit(bool I) { CXXThisExprBits.IsImplicit = I; }
1179
1180 bool isCapturedByCopyInLambdaWithExplicitObjectParameter() const {
1181 return CXXThisExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter;
1182 }
1183
1184 void setCapturedByCopyInLambdaWithExplicitObjectParameter(bool Set) {
1185 CXXThisExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = Set;
1186 setDependence(computeDependence(E: this));
1187 }
1188
1189 static bool classof(const Stmt *T) {
1190 return T->getStmtClass() == CXXThisExprClass;
1191 }
1192
1193 // Iterators
1194 child_range children() {
1195 return child_range(child_iterator(), child_iterator());
1196 }
1197
1198 const_child_range children() const {
1199 return const_child_range(const_child_iterator(), const_child_iterator());
1200 }
1201};
1202
1203/// A C++ throw-expression (C++ [except.throw]).
1204///
1205/// This handles 'throw' (for re-throwing the current exception) and
1206/// 'throw' assignment-expression. When assignment-expression isn't
1207/// present, Op will be null.
1208class CXXThrowExpr : public Expr {
1209 friend class ASTStmtReader;
1210
1211 /// The optional expression in the throw statement.
1212 Stmt *Operand;
1213
1214public:
1215 // \p Ty is the void type which is used as the result type of the
1216 // expression. The \p Loc is the location of the throw keyword.
1217 // \p Operand is the expression in the throw statement, and can be
1218 // null if not present.
1219 CXXThrowExpr(Expr *Operand, QualType Ty, SourceLocation Loc,
1220 bool IsThrownVariableInScope)
1221 : Expr(CXXThrowExprClass, Ty, VK_PRValue, OK_Ordinary), Operand(Operand) {
1222 CXXThrowExprBits.ThrowLoc = Loc;
1223 CXXThrowExprBits.IsThrownVariableInScope = IsThrownVariableInScope;
1224 setDependence(computeDependence(E: this));
1225 }
1226 CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
1227
1228 const Expr *getSubExpr() const { return cast_or_null<Expr>(Val: Operand); }
1229 Expr *getSubExpr() { return cast_or_null<Expr>(Val: Operand); }
1230
1231 SourceLocation getThrowLoc() const { return CXXThrowExprBits.ThrowLoc; }
1232
1233 /// Determines whether the variable thrown by this expression (if any!)
1234 /// is within the innermost try block.
1235 ///
1236 /// This information is required to determine whether the NRVO can apply to
1237 /// this variable.
1238 bool isThrownVariableInScope() const {
1239 return CXXThrowExprBits.IsThrownVariableInScope;
1240 }
1241
1242 SourceLocation getBeginLoc() const { return getThrowLoc(); }
1243 SourceLocation getEndLoc() const LLVM_READONLY {
1244 if (!getSubExpr())
1245 return getThrowLoc();
1246 return getSubExpr()->getEndLoc();
1247 }
1248
1249 static bool classof(const Stmt *T) {
1250 return T->getStmtClass() == CXXThrowExprClass;
1251 }
1252
1253 // Iterators
1254 child_range children() {
1255 return child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1256 }
1257
1258 const_child_range children() const {
1259 return const_child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1260 }
1261};
1262
1263/// A default argument (C++ [dcl.fct.default]).
1264///
1265/// This wraps up a function call argument that was created from the
1266/// corresponding parameter's default argument, when the call did not
1267/// explicitly supply arguments for all of the parameters.
1268class CXXDefaultArgExpr final
1269 : public Expr,
1270 private llvm::TrailingObjects<CXXDefaultArgExpr, Expr *> {
1271 friend class ASTStmtReader;
1272 friend class ASTReader;
1273 friend TrailingObjects;
1274
1275 /// The parameter whose default is being used.
1276 ParmVarDecl *Param;
1277
1278 /// The context where the default argument expression was used.
1279 DeclContext *UsedContext;
1280
1281 CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param,
1282 Expr *RewrittenExpr, DeclContext *UsedContext)
1283 : Expr(SC,
1284 Param->hasUnparsedDefaultArg()
1285 ? Param->getType().getNonReferenceType()
1286 : Param->getDefaultArg()->getType(),
1287 Param->getDefaultArg()->getValueKind(),
1288 Param->getDefaultArg()->getObjectKind()),
1289 Param(Param), UsedContext(UsedContext) {
1290 CXXDefaultArgExprBits.Loc = Loc;
1291 CXXDefaultArgExprBits.HasRewrittenInit = RewrittenExpr != nullptr;
1292 if (RewrittenExpr)
1293 *getTrailingObjects() = RewrittenExpr;
1294 setDependence(computeDependence(E: this));
1295 }
1296
1297 CXXDefaultArgExpr(EmptyShell Empty, bool HasRewrittenInit)
1298 : Expr(CXXDefaultArgExprClass, Empty) {
1299 CXXDefaultArgExprBits.HasRewrittenInit = HasRewrittenInit;
1300 }
1301
1302public:
1303 static CXXDefaultArgExpr *CreateEmpty(const ASTContext &C,
1304 bool HasRewrittenInit);
1305
1306 // \p Param is the parameter whose default argument is used by this
1307 // expression.
1308 static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
1309 ParmVarDecl *Param, Expr *RewrittenExpr,
1310 DeclContext *UsedContext);
1311 // Retrieve the parameter that the argument was created from.
1312 const ParmVarDecl *getParam() const { return Param; }
1313 ParmVarDecl *getParam() { return Param; }
1314
1315 bool hasRewrittenInit() const {
1316 return CXXDefaultArgExprBits.HasRewrittenInit;
1317 }
1318
1319 // Retrieve the argument to the function call.
1320 Expr *getExpr();
1321 const Expr *getExpr() const {
1322 return const_cast<CXXDefaultArgExpr *>(this)->getExpr();
1323 }
1324
1325 Expr *getRewrittenExpr() {
1326 return hasRewrittenInit() ? *getTrailingObjects() : nullptr;
1327 }
1328
1329 const Expr *getRewrittenExpr() const {
1330 return const_cast<CXXDefaultArgExpr *>(this)->getRewrittenExpr();
1331 }
1332
1333 // Retrieve the rewritten init expression (for an init expression containing
1334 // immediate calls) with the top level FullExpr and ConstantExpr stripped off.
1335 Expr *getAdjustedRewrittenExpr();
1336 const Expr *getAdjustedRewrittenExpr() const {
1337 return const_cast<CXXDefaultArgExpr *>(this)->getAdjustedRewrittenExpr();
1338 }
1339
1340 const DeclContext *getUsedContext() const { return UsedContext; }
1341 DeclContext *getUsedContext() { return UsedContext; }
1342
1343 /// Retrieve the location where this default argument was actually used.
1344 SourceLocation getUsedLocation() const { return CXXDefaultArgExprBits.Loc; }
1345
1346 /// Default argument expressions have no representation in the
1347 /// source, so they have an empty source range.
1348 SourceLocation getBeginLoc() const { return SourceLocation(); }
1349 SourceLocation getEndLoc() const { return SourceLocation(); }
1350
1351 SourceLocation getExprLoc() const { return getUsedLocation(); }
1352
1353 static bool classof(const Stmt *T) {
1354 return T->getStmtClass() == CXXDefaultArgExprClass;
1355 }
1356
1357 // Iterators
1358 child_range children() {
1359 return child_range(child_iterator(), child_iterator());
1360 }
1361
1362 const_child_range children() const {
1363 return const_child_range(const_child_iterator(), const_child_iterator());
1364 }
1365};
1366
1367/// A use of a default initializer in a constructor or in aggregate
1368/// initialization.
1369///
1370/// This wraps a use of a C++ default initializer (technically,
1371/// a brace-or-equal-initializer for a non-static data member) when it
1372/// is implicitly used in a mem-initializer-list in a constructor
1373/// (C++11 [class.base.init]p8) or in aggregate initialization
1374/// (C++1y [dcl.init.aggr]p7).
1375class CXXDefaultInitExpr final
1376 : public Expr,
1377 private llvm::TrailingObjects<CXXDefaultInitExpr, Expr *> {
1378
1379 friend class ASTStmtReader;
1380 friend class ASTReader;
1381 friend TrailingObjects;
1382 /// The field whose default is being used.
1383 FieldDecl *Field;
1384
1385 /// The context where the default initializer expression was used.
1386 DeclContext *UsedContext;
1387
1388 CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
1389 FieldDecl *Field, QualType Ty, DeclContext *UsedContext,
1390 Expr *RewrittenInitExpr);
1391
1392 CXXDefaultInitExpr(EmptyShell Empty, bool HasRewrittenInit)
1393 : Expr(CXXDefaultInitExprClass, Empty) {
1394 CXXDefaultInitExprBits.HasRewrittenInit = HasRewrittenInit;
1395 }
1396
1397public:
1398 static CXXDefaultInitExpr *CreateEmpty(const ASTContext &C,
1399 bool HasRewrittenInit);
1400 /// \p Field is the non-static data member whose default initializer is used
1401 /// by this expression.
1402 static CXXDefaultInitExpr *Create(const ASTContext &Ctx, SourceLocation Loc,
1403 FieldDecl *Field, DeclContext *UsedContext,
1404 Expr *RewrittenInitExpr);
1405
1406 bool hasRewrittenInit() const {
1407 return CXXDefaultInitExprBits.HasRewrittenInit;
1408 }
1409
1410 /// Get the field whose initializer will be used.
1411 FieldDecl *getField() { return Field; }
1412 const FieldDecl *getField() const { return Field; }
1413
1414 /// Get the initialization expression that will be used.
1415 Expr *getExpr();
1416 const Expr *getExpr() const {
1417 return const_cast<CXXDefaultInitExpr *>(this)->getExpr();
1418 }
1419
1420 /// Retrieve the initializing expression with evaluated immediate calls, if
1421 /// any.
1422 const Expr *getRewrittenExpr() const {
1423 assert(hasRewrittenInit() && "expected a rewritten init expression");
1424 return *getTrailingObjects();
1425 }
1426
1427 /// Retrieve the initializing expression with evaluated immediate calls, if
1428 /// any.
1429 Expr *getRewrittenExpr() {
1430 assert(hasRewrittenInit() && "expected a rewritten init expression");
1431 return *getTrailingObjects();
1432 }
1433
1434 const DeclContext *getUsedContext() const { return UsedContext; }
1435 DeclContext *getUsedContext() { return UsedContext; }
1436
1437 /// Retrieve the location where this default initializer expression was
1438 /// actually used.
1439 SourceLocation getUsedLocation() const { return getBeginLoc(); }
1440
1441 SourceLocation getBeginLoc() const { return CXXDefaultInitExprBits.Loc; }
1442 SourceLocation getEndLoc() const { return CXXDefaultInitExprBits.Loc; }
1443
1444 static bool classof(const Stmt *T) {
1445 return T->getStmtClass() == CXXDefaultInitExprClass;
1446 }
1447
1448 // Iterators
1449 child_range children() {
1450 return child_range(child_iterator(), child_iterator());
1451 }
1452
1453 const_child_range children() const {
1454 return const_child_range(const_child_iterator(), const_child_iterator());
1455 }
1456};
1457
1458/// Represents a C++ temporary.
1459class CXXTemporary {
1460 /// The destructor that needs to be called.
1461 const CXXDestructorDecl *Destructor;
1462
1463 explicit CXXTemporary(const CXXDestructorDecl *destructor)
1464 : Destructor(destructor) {}
1465
1466public:
1467 static CXXTemporary *Create(const ASTContext &C,
1468 const CXXDestructorDecl *Destructor);
1469
1470 const CXXDestructorDecl *getDestructor() const { return Destructor; }
1471
1472 void setDestructor(const CXXDestructorDecl *Dtor) {
1473 Destructor = Dtor;
1474 }
1475};
1476
1477/// Represents binding an expression to a temporary.
1478///
1479/// This ensures the destructor is called for the temporary. It should only be
1480/// needed for non-POD, non-trivially destructable class types. For example:
1481///
1482/// \code
1483/// struct S {
1484/// S() { } // User defined constructor makes S non-POD.
1485/// ~S() { } // User defined destructor makes it non-trivial.
1486/// };
1487/// void test() {
1488/// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1489/// }
1490/// \endcode
1491///
1492/// Destructor might be null if destructor declaration is not valid.
1493class CXXBindTemporaryExpr : public Expr {
1494 CXXTemporary *Temp = nullptr;
1495 Stmt *SubExpr = nullptr;
1496
1497 CXXBindTemporaryExpr(CXXTemporary *temp, Expr *SubExpr)
1498 : Expr(CXXBindTemporaryExprClass, SubExpr->getType(), VK_PRValue,
1499 OK_Ordinary),
1500 Temp(temp), SubExpr(SubExpr) {
1501 setDependence(computeDependence(E: this));
1502 }
1503
1504public:
1505 CXXBindTemporaryExpr(EmptyShell Empty)
1506 : Expr(CXXBindTemporaryExprClass, Empty) {}
1507
1508 static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
1509 Expr* SubExpr);
1510
1511 CXXTemporary *getTemporary() { return Temp; }
1512 const CXXTemporary *getTemporary() const { return Temp; }
1513 void setTemporary(CXXTemporary *T) { Temp = T; }
1514
1515 const Expr *getSubExpr() const { return cast<Expr>(Val: SubExpr); }
1516 Expr *getSubExpr() { return cast<Expr>(Val: SubExpr); }
1517 void setSubExpr(Expr *E) { SubExpr = E; }
1518
1519 SourceLocation getBeginLoc() const LLVM_READONLY {
1520 return SubExpr->getBeginLoc();
1521 }
1522
1523 SourceLocation getEndLoc() const LLVM_READONLY {
1524 return SubExpr->getEndLoc();
1525 }
1526
1527 // Implement isa/cast/dyncast/etc.
1528 static bool classof(const Stmt *T) {
1529 return T->getStmtClass() == CXXBindTemporaryExprClass;
1530 }
1531
1532 // Iterators
1533 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1534
1535 const_child_range children() const {
1536 return const_child_range(&SubExpr, &SubExpr + 1);
1537 }
1538};
1539
1540enum class CXXConstructionKind {
1541 Complete,
1542 NonVirtualBase,
1543 VirtualBase,
1544 Delegating
1545};
1546
1547/// Represents a call to a C++ constructor.
1548class CXXConstructExpr : public Expr {
1549 friend class ASTStmtReader;
1550
1551 /// A pointer to the constructor which will be ultimately called.
1552 CXXConstructorDecl *Constructor;
1553
1554 SourceRange ParenOrBraceRange;
1555
1556 /// The number of arguments.
1557 unsigned NumArgs;
1558
1559 // We would like to stash the arguments of the constructor call after
1560 // CXXConstructExpr. However CXXConstructExpr is used as a base class of
1561 // CXXTemporaryObjectExpr which makes the use of llvm::TrailingObjects
1562 // impossible.
1563 //
1564 // Instead we manually stash the trailing object after the full object
1565 // containing CXXConstructExpr (that is either CXXConstructExpr or
1566 // CXXTemporaryObjectExpr).
1567 //
1568 // The trailing objects are:
1569 //
1570 // * An array of getNumArgs() "Stmt *" for the arguments of the
1571 // constructor call.
1572
1573 /// Return a pointer to the start of the trailing arguments.
1574 /// Defined just after CXXTemporaryObjectExpr.
1575 inline Stmt **getTrailingArgs();
1576 const Stmt *const *getTrailingArgs() const {
1577 return const_cast<CXXConstructExpr *>(this)->getTrailingArgs();
1578 }
1579
1580protected:
1581 /// Build a C++ construction expression.
1582 CXXConstructExpr(StmtClass SC, QualType Ty, SourceLocation Loc,
1583 CXXConstructorDecl *Ctor, bool Elidable,
1584 ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1585 bool ListInitialization, bool StdInitListInitialization,
1586 bool ZeroInitialization, CXXConstructionKind ConstructKind,
1587 SourceRange ParenOrBraceRange);
1588
1589 /// Build an empty C++ construction expression.
1590 CXXConstructExpr(StmtClass SC, EmptyShell Empty, unsigned NumArgs);
1591
1592 /// Return the size in bytes of the trailing objects. Used by
1593 /// CXXTemporaryObjectExpr to allocate the right amount of storage.
1594 static unsigned sizeOfTrailingObjects(unsigned NumArgs) {
1595 return NumArgs * sizeof(Stmt *);
1596 }
1597
1598public:
1599 /// Create a C++ construction expression.
1600 static CXXConstructExpr *
1601 Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
1602 CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
1603 bool HadMultipleCandidates, bool ListInitialization,
1604 bool StdInitListInitialization, bool ZeroInitialization,
1605 CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange);
1606
1607 /// Create an empty C++ construction expression.
1608 static CXXConstructExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs);
1609
1610 /// Get the constructor that this expression will (ultimately) call.
1611 CXXConstructorDecl *getConstructor() const { return Constructor; }
1612
1613 SourceLocation getLocation() const { return CXXConstructExprBits.Loc; }
1614 void setLocation(SourceLocation Loc) { CXXConstructExprBits.Loc = Loc; }
1615
1616 /// Whether this construction is elidable.
1617 bool isElidable() const { return CXXConstructExprBits.Elidable; }
1618 void setElidable(bool E) { CXXConstructExprBits.Elidable = E; }
1619
1620 /// Whether the referred constructor was resolved from
1621 /// an overloaded set having size greater than 1.
1622 bool hadMultipleCandidates() const {
1623 return CXXConstructExprBits.HadMultipleCandidates;
1624 }
1625 void setHadMultipleCandidates(bool V) {
1626 CXXConstructExprBits.HadMultipleCandidates = V;
1627 }
1628
1629 /// Whether this constructor call was written as list-initialization.
1630 bool isListInitialization() const {
1631 return CXXConstructExprBits.ListInitialization;
1632 }
1633 void setListInitialization(bool V) {
1634 CXXConstructExprBits.ListInitialization = V;
1635 }
1636
1637 /// Whether this constructor call was written as list-initialization,
1638 /// but was interpreted as forming a std::initializer_list<T> from the list
1639 /// and passing that as a single constructor argument.
1640 /// See C++11 [over.match.list]p1 bullet 1.
1641 bool isStdInitListInitialization() const {
1642 return CXXConstructExprBits.StdInitListInitialization;
1643 }
1644 void setStdInitListInitialization(bool V) {
1645 CXXConstructExprBits.StdInitListInitialization = V;
1646 }
1647
1648 /// Whether this construction first requires
1649 /// zero-initialization before the initializer is called.
1650 bool requiresZeroInitialization() const {
1651 return CXXConstructExprBits.ZeroInitialization;
1652 }
1653 void setRequiresZeroInitialization(bool ZeroInit) {
1654 CXXConstructExprBits.ZeroInitialization = ZeroInit;
1655 }
1656
1657 /// Determine whether this constructor is actually constructing
1658 /// a base class (rather than a complete object).
1659 CXXConstructionKind getConstructionKind() const {
1660 return static_cast<CXXConstructionKind>(
1661 CXXConstructExprBits.ConstructionKind);
1662 }
1663 void setConstructionKind(CXXConstructionKind CK) {
1664 CXXConstructExprBits.ConstructionKind = llvm::to_underlying(E: CK);
1665 }
1666
1667 using arg_iterator = ExprIterator;
1668 using const_arg_iterator = ConstExprIterator;
1669 using arg_range = llvm::iterator_range<arg_iterator>;
1670 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
1671
1672 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
1673 const_arg_range arguments() const {
1674 return const_arg_range(arg_begin(), arg_end());
1675 }
1676
1677 arg_iterator arg_begin() { return getTrailingArgs(); }
1678 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
1679 const_arg_iterator arg_begin() const { return getTrailingArgs(); }
1680 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
1681
1682 Expr **getArgs() { return reinterpret_cast<Expr **>(getTrailingArgs()); }
1683 const Expr *const *getArgs() const {
1684 return reinterpret_cast<const Expr *const *>(getTrailingArgs());
1685 }
1686
1687 /// Return the number of arguments to the constructor call.
1688 unsigned getNumArgs() const { return NumArgs; }
1689
1690 /// Return the specified argument.
1691 Expr *getArg(unsigned Arg) {
1692 assert(Arg < getNumArgs() && "Arg access out of range!");
1693 return getArgs()[Arg];
1694 }
1695 const Expr *getArg(unsigned Arg) const {
1696 assert(Arg < getNumArgs() && "Arg access out of range!");
1697 return getArgs()[Arg];
1698 }
1699
1700 /// Set the specified argument.
1701 void setArg(unsigned Arg, Expr *ArgExpr) {
1702 assert(Arg < getNumArgs() && "Arg access out of range!");
1703 getArgs()[Arg] = ArgExpr;
1704 }
1705
1706 bool isImmediateEscalating() const {
1707 return CXXConstructExprBits.IsImmediateEscalating;
1708 }
1709
1710 void setIsImmediateEscalating(bool Set) {
1711 CXXConstructExprBits.IsImmediateEscalating = Set;
1712 }
1713
1714 SourceLocation getBeginLoc() const LLVM_READONLY;
1715 SourceLocation getEndLoc() const LLVM_READONLY;
1716 SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
1717 void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
1718
1719 static bool classof(const Stmt *T) {
1720 return T->getStmtClass() == CXXConstructExprClass ||
1721 T->getStmtClass() == CXXTemporaryObjectExprClass;
1722 }
1723
1724 // Iterators
1725 child_range children() {
1726 return child_range(getTrailingArgs(), getTrailingArgs() + getNumArgs());
1727 }
1728
1729 const_child_range children() const {
1730 auto Children = const_cast<CXXConstructExpr *>(this)->children();
1731 return const_child_range(Children.begin(), Children.end());
1732 }
1733};
1734
1735/// Represents a call to an inherited base class constructor from an
1736/// inheriting constructor. This call implicitly forwards the arguments from
1737/// the enclosing context (an inheriting constructor) to the specified inherited
1738/// base class constructor.
1739class CXXInheritedCtorInitExpr : public Expr {
1740private:
1741 CXXConstructorDecl *Constructor = nullptr;
1742
1743 /// The location of the using declaration.
1744 SourceLocation Loc;
1745
1746 /// Whether this is the construction of a virtual base.
1747 LLVM_PREFERRED_TYPE(bool)
1748 unsigned ConstructsVirtualBase : 1;
1749
1750 /// Whether the constructor is inherited from a virtual base class of the
1751 /// class that we construct.
1752 LLVM_PREFERRED_TYPE(bool)
1753 unsigned InheritedFromVirtualBase : 1;
1754
1755public:
1756 friend class ASTStmtReader;
1757
1758 /// Construct a C++ inheriting construction expression.
1759 CXXInheritedCtorInitExpr(SourceLocation Loc, QualType T,
1760 CXXConstructorDecl *Ctor, bool ConstructsVirtualBase,
1761 bool InheritedFromVirtualBase)
1762 : Expr(CXXInheritedCtorInitExprClass, T, VK_PRValue, OK_Ordinary),
1763 Constructor(Ctor), Loc(Loc),
1764 ConstructsVirtualBase(ConstructsVirtualBase),
1765 InheritedFromVirtualBase(InheritedFromVirtualBase) {
1766 assert(!T->isDependentType());
1767 setDependence(ExprDependence::None);
1768 }
1769
1770 /// Construct an empty C++ inheriting construction expression.
1771 explicit CXXInheritedCtorInitExpr(EmptyShell Empty)
1772 : Expr(CXXInheritedCtorInitExprClass, Empty),
1773 ConstructsVirtualBase(false), InheritedFromVirtualBase(false) {}
1774
1775 /// Get the constructor that this expression will call.
1776 CXXConstructorDecl *getConstructor() const { return Constructor; }
1777
1778 /// Determine whether this constructor is actually constructing
1779 /// a base class (rather than a complete object).
1780 bool constructsVBase() const { return ConstructsVirtualBase; }
1781 CXXConstructionKind getConstructionKind() const {
1782 return ConstructsVirtualBase ? CXXConstructionKind::VirtualBase
1783 : CXXConstructionKind::NonVirtualBase;
1784 }
1785
1786 /// Determine whether the inherited constructor is inherited from a
1787 /// virtual base of the object we construct. If so, we are not responsible
1788 /// for calling the inherited constructor (the complete object constructor
1789 /// does that), and so we don't need to pass any arguments.
1790 bool inheritedFromVBase() const { return InheritedFromVirtualBase; }
1791
1792 SourceLocation getLocation() const LLVM_READONLY { return Loc; }
1793 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1794 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1795
1796 static bool classof(const Stmt *T) {
1797 return T->getStmtClass() == CXXInheritedCtorInitExprClass;
1798 }
1799
1800 child_range children() {
1801 return child_range(child_iterator(), child_iterator());
1802 }
1803
1804 const_child_range children() const {
1805 return const_child_range(const_child_iterator(), const_child_iterator());
1806 }
1807};
1808
1809/// Represents an explicit C++ type conversion that uses "functional"
1810/// notation (C++ [expr.type.conv]).
1811///
1812/// Example:
1813/// \code
1814/// x = int(0.5);
1815/// \endcode
1816class CXXFunctionalCastExpr final
1817 : public ExplicitCastExpr,
1818 private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *,
1819 FPOptionsOverride> {
1820 SourceLocation LParenLoc;
1821 SourceLocation RParenLoc;
1822
1823 CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1824 TypeSourceInfo *writtenTy, CastKind kind,
1825 Expr *castExpr, unsigned pathSize,
1826 FPOptionsOverride FPO, SourceLocation lParenLoc,
1827 SourceLocation rParenLoc)
1828 : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind, castExpr,
1829 pathSize, FPO.requiresTrailingStorage(), writtenTy),
1830 LParenLoc(lParenLoc), RParenLoc(rParenLoc) {
1831 if (hasStoredFPFeatures())
1832 *getTrailingFPFeatures() = FPO;
1833 }
1834
1835 explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize,
1836 bool HasFPFeatures)
1837 : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize,
1838 HasFPFeatures) {}
1839
1840 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
1841 return path_size();
1842 }
1843
1844public:
1845 friend class CastExpr;
1846 friend TrailingObjects;
1847
1848 static CXXFunctionalCastExpr *
1849 Create(const ASTContext &Context, QualType T, ExprValueKind VK,
1850 TypeSourceInfo *Written, CastKind Kind, Expr *Op,
1851 const CXXCastPath *Path, FPOptionsOverride FPO, SourceLocation LPLoc,
1852 SourceLocation RPLoc);
1853 static CXXFunctionalCastExpr *
1854 CreateEmpty(const ASTContext &Context, unsigned PathSize, bool HasFPFeatures);
1855
1856 SourceLocation getLParenLoc() const { return LParenLoc; }
1857 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1858 SourceLocation getRParenLoc() const { return RParenLoc; }
1859 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1860
1861 /// Determine whether this expression models list-initialization.
1862 bool isListInitialization() const { return LParenLoc.isInvalid(); }
1863
1864 SourceLocation getBeginLoc() const LLVM_READONLY;
1865 SourceLocation getEndLoc() const LLVM_READONLY;
1866
1867 static bool classof(const Stmt *T) {
1868 return T->getStmtClass() == CXXFunctionalCastExprClass;
1869 }
1870};
1871
1872/// Represents a C++ functional cast expression that builds a
1873/// temporary object.
1874///
1875/// This expression type represents a C++ "functional" cast
1876/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1877/// constructor to build a temporary object. With N == 1 arguments the
1878/// functional cast expression will be represented by CXXFunctionalCastExpr.
1879/// Example:
1880/// \code
1881/// struct X { X(int, float); }
1882///
1883/// X create_X() {
1884/// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1885/// };
1886/// \endcode
1887class CXXTemporaryObjectExpr final : public CXXConstructExpr {
1888 friend class ASTStmtReader;
1889
1890 // CXXTemporaryObjectExpr has some trailing objects belonging
1891 // to CXXConstructExpr. See the comment inside CXXConstructExpr
1892 // for more details.
1893
1894 TypeSourceInfo *TSI;
1895
1896 CXXTemporaryObjectExpr(CXXConstructorDecl *Cons, QualType Ty,
1897 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1898 SourceRange ParenOrBraceRange,
1899 bool HadMultipleCandidates, bool ListInitialization,
1900 bool StdInitListInitialization,
1901 bool ZeroInitialization);
1902
1903 CXXTemporaryObjectExpr(EmptyShell Empty, unsigned NumArgs);
1904
1905public:
1906 static CXXTemporaryObjectExpr *
1907 Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
1908 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1909 SourceRange ParenOrBraceRange, bool HadMultipleCandidates,
1910 bool ListInitialization, bool StdInitListInitialization,
1911 bool ZeroInitialization);
1912
1913 static CXXTemporaryObjectExpr *CreateEmpty(const ASTContext &Ctx,
1914 unsigned NumArgs);
1915
1916 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
1917
1918 SourceLocation getBeginLoc() const LLVM_READONLY;
1919 SourceLocation getEndLoc() const LLVM_READONLY;
1920
1921 static bool classof(const Stmt *T) {
1922 return T->getStmtClass() == CXXTemporaryObjectExprClass;
1923 }
1924};
1925
1926Stmt **CXXConstructExpr::getTrailingArgs() {
1927 if (auto *E = dyn_cast<CXXTemporaryObjectExpr>(Val: this))
1928 return reinterpret_cast<Stmt **>(E + 1);
1929 assert((getStmtClass() == CXXConstructExprClass) &&
1930 "Unexpected class deriving from CXXConstructExpr!");
1931 return reinterpret_cast<Stmt **>(this + 1);
1932}
1933
1934/// A C++ lambda expression, which produces a function object
1935/// (of unspecified type) that can be invoked later.
1936///
1937/// Example:
1938/// \code
1939/// void low_pass_filter(std::vector<double> &values, double cutoff) {
1940/// values.erase(std::remove_if(values.begin(), values.end(),
1941/// [=](double value) { return value > cutoff; });
1942/// }
1943/// \endcode
1944///
1945/// C++11 lambda expressions can capture local variables, either by copying
1946/// the values of those local variables at the time the function
1947/// object is constructed (not when it is called!) or by holding a
1948/// reference to the local variable. These captures can occur either
1949/// implicitly or can be written explicitly between the square
1950/// brackets ([...]) that start the lambda expression.
1951///
1952/// C++1y introduces a new form of "capture" called an init-capture that
1953/// includes an initializing expression (rather than capturing a variable),
1954/// and which can never occur implicitly.
1955class LambdaExpr final : public Expr,
1956 private llvm::TrailingObjects<LambdaExpr, Stmt *> {
1957 // LambdaExpr has some data stored in LambdaExprBits.
1958
1959 /// The source range that covers the lambda introducer ([...]).
1960 SourceRange IntroducerRange;
1961
1962 /// The source location of this lambda's capture-default ('=' or '&').
1963 SourceLocation CaptureDefaultLoc;
1964
1965 /// The location of the closing brace ('}') that completes
1966 /// the lambda.
1967 ///
1968 /// The location of the brace is also available by looking up the
1969 /// function call operator in the lambda class. However, it is
1970 /// stored here to improve the performance of getSourceRange(), and
1971 /// to avoid having to deserialize the function call operator from a
1972 /// module file just to determine the source range.
1973 SourceLocation ClosingBrace;
1974
1975 /// Construct a lambda expression.
1976 LambdaExpr(QualType T, SourceRange IntroducerRange,
1977 LambdaCaptureDefault CaptureDefault,
1978 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
1979 bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1980 SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack);
1981
1982 /// Construct an empty lambda expression.
1983 LambdaExpr(EmptyShell Empty, unsigned NumCaptures);
1984
1985 Stmt **getStoredStmts() { return getTrailingObjects(); }
1986 Stmt *const *getStoredStmts() const { return getTrailingObjects(); }
1987
1988 void initBodyIfNeeded() const;
1989
1990public:
1991 friend class ASTStmtReader;
1992 friend class ASTStmtWriter;
1993 friend TrailingObjects;
1994
1995 /// Construct a new lambda expression.
1996 static LambdaExpr *
1997 Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange,
1998 LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc,
1999 bool ExplicitParams, bool ExplicitResultType,
2000 ArrayRef<Expr *> CaptureInits, SourceLocation ClosingBrace,
2001 bool ContainsUnexpandedParameterPack);
2002
2003 /// Construct a new lambda expression that will be deserialized from
2004 /// an external source.
2005 static LambdaExpr *CreateDeserialized(const ASTContext &C,
2006 unsigned NumCaptures);
2007
2008 /// Determine the default capture kind for this lambda.
2009 LambdaCaptureDefault getCaptureDefault() const {
2010 return static_cast<LambdaCaptureDefault>(LambdaExprBits.CaptureDefault);
2011 }
2012
2013 /// Retrieve the location of this lambda's capture-default, if any.
2014 SourceLocation getCaptureDefaultLoc() const { return CaptureDefaultLoc; }
2015
2016 /// Determine whether one of this lambda's captures is an init-capture.
2017 bool isInitCapture(const LambdaCapture *Capture) const;
2018
2019 /// An iterator that walks over the captures of the lambda,
2020 /// both implicit and explicit.
2021 using capture_iterator = const LambdaCapture *;
2022
2023 /// An iterator over a range of lambda captures.
2024 using capture_range = llvm::iterator_range<capture_iterator>;
2025
2026 /// Retrieve this lambda's captures.
2027 capture_range captures() const;
2028
2029 /// Retrieve an iterator pointing to the first lambda capture.
2030 capture_iterator capture_begin() const;
2031
2032 /// Retrieve an iterator pointing past the end of the
2033 /// sequence of lambda captures.
2034 capture_iterator capture_end() const;
2035
2036 /// Determine the number of captures in this lambda.
2037 unsigned capture_size() const { return LambdaExprBits.NumCaptures; }
2038
2039 /// Retrieve this lambda's explicit captures.
2040 capture_range explicit_captures() const;
2041
2042 /// Retrieve an iterator pointing to the first explicit
2043 /// lambda capture.
2044 capture_iterator explicit_capture_begin() const;
2045
2046 /// Retrieve an iterator pointing past the end of the sequence of
2047 /// explicit lambda captures.
2048 capture_iterator explicit_capture_end() const;
2049
2050 /// Retrieve this lambda's implicit captures.
2051 capture_range implicit_captures() const;
2052
2053 /// Retrieve an iterator pointing to the first implicit
2054 /// lambda capture.
2055 capture_iterator implicit_capture_begin() const;
2056
2057 /// Retrieve an iterator pointing past the end of the sequence of
2058 /// implicit lambda captures.
2059 capture_iterator implicit_capture_end() const;
2060
2061 /// Iterator that walks over the capture initialization
2062 /// arguments.
2063 using capture_init_iterator = Expr **;
2064
2065 /// Const iterator that walks over the capture initialization
2066 /// arguments.
2067 /// FIXME: This interface is prone to being used incorrectly.
2068 using const_capture_init_iterator = Expr *const *;
2069
2070 /// Retrieve the initialization expressions for this lambda's captures.
2071 llvm::iterator_range<capture_init_iterator> capture_inits() {
2072 return llvm::make_range(x: capture_init_begin(), y: capture_init_end());
2073 }
2074
2075 /// Retrieve the initialization expressions for this lambda's captures.
2076 llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
2077 return llvm::make_range(x: capture_init_begin(), y: capture_init_end());
2078 }
2079
2080 /// Retrieve the first initialization argument for this
2081 /// lambda expression (which initializes the first capture field).
2082 capture_init_iterator capture_init_begin() {
2083 return reinterpret_cast<Expr **>(getStoredStmts());
2084 }
2085
2086 /// Retrieve the first initialization argument for this
2087 /// lambda expression (which initializes the first capture field).
2088 const_capture_init_iterator capture_init_begin() const {
2089 return reinterpret_cast<Expr *const *>(getStoredStmts());
2090 }
2091
2092 /// Retrieve the iterator pointing one past the last
2093 /// initialization argument for this lambda expression.
2094 capture_init_iterator capture_init_end() {
2095 return capture_init_begin() + capture_size();
2096 }
2097
2098 /// Retrieve the iterator pointing one past the last
2099 /// initialization argument for this lambda expression.
2100 const_capture_init_iterator capture_init_end() const {
2101 return capture_init_begin() + capture_size();
2102 }
2103
2104 /// Retrieve the source range covering the lambda introducer,
2105 /// which contains the explicit capture list surrounded by square
2106 /// brackets ([...]).
2107 SourceRange getIntroducerRange() const { return IntroducerRange; }
2108
2109 /// Retrieve the class that corresponds to the lambda.
2110 ///
2111 /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
2112 /// captures in its fields and provides the various operations permitted
2113 /// on a lambda (copying, calling).
2114 CXXRecordDecl *getLambdaClass() const;
2115
2116 /// Retrieve the function call operator associated with this
2117 /// lambda expression.
2118 CXXMethodDecl *getCallOperator() const;
2119
2120 /// Retrieve the function template call operator associated with this
2121 /// lambda expression.
2122 FunctionTemplateDecl *getDependentCallOperator() const;
2123
2124 /// If this is a generic lambda expression, retrieve the template
2125 /// parameter list associated with it, or else return null.
2126 TemplateParameterList *getTemplateParameterList() const;
2127
2128 /// Get the template parameters were explicitly specified (as opposed to being
2129 /// invented by use of an auto parameter).
2130 ArrayRef<NamedDecl *> getExplicitTemplateParameters() const;
2131
2132 /// Get the trailing requires clause, if any.
2133 const AssociatedConstraint &getTrailingRequiresClause() const;
2134
2135 /// Whether this is a generic lambda.
2136 bool isGenericLambda() const { return getTemplateParameterList(); }
2137
2138 /// Retrieve the body of the lambda. This will be most of the time
2139 /// a \p CompoundStmt, but can also be \p CoroutineBodyStmt wrapping
2140 /// a \p CompoundStmt. Note that unlike functions, lambda-expressions
2141 /// cannot have a function-try-block.
2142 Stmt *getBody() const;
2143
2144 /// Retrieve the \p CompoundStmt representing the body of the lambda.
2145 /// This is a convenience function for callers who do not need
2146 /// to handle node(s) which may wrap a \p CompoundStmt.
2147 const CompoundStmt *getCompoundStmtBody() const;
2148 CompoundStmt *getCompoundStmtBody() {
2149 const auto *ConstThis = this;
2150 return const_cast<CompoundStmt *>(ConstThis->getCompoundStmtBody());
2151 }
2152
2153 /// Determine whether the lambda is mutable, meaning that any
2154 /// captures values can be modified.
2155 bool isMutable() const;
2156
2157 /// Determine whether this lambda has an explicit parameter
2158 /// list vs. an implicit (empty) parameter list.
2159 bool hasExplicitParameters() const { return LambdaExprBits.ExplicitParams; }
2160
2161 /// Whether this lambda had its result type explicitly specified.
2162 bool hasExplicitResultType() const {
2163 return LambdaExprBits.ExplicitResultType;
2164 }
2165
2166 static bool classof(const Stmt *T) {
2167 return T->getStmtClass() == LambdaExprClass;
2168 }
2169
2170 SourceLocation getBeginLoc() const LLVM_READONLY {
2171 return IntroducerRange.getBegin();
2172 }
2173
2174 SourceLocation getEndLoc() const LLVM_READONLY { return ClosingBrace; }
2175
2176 /// Includes the captures and the body of the lambda.
2177 child_range children();
2178 const_child_range children() const;
2179};
2180
2181/// An expression "T()" which creates an rvalue of a non-class type T.
2182/// For non-void T, the rvalue is value-initialized.
2183/// See (C++98 [5.2.3p2]).
2184class CXXScalarValueInitExpr : public Expr {
2185 friend class ASTStmtReader;
2186
2187 TypeSourceInfo *TypeInfo;
2188
2189public:
2190 /// Create an explicitly-written scalar-value initialization
2191 /// expression.
2192 CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
2193 SourceLocation RParenLoc)
2194 : Expr(CXXScalarValueInitExprClass, Type, VK_PRValue, OK_Ordinary),
2195 TypeInfo(TypeInfo) {
2196 CXXScalarValueInitExprBits.RParenLoc = RParenLoc;
2197 setDependence(computeDependence(E: this));
2198 }
2199
2200 explicit CXXScalarValueInitExpr(EmptyShell Shell)
2201 : Expr(CXXScalarValueInitExprClass, Shell) {}
2202
2203 TypeSourceInfo *getTypeSourceInfo() const {
2204 return TypeInfo;
2205 }
2206
2207 SourceLocation getRParenLoc() const {
2208 return CXXScalarValueInitExprBits.RParenLoc;
2209 }
2210
2211 SourceLocation getBeginLoc() const LLVM_READONLY;
2212 SourceLocation getEndLoc() const { return getRParenLoc(); }
2213
2214 static bool classof(const Stmt *T) {
2215 return T->getStmtClass() == CXXScalarValueInitExprClass;
2216 }
2217
2218 // Iterators
2219 child_range children() {
2220 return child_range(child_iterator(), child_iterator());
2221 }
2222
2223 const_child_range children() const {
2224 return const_child_range(const_child_iterator(), const_child_iterator());
2225 }
2226};
2227
2228enum class CXXNewInitializationStyle {
2229 /// New-expression has no initializer as written.
2230 None,
2231
2232 /// New-expression has a C++98 paren-delimited initializer.
2233 Parens,
2234
2235 /// New-expression has a C++11 list-initializer.
2236 Braces
2237};
2238
2239enum class TypeAwareAllocationMode : unsigned { No, Yes };
2240
2241inline bool isTypeAwareAllocation(TypeAwareAllocationMode Mode) {
2242 return Mode == TypeAwareAllocationMode::Yes;
2243}
2244
2245inline TypeAwareAllocationMode
2246typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation) {
2247 return IsTypeAwareAllocation ? TypeAwareAllocationMode::Yes
2248 : TypeAwareAllocationMode::No;
2249}
2250
2251enum class AlignedAllocationMode : unsigned { No, Yes };
2252
2253inline bool isAlignedAllocation(AlignedAllocationMode Mode) {
2254 return Mode == AlignedAllocationMode::Yes;
2255}
2256
2257inline AlignedAllocationMode alignedAllocationModeFromBool(bool IsAligned) {
2258 return IsAligned ? AlignedAllocationMode::Yes : AlignedAllocationMode::No;
2259}
2260
2261enum class SizedDeallocationMode : unsigned { No, Yes };
2262
2263inline bool isSizedDeallocation(SizedDeallocationMode Mode) {
2264 return Mode == SizedDeallocationMode::Yes;
2265}
2266
2267inline SizedDeallocationMode sizedDeallocationModeFromBool(bool IsSized) {
2268 return IsSized ? SizedDeallocationMode::Yes : SizedDeallocationMode::No;
2269}
2270
2271struct ImplicitAllocationParameters {
2272 ImplicitAllocationParameters(QualType AllocType,
2273 TypeAwareAllocationMode PassTypeIdentity,
2274 AlignedAllocationMode PassAlignment)
2275 : Type(AllocType), PassTypeIdentity(PassTypeIdentity),
2276 PassAlignment(PassAlignment) {
2277 if (!Type.isNull())
2278 Type = Type.getUnqualifiedType();
2279 }
2280 explicit ImplicitAllocationParameters(AlignedAllocationMode PassAlignment)
2281 : PassTypeIdentity(TypeAwareAllocationMode::No),
2282 PassAlignment(PassAlignment) {}
2283
2284 unsigned getNumImplicitArgs() const {
2285 unsigned Count = 1; // Size
2286 if (isTypeAwareAllocation(Mode: PassTypeIdentity))
2287 ++Count;
2288 if (isAlignedAllocation(Mode: PassAlignment))
2289 ++Count;
2290 return Count;
2291 }
2292
2293 QualType Type;
2294 TypeAwareAllocationMode PassTypeIdentity;
2295 AlignedAllocationMode PassAlignment;
2296};
2297
2298struct ImplicitDeallocationParameters {
2299 ImplicitDeallocationParameters(QualType DeallocType,
2300 TypeAwareAllocationMode PassTypeIdentity,
2301 AlignedAllocationMode PassAlignment,
2302 SizedDeallocationMode PassSize)
2303 : Type(DeallocType), PassTypeIdentity(PassTypeIdentity),
2304 PassAlignment(PassAlignment), PassSize(PassSize) {
2305 if (!Type.isNull())
2306 Type = Type.getUnqualifiedType();
2307 }
2308
2309 ImplicitDeallocationParameters(AlignedAllocationMode PassAlignment,
2310 SizedDeallocationMode PassSize)
2311 : PassTypeIdentity(TypeAwareAllocationMode::No),
2312 PassAlignment(PassAlignment), PassSize(PassSize) {}
2313
2314 unsigned getNumImplicitArgs() const {
2315 unsigned Count = 1; // Size
2316 if (isTypeAwareAllocation(Mode: PassTypeIdentity))
2317 ++Count;
2318 if (isAlignedAllocation(Mode: PassAlignment))
2319 ++Count;
2320 if (isSizedDeallocation(Mode: PassSize))
2321 ++Count;
2322 return Count;
2323 }
2324
2325 QualType Type;
2326 TypeAwareAllocationMode PassTypeIdentity;
2327 AlignedAllocationMode PassAlignment;
2328 SizedDeallocationMode PassSize;
2329};
2330
2331/// Represents a new-expression for memory allocation and constructor
2332/// calls, e.g: "new CXXNewExpr(foo)".
2333class CXXNewExpr final
2334 : public Expr,
2335 private llvm::TrailingObjects<CXXNewExpr, Stmt *, SourceRange> {
2336 friend class ASTStmtReader;
2337 friend class ASTStmtWriter;
2338 friend TrailingObjects;
2339
2340 /// Points to the allocation function used.
2341 FunctionDecl *OperatorNew;
2342
2343 /// Points to the deallocation function used in case of error. May be null.
2344 FunctionDecl *OperatorDelete;
2345
2346 /// The allocated type-source information, as written in the source.
2347 TypeSourceInfo *AllocatedTypeInfo;
2348
2349 /// Range of the entire new expression.
2350 SourceRange Range;
2351
2352 /// Source-range of a paren-delimited initializer.
2353 SourceRange DirectInitRange;
2354
2355 // CXXNewExpr is followed by several optional trailing objects.
2356 // They are in order:
2357 //
2358 // * An optional "Stmt *" for the array size expression.
2359 // Present if and ony if isArray().
2360 //
2361 // * An optional "Stmt *" for the init expression.
2362 // Present if and only if hasInitializer().
2363 //
2364 // * An array of getNumPlacementArgs() "Stmt *" for the placement new
2365 // arguments, if any.
2366 //
2367 // * An optional SourceRange for the range covering the parenthesized type-id
2368 // if the allocated type was expressed as a parenthesized type-id.
2369 // Present if and only if isParenTypeId().
2370 unsigned arraySizeOffset() const { return 0; }
2371 unsigned initExprOffset() const { return arraySizeOffset() + isArray(); }
2372 unsigned placementNewArgsOffset() const {
2373 return initExprOffset() + hasInitializer();
2374 }
2375
2376 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2377 return isArray() + hasInitializer() + getNumPlacementArgs();
2378 }
2379
2380 unsigned numTrailingObjects(OverloadToken<SourceRange>) const {
2381 return isParenTypeId();
2382 }
2383
2384 /// Build a c++ new expression.
2385 CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
2386 FunctionDecl *OperatorDelete,
2387 const ImplicitAllocationParameters &IAP,
2388 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2389 SourceRange TypeIdParens, std::optional<Expr *> ArraySize,
2390 CXXNewInitializationStyle InitializationStyle, Expr *Initializer,
2391 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2392 SourceRange DirectInitRange);
2393
2394 /// Build an empty c++ new expression.
2395 CXXNewExpr(EmptyShell Empty, bool IsArray, unsigned NumPlacementArgs,
2396 bool IsParenTypeId);
2397
2398public:
2399 /// Create a c++ new expression.
2400 static CXXNewExpr *
2401 Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,
2402 FunctionDecl *OperatorDelete, const ImplicitAllocationParameters &IAP,
2403 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2404 SourceRange TypeIdParens, std::optional<Expr *> ArraySize,
2405 CXXNewInitializationStyle InitializationStyle, Expr *Initializer,
2406 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2407 SourceRange DirectInitRange);
2408
2409 /// Create an empty c++ new expression.
2410 static CXXNewExpr *CreateEmpty(const ASTContext &Ctx, bool IsArray,
2411 bool HasInit, unsigned NumPlacementArgs,
2412 bool IsParenTypeId);
2413
2414 QualType getAllocatedType() const {
2415 return getType()->castAs<PointerType>()->getPointeeType();
2416 }
2417
2418 TypeSourceInfo *getAllocatedTypeSourceInfo() const {
2419 return AllocatedTypeInfo;
2420 }
2421
2422 /// True if the allocation result needs to be null-checked.
2423 ///
2424 /// C++11 [expr.new]p13:
2425 /// If the allocation function returns null, initialization shall
2426 /// not be done, the deallocation function shall not be called,
2427 /// and the value of the new-expression shall be null.
2428 ///
2429 /// C++ DR1748:
2430 /// If the allocation function is a reserved placement allocation
2431 /// function that returns null, the behavior is undefined.
2432 ///
2433 /// An allocation function is not allowed to return null unless it
2434 /// has a non-throwing exception-specification. The '03 rule is
2435 /// identical except that the definition of a non-throwing
2436 /// exception specification is just "is it throw()?".
2437 bool shouldNullCheckAllocation() const;
2438
2439 FunctionDecl *getOperatorNew() const { return OperatorNew; }
2440 void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
2441 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2442 void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
2443
2444 bool isArray() const { return CXXNewExprBits.IsArray; }
2445
2446 /// This might return std::nullopt even if isArray() returns true,
2447 /// since there might not be an array size expression.
2448 /// If the result is not std::nullopt, it will never wrap a nullptr.
2449 std::optional<Expr *> getArraySize() {
2450 if (!isArray())
2451 return std::nullopt;
2452
2453 if (auto *Result =
2454 cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]))
2455 return Result;
2456
2457 return std::nullopt;
2458 }
2459
2460 /// This might return std::nullopt even if isArray() returns true,
2461 /// since there might not be an array size expression.
2462 /// If the result is not std::nullopt, it will never wrap a nullptr.
2463 std::optional<const Expr *> getArraySize() const {
2464 if (!isArray())
2465 return std::nullopt;
2466
2467 if (auto *Result =
2468 cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]))
2469 return Result;
2470
2471 return std::nullopt;
2472 }
2473
2474 unsigned getNumPlacementArgs() const {
2475 return CXXNewExprBits.NumPlacementArgs;
2476 }
2477
2478 Expr **getPlacementArgs() {
2479 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>() +
2480 placementNewArgsOffset());
2481 }
2482
2483 Expr *getPlacementArg(unsigned I) {
2484 assert((I < getNumPlacementArgs()) && "Index out of range!");
2485 return getPlacementArgs()[I];
2486 }
2487 const Expr *getPlacementArg(unsigned I) const {
2488 return const_cast<CXXNewExpr *>(this)->getPlacementArg(I);
2489 }
2490
2491 unsigned getNumImplicitArgs() const {
2492 return implicitAllocationParameters().getNumImplicitArgs();
2493 }
2494
2495 bool isParenTypeId() const { return CXXNewExprBits.IsParenTypeId; }
2496 SourceRange getTypeIdParens() const {
2497 return isParenTypeId() ? getTrailingObjects<SourceRange>()[0]
2498 : SourceRange();
2499 }
2500
2501 bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
2502
2503 /// Whether this new-expression has any initializer at all.
2504 bool hasInitializer() const { return CXXNewExprBits.HasInitializer; }
2505
2506 /// The kind of initializer this new-expression has.
2507 CXXNewInitializationStyle getInitializationStyle() const {
2508 return static_cast<CXXNewInitializationStyle>(
2509 CXXNewExprBits.StoredInitializationStyle);
2510 }
2511
2512 /// The initializer of this new-expression.
2513 Expr *getInitializer() {
2514 return hasInitializer()
2515 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2516 : nullptr;
2517 }
2518 const Expr *getInitializer() const {
2519 return hasInitializer()
2520 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2521 : nullptr;
2522 }
2523
2524 /// Returns the CXXConstructExpr from this new-expression, or null.
2525 const CXXConstructExpr *getConstructExpr() const {
2526 return dyn_cast_or_null<CXXConstructExpr>(Val: getInitializer());
2527 }
2528
2529 /// Indicates whether the required alignment should be implicitly passed to
2530 /// the allocation function.
2531 bool passAlignment() const { return CXXNewExprBits.ShouldPassAlignment; }
2532
2533 /// Answers whether the usual array deallocation function for the
2534 /// allocated type expects the size of the allocation as a
2535 /// parameter.
2536 bool doesUsualArrayDeleteWantSize() const {
2537 return CXXNewExprBits.UsualArrayDeleteWantsSize;
2538 }
2539
2540 /// Provides the full set of information about expected implicit
2541 /// parameters in this call
2542 ImplicitAllocationParameters implicitAllocationParameters() const {
2543 return ImplicitAllocationParameters{
2544 getAllocatedType(),
2545 typeAwareAllocationModeFromBool(IsTypeAwareAllocation: CXXNewExprBits.ShouldPassTypeIdentity),
2546 alignedAllocationModeFromBool(IsAligned: CXXNewExprBits.ShouldPassAlignment)};
2547 }
2548
2549 using arg_iterator = ExprIterator;
2550 using const_arg_iterator = ConstExprIterator;
2551
2552 llvm::iterator_range<arg_iterator> placement_arguments() {
2553 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2554 }
2555
2556 llvm::iterator_range<const_arg_iterator> placement_arguments() const {
2557 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2558 }
2559
2560 arg_iterator placement_arg_begin() {
2561 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2562 }
2563 arg_iterator placement_arg_end() {
2564 return placement_arg_begin() + getNumPlacementArgs();
2565 }
2566 const_arg_iterator placement_arg_begin() const {
2567 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2568 }
2569 const_arg_iterator placement_arg_end() const {
2570 return placement_arg_begin() + getNumPlacementArgs();
2571 }
2572
2573 using raw_arg_iterator = Stmt **;
2574
2575 raw_arg_iterator raw_arg_begin() { return getTrailingObjects<Stmt *>(); }
2576 raw_arg_iterator raw_arg_end() {
2577 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2578 }
2579 const_arg_iterator raw_arg_begin() const {
2580 return getTrailingObjects<Stmt *>();
2581 }
2582 const_arg_iterator raw_arg_end() const {
2583 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2584 }
2585
2586 SourceLocation getBeginLoc() const { return Range.getBegin(); }
2587 SourceLocation getEndLoc() const { return Range.getEnd(); }
2588
2589 SourceRange getDirectInitRange() const { return DirectInitRange; }
2590 SourceRange getSourceRange() const { return Range; }
2591
2592 static bool classof(const Stmt *T) {
2593 return T->getStmtClass() == CXXNewExprClass;
2594 }
2595
2596 // Iterators
2597 child_range children() { return child_range(raw_arg_begin(), raw_arg_end()); }
2598
2599 const_child_range children() const {
2600 return const_child_range(const_cast<CXXNewExpr *>(this)->children());
2601 }
2602};
2603
2604/// Represents a \c delete expression for memory deallocation and
2605/// destructor calls, e.g. "delete[] pArray".
2606class CXXDeleteExpr : public Expr {
2607 friend class ASTStmtReader;
2608
2609 /// Points to the operator delete overload that is used. Could be a member.
2610 FunctionDecl *OperatorDelete = nullptr;
2611
2612 /// The pointer expression to be deleted.
2613 Stmt *Argument = nullptr;
2614
2615public:
2616 CXXDeleteExpr(QualType Ty, bool GlobalDelete, bool ArrayForm,
2617 bool ArrayFormAsWritten, bool UsualArrayDeleteWantsSize,
2618 FunctionDecl *OperatorDelete, Expr *Arg, SourceLocation Loc)
2619 : Expr(CXXDeleteExprClass, Ty, VK_PRValue, OK_Ordinary),
2620 OperatorDelete(OperatorDelete), Argument(Arg) {
2621 CXXDeleteExprBits.GlobalDelete = GlobalDelete;
2622 CXXDeleteExprBits.ArrayForm = ArrayForm;
2623 CXXDeleteExprBits.ArrayFormAsWritten = ArrayFormAsWritten;
2624 CXXDeleteExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;
2625 CXXDeleteExprBits.Loc = Loc;
2626 setDependence(computeDependence(E: this));
2627 }
2628
2629 explicit CXXDeleteExpr(EmptyShell Shell) : Expr(CXXDeleteExprClass, Shell) {}
2630
2631 bool isGlobalDelete() const { return CXXDeleteExprBits.GlobalDelete; }
2632 bool isArrayForm() const { return CXXDeleteExprBits.ArrayForm; }
2633 bool isArrayFormAsWritten() const {
2634 return CXXDeleteExprBits.ArrayFormAsWritten;
2635 }
2636
2637 /// Answers whether the usual array deallocation function for the
2638 /// allocated type expects the size of the allocation as a
2639 /// parameter. This can be true even if the actual deallocation
2640 /// function that we're using doesn't want a size.
2641 bool doesUsualArrayDeleteWantSize() const {
2642 return CXXDeleteExprBits.UsualArrayDeleteWantsSize;
2643 }
2644
2645 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2646
2647 Expr *getArgument() { return cast<Expr>(Val: Argument); }
2648 const Expr *getArgument() const { return cast<Expr>(Val: Argument); }
2649
2650 /// Retrieve the type being destroyed.
2651 ///
2652 /// If the type being destroyed is a dependent type which may or may not
2653 /// be a pointer, return an invalid type.
2654 QualType getDestroyedType() const;
2655
2656 SourceLocation getBeginLoc() const { return CXXDeleteExprBits.Loc; }
2657 SourceLocation getEndLoc() const LLVM_READONLY {
2658 return Argument->getEndLoc();
2659 }
2660
2661 static bool classof(const Stmt *T) {
2662 return T->getStmtClass() == CXXDeleteExprClass;
2663 }
2664
2665 // Iterators
2666 child_range children() { return child_range(&Argument, &Argument + 1); }
2667
2668 const_child_range children() const {
2669 return const_child_range(&Argument, &Argument + 1);
2670 }
2671};
2672
2673/// Stores the type being destroyed by a pseudo-destructor expression.
2674class PseudoDestructorTypeStorage {
2675 /// Either the type source information or the name of the type, if
2676 /// it couldn't be resolved due to type-dependence.
2677 llvm::PointerUnion<TypeSourceInfo *, const IdentifierInfo *> Type;
2678
2679 /// The starting source location of the pseudo-destructor type.
2680 SourceLocation Location;
2681
2682public:
2683 PseudoDestructorTypeStorage() = default;
2684
2685 PseudoDestructorTypeStorage(const IdentifierInfo *II, SourceLocation Loc)
2686 : Type(II), Location(Loc) {}
2687
2688 PseudoDestructorTypeStorage(TypeSourceInfo *Info);
2689
2690 TypeSourceInfo *getTypeSourceInfo() const {
2691 return Type.dyn_cast<TypeSourceInfo *>();
2692 }
2693
2694 const IdentifierInfo *getIdentifier() const {
2695 return Type.dyn_cast<const IdentifierInfo *>();
2696 }
2697
2698 SourceLocation getLocation() const { return Location; }
2699};
2700
2701/// Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
2702///
2703/// A pseudo-destructor is an expression that looks like a member access to a
2704/// destructor of a scalar type, except that scalar types don't have
2705/// destructors. For example:
2706///
2707/// \code
2708/// typedef int T;
2709/// void f(int *p) {
2710/// p->T::~T();
2711/// }
2712/// \endcode
2713///
2714/// Pseudo-destructors typically occur when instantiating templates such as:
2715///
2716/// \code
2717/// template<typename T>
2718/// void destroy(T* ptr) {
2719/// ptr->T::~T();
2720/// }
2721/// \endcode
2722///
2723/// for scalar types. A pseudo-destructor expression has no run-time semantics
2724/// beyond evaluating the base expression.
2725class CXXPseudoDestructorExpr : public Expr {
2726 friend class ASTStmtReader;
2727
2728 /// The base expression (that is being destroyed).
2729 Stmt *Base = nullptr;
2730
2731 /// Whether the operator was an arrow ('->'); otherwise, it was a
2732 /// period ('.').
2733 LLVM_PREFERRED_TYPE(bool)
2734 bool IsArrow : 1;
2735
2736 /// The location of the '.' or '->' operator.
2737 SourceLocation OperatorLoc;
2738
2739 /// The nested-name-specifier that follows the operator, if present.
2740 NestedNameSpecifierLoc QualifierLoc;
2741
2742 /// The type that precedes the '::' in a qualified pseudo-destructor
2743 /// expression.
2744 TypeSourceInfo *ScopeType = nullptr;
2745
2746 /// The location of the '::' in a qualified pseudo-destructor
2747 /// expression.
2748 SourceLocation ColonColonLoc;
2749
2750 /// The location of the '~'.
2751 SourceLocation TildeLoc;
2752
2753 /// The type being destroyed, or its name if we were unable to
2754 /// resolve the name.
2755 PseudoDestructorTypeStorage DestroyedType;
2756
2757public:
2758 CXXPseudoDestructorExpr(const ASTContext &Context,
2759 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2760 NestedNameSpecifierLoc QualifierLoc,
2761 TypeSourceInfo *ScopeType,
2762 SourceLocation ColonColonLoc,
2763 SourceLocation TildeLoc,
2764 PseudoDestructorTypeStorage DestroyedType);
2765
2766 explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2767 : Expr(CXXPseudoDestructorExprClass, Shell), IsArrow(false) {}
2768
2769 Expr *getBase() const { return cast<Expr>(Val: Base); }
2770
2771 /// Determines whether this member expression actually had
2772 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2773 /// x->Base::foo.
2774 bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2775
2776 /// Retrieves the nested-name-specifier that qualifies the type name,
2777 /// with source-location information.
2778 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2779
2780 /// If the member name was qualified, retrieves the
2781 /// nested-name-specifier that precedes the member name. Otherwise, returns
2782 /// null.
2783 NestedNameSpecifier *getQualifier() const {
2784 return QualifierLoc.getNestedNameSpecifier();
2785 }
2786
2787 /// Determine whether this pseudo-destructor expression was written
2788 /// using an '->' (otherwise, it used a '.').
2789 bool isArrow() const { return IsArrow; }
2790
2791 /// Retrieve the location of the '.' or '->' operator.
2792 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2793
2794 /// Retrieve the scope type in a qualified pseudo-destructor
2795 /// expression.
2796 ///
2797 /// Pseudo-destructor expressions can have extra qualification within them
2798 /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2799 /// Here, if the object type of the expression is (or may be) a scalar type,
2800 /// \p T may also be a scalar type and, therefore, cannot be part of a
2801 /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2802 /// destructor expression.
2803 TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2804
2805 /// Retrieve the location of the '::' in a qualified pseudo-destructor
2806 /// expression.
2807 SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2808
2809 /// Retrieve the location of the '~'.
2810 SourceLocation getTildeLoc() const { return TildeLoc; }
2811
2812 /// Retrieve the source location information for the type
2813 /// being destroyed.
2814 ///
2815 /// This type-source information is available for non-dependent
2816 /// pseudo-destructor expressions and some dependent pseudo-destructor
2817 /// expressions. Returns null if we only have the identifier for a
2818 /// dependent pseudo-destructor expression.
2819 TypeSourceInfo *getDestroyedTypeInfo() const {
2820 return DestroyedType.getTypeSourceInfo();
2821 }
2822
2823 /// In a dependent pseudo-destructor expression for which we do not
2824 /// have full type information on the destroyed type, provides the name
2825 /// of the destroyed type.
2826 const IdentifierInfo *getDestroyedTypeIdentifier() const {
2827 return DestroyedType.getIdentifier();
2828 }
2829
2830 /// Retrieve the type being destroyed.
2831 QualType getDestroyedType() const;
2832
2833 /// Retrieve the starting location of the type being destroyed.
2834 SourceLocation getDestroyedTypeLoc() const {
2835 return DestroyedType.getLocation();
2836 }
2837
2838 /// Set the name of destroyed type for a dependent pseudo-destructor
2839 /// expression.
2840 void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2841 DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2842 }
2843
2844 /// Set the destroyed type.
2845 void setDestroyedType(TypeSourceInfo *Info) {
2846 DestroyedType = PseudoDestructorTypeStorage(Info);
2847 }
2848
2849 SourceLocation getBeginLoc() const LLVM_READONLY {
2850 return Base->getBeginLoc();
2851 }
2852 SourceLocation getEndLoc() const LLVM_READONLY;
2853
2854 static bool classof(const Stmt *T) {
2855 return T->getStmtClass() == CXXPseudoDestructorExprClass;
2856 }
2857
2858 // Iterators
2859 child_range children() { return child_range(&Base, &Base + 1); }
2860
2861 const_child_range children() const {
2862 return const_child_range(&Base, &Base + 1);
2863 }
2864};
2865
2866/// A type trait used in the implementation of various C++11 and
2867/// Library TR1 trait templates.
2868///
2869/// \code
2870/// __is_pod(int) == true
2871/// __is_enum(std::string) == false
2872/// __is_trivially_constructible(vector<int>, int*, int*)
2873/// \endcode
2874class TypeTraitExpr final
2875 : public Expr,
2876 private llvm::TrailingObjects<TypeTraitExpr, APValue, TypeSourceInfo *> {
2877 /// The location of the type trait keyword.
2878 SourceLocation Loc;
2879
2880 /// The location of the closing parenthesis.
2881 SourceLocation RParenLoc;
2882
2883 TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2884 ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc,
2885 std::variant<bool, APValue> Value);
2886
2887 TypeTraitExpr(EmptyShell Empty, bool IsStoredAsBool);
2888
2889 size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
2890 return getNumArgs();
2891 }
2892
2893 size_t numTrailingObjects(OverloadToken<APValue>) const {
2894 return TypeTraitExprBits.IsBooleanTypeTrait ? 0 : 1;
2895 }
2896
2897public:
2898 friend class ASTStmtReader;
2899 friend class ASTStmtWriter;
2900 friend TrailingObjects;
2901
2902 /// Create a new type trait expression.
2903 static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2904 SourceLocation Loc, TypeTrait Kind,
2905 ArrayRef<TypeSourceInfo *> Args,
2906 SourceLocation RParenLoc,
2907 bool Value);
2908
2909 static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2910 SourceLocation Loc, TypeTrait Kind,
2911 ArrayRef<TypeSourceInfo *> Args,
2912 SourceLocation RParenLoc, APValue Value);
2913
2914 static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
2915 bool IsStoredAsBool,
2916 unsigned NumArgs);
2917
2918 /// Determine which type trait this expression uses.
2919 TypeTrait getTrait() const {
2920 return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2921 }
2922
2923 bool isStoredAsBoolean() const {
2924 return TypeTraitExprBits.IsBooleanTypeTrait;
2925 }
2926
2927 bool getBoolValue() const {
2928 assert(!isValueDependent() && TypeTraitExprBits.IsBooleanTypeTrait);
2929 return TypeTraitExprBits.Value;
2930 }
2931
2932 const APValue &getAPValue() const {
2933 assert(!isValueDependent() && !TypeTraitExprBits.IsBooleanTypeTrait);
2934 return *getTrailingObjects<APValue>();
2935 }
2936
2937 /// Determine the number of arguments to this type trait.
2938 unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2939
2940 /// Retrieve the Ith argument.
2941 TypeSourceInfo *getArg(unsigned I) const {
2942 assert(I < getNumArgs() && "Argument out-of-range");
2943 return getArgs()[I];
2944 }
2945
2946 /// Retrieve the argument types.
2947 ArrayRef<TypeSourceInfo *> getArgs() const {
2948 return getTrailingObjects<TypeSourceInfo *>(getNumArgs());
2949 }
2950
2951 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2952 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2953
2954 static bool classof(const Stmt *T) {
2955 return T->getStmtClass() == TypeTraitExprClass;
2956 }
2957
2958 // Iterators
2959 child_range children() {
2960 return child_range(child_iterator(), child_iterator());
2961 }
2962
2963 const_child_range children() const {
2964 return const_child_range(const_child_iterator(), const_child_iterator());
2965 }
2966};
2967
2968/// An Embarcadero array type trait, as used in the implementation of
2969/// __array_rank and __array_extent.
2970///
2971/// Example:
2972/// \code
2973/// __array_rank(int[10][20]) == 2
2974/// __array_extent(int[10][20], 1) == 20
2975/// \endcode
2976class ArrayTypeTraitExpr : public Expr {
2977 /// The value of the type trait. Unspecified if dependent.
2978 uint64_t Value = 0;
2979
2980 /// The array dimension being queried, or -1 if not used.
2981 Expr *Dimension;
2982
2983 /// The location of the type trait keyword.
2984 SourceLocation Loc;
2985
2986 /// The location of the closing paren.
2987 SourceLocation RParen;
2988
2989 /// The type being queried.
2990 TypeSourceInfo *QueriedType = nullptr;
2991
2992public:
2993 friend class ASTStmtReader;
2994
2995 ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2996 TypeSourceInfo *queried, uint64_t value, Expr *dimension,
2997 SourceLocation rparen, QualType ty)
2998 : Expr(ArrayTypeTraitExprClass, ty, VK_PRValue, OK_Ordinary),
2999 Value(value), Dimension(dimension), Loc(loc), RParen(rparen),
3000 QueriedType(queried) {
3001 assert(att <= ATT_Last && "invalid enum value!");
3002 ArrayTypeTraitExprBits.ATT = att;
3003 assert(static_cast<unsigned>(att) == ArrayTypeTraitExprBits.ATT &&
3004 "ATT overflow!");
3005 setDependence(computeDependence(E: this));
3006 }
3007
3008 explicit ArrayTypeTraitExpr(EmptyShell Empty)
3009 : Expr(ArrayTypeTraitExprClass, Empty) {
3010 ArrayTypeTraitExprBits.ATT = 0;
3011 }
3012
3013 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
3014 SourceLocation getEndLoc() const LLVM_READONLY { return RParen; }
3015
3016 ArrayTypeTrait getTrait() const {
3017 return static_cast<ArrayTypeTrait>(ArrayTypeTraitExprBits.ATT);
3018 }
3019
3020 QualType getQueriedType() const { return QueriedType->getType(); }
3021
3022 TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
3023
3024 uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
3025
3026 Expr *getDimensionExpression() const { return Dimension; }
3027
3028 static bool classof(const Stmt *T) {
3029 return T->getStmtClass() == ArrayTypeTraitExprClass;
3030 }
3031
3032 // Iterators
3033 child_range children() {
3034 return child_range(child_iterator(), child_iterator());
3035 }
3036
3037 const_child_range children() const {
3038 return const_child_range(const_child_iterator(), const_child_iterator());
3039 }
3040};
3041
3042/// An expression trait intrinsic.
3043///
3044/// Example:
3045/// \code
3046/// __is_lvalue_expr(std::cout) == true
3047/// __is_lvalue_expr(1) == false
3048/// \endcode
3049class ExpressionTraitExpr : public Expr {
3050 /// The location of the type trait keyword.
3051 SourceLocation Loc;
3052
3053 /// The location of the closing paren.
3054 SourceLocation RParen;
3055
3056 /// The expression being queried.
3057 Expr* QueriedExpression = nullptr;
3058
3059public:
3060 friend class ASTStmtReader;
3061
3062 ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et, Expr *queried,
3063 bool value, SourceLocation rparen, QualType resultType)
3064 : Expr(ExpressionTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
3065 Loc(loc), RParen(rparen), QueriedExpression(queried) {
3066 ExpressionTraitExprBits.ET = et;
3067 ExpressionTraitExprBits.Value = value;
3068
3069 assert(et <= ET_Last && "invalid enum value!");
3070 assert(static_cast<unsigned>(et) == ExpressionTraitExprBits.ET &&
3071 "ET overflow!");
3072 setDependence(computeDependence(E: this));
3073 }
3074
3075 explicit ExpressionTraitExpr(EmptyShell Empty)
3076 : Expr(ExpressionTraitExprClass, Empty) {
3077 ExpressionTraitExprBits.ET = 0;
3078 ExpressionTraitExprBits.Value = false;
3079 }
3080
3081 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
3082 SourceLocation getEndLoc() const LLVM_READONLY { return RParen; }
3083
3084 ExpressionTrait getTrait() const {
3085 return static_cast<ExpressionTrait>(ExpressionTraitExprBits.ET);
3086 }
3087
3088 Expr *getQueriedExpression() const { return QueriedExpression; }
3089
3090 bool getValue() const { return ExpressionTraitExprBits.Value; }
3091
3092 static bool classof(const Stmt *T) {
3093 return T->getStmtClass() == ExpressionTraitExprClass;
3094 }
3095
3096 // Iterators
3097 child_range children() {
3098 return child_range(child_iterator(), child_iterator());
3099 }
3100
3101 const_child_range children() const {
3102 return const_child_range(const_child_iterator(), const_child_iterator());
3103 }
3104};
3105
3106/// A reference to an overloaded function set, either an
3107/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
3108class OverloadExpr : public Expr {
3109 friend class ASTStmtReader;
3110 friend class ASTStmtWriter;
3111
3112 /// The common name of these declarations.
3113 DeclarationNameInfo NameInfo;
3114
3115 /// The nested-name-specifier that qualifies the name, if any.
3116 NestedNameSpecifierLoc QualifierLoc;
3117
3118protected:
3119 OverloadExpr(StmtClass SC, const ASTContext &Context,
3120 NestedNameSpecifierLoc QualifierLoc,
3121 SourceLocation TemplateKWLoc,
3122 const DeclarationNameInfo &NameInfo,
3123 const TemplateArgumentListInfo *TemplateArgs,
3124 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
3125 bool KnownDependent, bool KnownInstantiationDependent,
3126 bool KnownContainsUnexpandedParameterPack);
3127
3128 OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,
3129 bool HasTemplateKWAndArgsInfo);
3130
3131 /// Return the results. Defined after UnresolvedMemberExpr.
3132 inline DeclAccessPair *getTrailingResults();
3133 const DeclAccessPair *getTrailingResults() const {
3134 return const_cast<OverloadExpr *>(this)->getTrailingResults();
3135 }
3136
3137 /// Return the optional template keyword and arguments info.
3138 /// Defined after UnresolvedMemberExpr.
3139 inline ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo();
3140 const ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo() const {
3141 return const_cast<OverloadExpr *>(this)
3142 ->getTrailingASTTemplateKWAndArgsInfo();
3143 }
3144
3145 /// Return the optional template arguments. Defined after
3146 /// UnresolvedMemberExpr.
3147 inline TemplateArgumentLoc *getTrailingTemplateArgumentLoc();
3148 const TemplateArgumentLoc *getTrailingTemplateArgumentLoc() const {
3149 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
3150 }
3151
3152 bool hasTemplateKWAndArgsInfo() const {
3153 return OverloadExprBits.HasTemplateKWAndArgsInfo;
3154 }
3155
3156public:
3157 struct FindResult {
3158 OverloadExpr *Expression = nullptr;
3159 bool IsAddressOfOperand = false;
3160 bool IsAddressOfOperandWithParen = false;
3161 bool HasFormOfMemberPointer = false;
3162 };
3163
3164 /// Finds the overloaded expression in the given expression \p E of
3165 /// OverloadTy.
3166 ///
3167 /// \return the expression (which must be there) and true if it has
3168 /// the particular form of a member pointer expression
3169 static FindResult find(Expr *E) {
3170 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
3171
3172 FindResult Result;
3173 bool HasParen = isa<ParenExpr>(Val: E);
3174
3175 E = E->IgnoreParens();
3176 if (isa<UnaryOperator>(Val: E)) {
3177 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
3178 E = cast<UnaryOperator>(Val: E)->getSubExpr();
3179 auto *Ovl = cast<OverloadExpr>(Val: E->IgnoreParens());
3180
3181 Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
3182 Result.IsAddressOfOperand = true;
3183 Result.IsAddressOfOperandWithParen = HasParen;
3184 Result.Expression = Ovl;
3185 } else {
3186 Result.Expression = cast<OverloadExpr>(Val: E);
3187 }
3188
3189 return Result;
3190 }
3191
3192 /// Gets the naming class of this lookup, if any.
3193 /// Defined after UnresolvedMemberExpr.
3194 inline CXXRecordDecl *getNamingClass();
3195 const CXXRecordDecl *getNamingClass() const {
3196 return const_cast<OverloadExpr *>(this)->getNamingClass();
3197 }
3198
3199 using decls_iterator = UnresolvedSetImpl::iterator;
3200
3201 decls_iterator decls_begin() const {
3202 return UnresolvedSetIterator(getTrailingResults());
3203 }
3204 decls_iterator decls_end() const {
3205 return UnresolvedSetIterator(getTrailingResults() + getNumDecls());
3206 }
3207 llvm::iterator_range<decls_iterator> decls() const {
3208 return llvm::make_range(x: decls_begin(), y: decls_end());
3209 }
3210
3211 /// Gets the number of declarations in the unresolved set.
3212 unsigned getNumDecls() const { return OverloadExprBits.NumResults; }
3213
3214 /// Gets the full name info.
3215 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
3216
3217 /// Gets the name looked up.
3218 DeclarationName getName() const { return NameInfo.getName(); }
3219
3220 /// Gets the location of the name.
3221 SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
3222
3223 /// Fetches the nested-name qualifier, if one was given.
3224 NestedNameSpecifier *getQualifier() const {
3225 return QualifierLoc.getNestedNameSpecifier();
3226 }
3227
3228 /// Fetches the nested-name qualifier with source-location
3229 /// information, if one was given.
3230 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3231
3232 /// Retrieve the location of the template keyword preceding
3233 /// this name, if any.
3234 SourceLocation getTemplateKeywordLoc() const {
3235 if (!hasTemplateKWAndArgsInfo())
3236 return SourceLocation();
3237 return getTrailingASTTemplateKWAndArgsInfo()->TemplateKWLoc;
3238 }
3239
3240 /// Retrieve the location of the left angle bracket starting the
3241 /// explicit template argument list following the name, if any.
3242 SourceLocation getLAngleLoc() const {
3243 if (!hasTemplateKWAndArgsInfo())
3244 return SourceLocation();
3245 return getTrailingASTTemplateKWAndArgsInfo()->LAngleLoc;
3246 }
3247
3248 /// Retrieve the location of the right angle bracket ending the
3249 /// explicit template argument list following the name, if any.
3250 SourceLocation getRAngleLoc() const {
3251 if (!hasTemplateKWAndArgsInfo())
3252 return SourceLocation();
3253 return getTrailingASTTemplateKWAndArgsInfo()->RAngleLoc;
3254 }
3255
3256 /// Determines whether the name was preceded by the template keyword.
3257 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3258
3259 /// Determines whether this expression had explicit template arguments.
3260 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3261
3262 TemplateArgumentLoc const *getTemplateArgs() const {
3263 if (!hasExplicitTemplateArgs())
3264 return nullptr;
3265 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
3266 }
3267
3268 unsigned getNumTemplateArgs() const {
3269 if (!hasExplicitTemplateArgs())
3270 return 0;
3271
3272 return getTrailingASTTemplateKWAndArgsInfo()->NumTemplateArgs;
3273 }
3274
3275 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3276 return {getTemplateArgs(), getNumTemplateArgs()};
3277 }
3278
3279 /// Copies the template arguments into the given structure.
3280 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3281 if (hasExplicitTemplateArgs())
3282 getTrailingASTTemplateKWAndArgsInfo()->copyInto(ArgArray: getTemplateArgs(), List);
3283 }
3284
3285 static bool classof(const Stmt *T) {
3286 return T->getStmtClass() == UnresolvedLookupExprClass ||
3287 T->getStmtClass() == UnresolvedMemberExprClass;
3288 }
3289};
3290
3291/// A reference to a name which we were able to look up during
3292/// parsing but could not resolve to a specific declaration.
3293///
3294/// This arises in several ways:
3295/// * we might be waiting for argument-dependent lookup;
3296/// * the name might resolve to an overloaded function;
3297/// * the name might resolve to a non-function template; for example, in the
3298/// following snippet, the return expression of the member function
3299/// 'foo()' might remain unresolved until instantiation:
3300///
3301/// \code
3302/// struct P {
3303/// template <class T> using I = T;
3304/// };
3305///
3306/// struct Q {
3307/// template <class T> int foo() {
3308/// return T::template I<int>;
3309/// }
3310/// };
3311/// \endcode
3312///
3313/// ...which is distinct from modeling function overloads, and therefore we use
3314/// a different builtin type 'UnresolvedTemplate' to avoid confusion. This is
3315/// done in Sema::BuildTemplateIdExpr.
3316///
3317/// and eventually:
3318/// * the lookup might have included a function template.
3319/// * the unresolved template gets transformed in an instantiation or gets
3320/// diagnosed for its direct use.
3321///
3322/// These never include UnresolvedUsingValueDecls, which are always class
3323/// members and therefore appear only in UnresolvedMemberLookupExprs.
3324class UnresolvedLookupExpr final
3325 : public OverloadExpr,
3326 private llvm::TrailingObjects<UnresolvedLookupExpr, DeclAccessPair,
3327 ASTTemplateKWAndArgsInfo,
3328 TemplateArgumentLoc> {
3329 friend class ASTStmtReader;
3330 friend class OverloadExpr;
3331 friend TrailingObjects;
3332
3333 /// The naming class (C++ [class.access.base]p5) of the lookup, if
3334 /// any. This can generally be recalculated from the context chain,
3335 /// but that can be fairly expensive for unqualified lookups.
3336 CXXRecordDecl *NamingClass;
3337
3338 // UnresolvedLookupExpr is followed by several trailing objects.
3339 // They are in order:
3340 //
3341 // * An array of getNumResults() DeclAccessPair for the results. These are
3342 // undesugared, which is to say, they may include UsingShadowDecls.
3343 // Access is relative to the naming class.
3344 //
3345 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3346 // template keyword and arguments. Present if and only if
3347 // hasTemplateKWAndArgsInfo().
3348 //
3349 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
3350 // location information for the explicitly specified template arguments.
3351
3352 UnresolvedLookupExpr(const ASTContext &Context, CXXRecordDecl *NamingClass,
3353 NestedNameSpecifierLoc QualifierLoc,
3354 SourceLocation TemplateKWLoc,
3355 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3356 const TemplateArgumentListInfo *TemplateArgs,
3357 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
3358 bool KnownDependent, bool KnownInstantiationDependent);
3359
3360 UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
3361 bool HasTemplateKWAndArgsInfo);
3362
3363 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3364 return getNumDecls();
3365 }
3366
3367 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3368 return hasTemplateKWAndArgsInfo();
3369 }
3370
3371public:
3372 static UnresolvedLookupExpr *
3373 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3374 NestedNameSpecifierLoc QualifierLoc,
3375 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3376 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
3377 bool KnownDependent, bool KnownInstantiationDependent);
3378
3379 // After canonicalization, there may be dependent template arguments in
3380 // CanonicalConverted But none of Args is dependent. When any of
3381 // CanonicalConverted dependent, KnownDependent is true.
3382 static UnresolvedLookupExpr *
3383 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3384 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3385 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3386 const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
3387 UnresolvedSetIterator End, bool KnownDependent,
3388 bool KnownInstantiationDependent);
3389
3390 static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
3391 unsigned NumResults,
3392 bool HasTemplateKWAndArgsInfo,
3393 unsigned NumTemplateArgs);
3394
3395 /// True if this declaration should be extended by
3396 /// argument-dependent lookup.
3397 bool requiresADL() const { return UnresolvedLookupExprBits.RequiresADL; }
3398
3399 /// Gets the 'naming class' (in the sense of C++0x
3400 /// [class.access.base]p5) of the lookup. This is the scope
3401 /// that was looked in to find these results.
3402 CXXRecordDecl *getNamingClass() { return NamingClass; }
3403 const CXXRecordDecl *getNamingClass() const { return NamingClass; }
3404
3405 SourceLocation getBeginLoc() const LLVM_READONLY {
3406 if (NestedNameSpecifierLoc l = getQualifierLoc())
3407 return l.getBeginLoc();
3408 return getNameInfo().getBeginLoc();
3409 }
3410
3411 SourceLocation getEndLoc() const LLVM_READONLY {
3412 if (hasExplicitTemplateArgs())
3413 return getRAngleLoc();
3414 return getNameInfo().getEndLoc();
3415 }
3416
3417 child_range children() {
3418 return child_range(child_iterator(), child_iterator());
3419 }
3420
3421 const_child_range children() const {
3422 return const_child_range(const_child_iterator(), const_child_iterator());
3423 }
3424
3425 static bool classof(const Stmt *T) {
3426 return T->getStmtClass() == UnresolvedLookupExprClass;
3427 }
3428};
3429
3430/// A qualified reference to a name whose declaration cannot
3431/// yet be resolved.
3432///
3433/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
3434/// it expresses a reference to a declaration such as
3435/// X<T>::value. The difference, however, is that an
3436/// DependentScopeDeclRefExpr node is used only within C++ templates when
3437/// the qualification (e.g., X<T>::) refers to a dependent type. In
3438/// this case, X<T>::value cannot resolve to a declaration because the
3439/// declaration will differ from one instantiation of X<T> to the
3440/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
3441/// qualifier (X<T>::) and the name of the entity being referenced
3442/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
3443/// declaration can be found.
3444class DependentScopeDeclRefExpr final
3445 : public Expr,
3446 private llvm::TrailingObjects<DependentScopeDeclRefExpr,
3447 ASTTemplateKWAndArgsInfo,
3448 TemplateArgumentLoc> {
3449 friend class ASTStmtReader;
3450 friend class ASTStmtWriter;
3451 friend TrailingObjects;
3452
3453 /// The nested-name-specifier that qualifies this unresolved
3454 /// declaration name.
3455 NestedNameSpecifierLoc QualifierLoc;
3456
3457 /// The name of the entity we will be referencing.
3458 DeclarationNameInfo NameInfo;
3459
3460 DependentScopeDeclRefExpr(QualType Ty, NestedNameSpecifierLoc QualifierLoc,
3461 SourceLocation TemplateKWLoc,
3462 const DeclarationNameInfo &NameInfo,
3463 const TemplateArgumentListInfo *Args);
3464
3465 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3466 return hasTemplateKWAndArgsInfo();
3467 }
3468
3469 bool hasTemplateKWAndArgsInfo() const {
3470 return DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo;
3471 }
3472
3473public:
3474 static DependentScopeDeclRefExpr *
3475 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
3476 SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
3477 const TemplateArgumentListInfo *TemplateArgs);
3478
3479 static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &Context,
3480 bool HasTemplateKWAndArgsInfo,
3481 unsigned NumTemplateArgs);
3482
3483 /// Retrieve the name that this expression refers to.
3484 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
3485
3486 /// Retrieve the name that this expression refers to.
3487 DeclarationName getDeclName() const { return NameInfo.getName(); }
3488
3489 /// Retrieve the location of the name within the expression.
3490 ///
3491 /// For example, in "X<T>::value" this is the location of "value".
3492 SourceLocation getLocation() const { return NameInfo.getLoc(); }
3493
3494 /// Retrieve the nested-name-specifier that qualifies the
3495 /// name, with source location information.
3496 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3497
3498 /// Retrieve the nested-name-specifier that qualifies this
3499 /// declaration.
3500 NestedNameSpecifier *getQualifier() const {
3501 return QualifierLoc.getNestedNameSpecifier();
3502 }
3503
3504 /// Retrieve the location of the template keyword preceding
3505 /// this name, if any.
3506 SourceLocation getTemplateKeywordLoc() const {
3507 if (!hasTemplateKWAndArgsInfo())
3508 return SourceLocation();
3509 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3510 }
3511
3512 /// Retrieve the location of the left angle bracket starting the
3513 /// explicit template argument list following the name, if any.
3514 SourceLocation getLAngleLoc() const {
3515 if (!hasTemplateKWAndArgsInfo())
3516 return SourceLocation();
3517 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3518 }
3519
3520 /// Retrieve the location of the right angle bracket ending the
3521 /// explicit template argument list following the name, if any.
3522 SourceLocation getRAngleLoc() const {
3523 if (!hasTemplateKWAndArgsInfo())
3524 return SourceLocation();
3525 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3526 }
3527
3528 /// Determines whether the name was preceded by the template keyword.
3529 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3530
3531 /// Determines whether this lookup had explicit template arguments.
3532 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3533
3534 /// Copies the template arguments (if present) into the given
3535 /// structure.
3536 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3537 if (hasExplicitTemplateArgs())
3538 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3539 getTrailingObjects<TemplateArgumentLoc>(), List);
3540 }
3541
3542 TemplateArgumentLoc const *getTemplateArgs() const {
3543 if (!hasExplicitTemplateArgs())
3544 return nullptr;
3545
3546 return getTrailingObjects<TemplateArgumentLoc>();
3547 }
3548
3549 unsigned getNumTemplateArgs() const {
3550 if (!hasExplicitTemplateArgs())
3551 return 0;
3552
3553 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3554 }
3555
3556 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3557 return {getTemplateArgs(), getNumTemplateArgs()};
3558 }
3559
3560 /// Note: getBeginLoc() is the start of the whole DependentScopeDeclRefExpr,
3561 /// and differs from getLocation().getStart().
3562 SourceLocation getBeginLoc() const LLVM_READONLY {
3563 return QualifierLoc.getBeginLoc();
3564 }
3565
3566 SourceLocation getEndLoc() const LLVM_READONLY {
3567 if (hasExplicitTemplateArgs())
3568 return getRAngleLoc();
3569 return getLocation();
3570 }
3571
3572 static bool classof(const Stmt *T) {
3573 return T->getStmtClass() == DependentScopeDeclRefExprClass;
3574 }
3575
3576 child_range children() {
3577 return child_range(child_iterator(), child_iterator());
3578 }
3579
3580 const_child_range children() const {
3581 return const_child_range(const_child_iterator(), const_child_iterator());
3582 }
3583};
3584
3585/// Represents an expression -- generally a full-expression -- that
3586/// introduces cleanups to be run at the end of the sub-expression's
3587/// evaluation. The most common source of expression-introduced
3588/// cleanups is temporary objects in C++, but several other kinds of
3589/// expressions can create cleanups, including basically every
3590/// call in ARC that returns an Objective-C pointer.
3591///
3592/// This expression also tracks whether the sub-expression contains a
3593/// potentially-evaluated block literal. The lifetime of a block
3594/// literal is the extent of the enclosing scope.
3595class ExprWithCleanups final
3596 : public FullExpr,
3597 private llvm::TrailingObjects<
3598 ExprWithCleanups,
3599 llvm::PointerUnion<BlockDecl *, CompoundLiteralExpr *>> {
3600public:
3601 /// The type of objects that are kept in the cleanup.
3602 /// It's useful to remember the set of blocks and block-scoped compound
3603 /// literals; we could also remember the set of temporaries, but there's
3604 /// currently no need.
3605 using CleanupObject = llvm::PointerUnion<BlockDecl *, CompoundLiteralExpr *>;
3606
3607private:
3608 friend class ASTStmtReader;
3609 friend TrailingObjects;
3610
3611 ExprWithCleanups(EmptyShell, unsigned NumObjects);
3612 ExprWithCleanups(Expr *SubExpr, bool CleanupsHaveSideEffects,
3613 ArrayRef<CleanupObject> Objects);
3614
3615public:
3616 static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
3617 unsigned numObjects);
3618
3619 static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
3620 bool CleanupsHaveSideEffects,
3621 ArrayRef<CleanupObject> objects);
3622
3623 ArrayRef<CleanupObject> getObjects() const {
3624 return getTrailingObjects(getNumObjects());
3625 }
3626
3627 unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
3628
3629 CleanupObject getObject(unsigned i) const {
3630 assert(i < getNumObjects() && "Index out of range");
3631 return getObjects()[i];
3632 }
3633
3634 bool cleanupsHaveSideEffects() const {
3635 return ExprWithCleanupsBits.CleanupsHaveSideEffects;
3636 }
3637
3638 SourceLocation getBeginLoc() const LLVM_READONLY {
3639 return SubExpr->getBeginLoc();
3640 }
3641
3642 SourceLocation getEndLoc() const LLVM_READONLY {
3643 return SubExpr->getEndLoc();
3644 }
3645
3646 // Implement isa/cast/dyncast/etc.
3647 static bool classof(const Stmt *T) {
3648 return T->getStmtClass() == ExprWithCleanupsClass;
3649 }
3650
3651 // Iterators
3652 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
3653
3654 const_child_range children() const {
3655 return const_child_range(&SubExpr, &SubExpr + 1);
3656 }
3657};
3658
3659/// Describes an explicit type conversion that uses functional
3660/// notion but could not be resolved because one or more arguments are
3661/// type-dependent.
3662///
3663/// The explicit type conversions expressed by
3664/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
3665/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
3666/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
3667/// type-dependent. For example, this would occur in a template such
3668/// as:
3669///
3670/// \code
3671/// template<typename T, typename A1>
3672/// inline T make_a(const A1& a1) {
3673/// return T(a1);
3674/// }
3675/// \endcode
3676///
3677/// When the returned expression is instantiated, it may resolve to a
3678/// constructor call, conversion function call, or some kind of type
3679/// conversion.
3680class CXXUnresolvedConstructExpr final
3681 : public Expr,
3682 private llvm::TrailingObjects<CXXUnresolvedConstructExpr, Expr *> {
3683 friend class ASTStmtReader;
3684 friend TrailingObjects;
3685
3686 /// The type being constructed, and whether the construct expression models
3687 /// list initialization or not.
3688 llvm::PointerIntPair<TypeSourceInfo *, 1> TypeAndInitForm;
3689
3690 /// The location of the left parentheses ('(').
3691 SourceLocation LParenLoc;
3692
3693 /// The location of the right parentheses (')').
3694 SourceLocation RParenLoc;
3695
3696 CXXUnresolvedConstructExpr(QualType T, TypeSourceInfo *TSI,
3697 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
3698 SourceLocation RParenLoc, bool IsListInit);
3699
3700 CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
3701 : Expr(CXXUnresolvedConstructExprClass, Empty) {
3702 CXXUnresolvedConstructExprBits.NumArgs = NumArgs;
3703 }
3704
3705public:
3706 static CXXUnresolvedConstructExpr *
3707 Create(const ASTContext &Context, QualType T, TypeSourceInfo *TSI,
3708 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
3709 SourceLocation RParenLoc, bool IsListInit);
3710
3711 static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &Context,
3712 unsigned NumArgs);
3713
3714 /// Retrieve the type that is being constructed, as specified
3715 /// in the source code.
3716 QualType getTypeAsWritten() const { return getTypeSourceInfo()->getType(); }
3717
3718 /// Retrieve the type source information for the type being
3719 /// constructed.
3720 TypeSourceInfo *getTypeSourceInfo() const {
3721 return TypeAndInitForm.getPointer();
3722 }
3723
3724 /// Retrieve the location of the left parentheses ('(') that
3725 /// precedes the argument list.
3726 SourceLocation getLParenLoc() const { return LParenLoc; }
3727 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3728
3729 /// Retrieve the location of the right parentheses (')') that
3730 /// follows the argument list.
3731 SourceLocation getRParenLoc() const { return RParenLoc; }
3732 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3733
3734 /// Determine whether this expression models list-initialization.
3735 /// If so, there will be exactly one subexpression, which will be
3736 /// an InitListExpr.
3737 bool isListInitialization() const { return TypeAndInitForm.getInt(); }
3738
3739 /// Retrieve the number of arguments.
3740 unsigned getNumArgs() const { return CXXUnresolvedConstructExprBits.NumArgs; }
3741
3742 using arg_iterator = Expr **;
3743 using arg_range = llvm::iterator_range<arg_iterator>;
3744
3745 arg_iterator arg_begin() { return getTrailingObjects(); }
3746 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3747 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3748
3749 using const_arg_iterator = const Expr* const *;
3750 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
3751
3752 const_arg_iterator arg_begin() const { return getTrailingObjects(); }
3753 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3754 const_arg_range arguments() const {
3755 return const_arg_range(arg_begin(), arg_end());
3756 }
3757
3758 Expr *getArg(unsigned I) {
3759 assert(I < getNumArgs() && "Argument index out-of-range");
3760 return arg_begin()[I];
3761 }
3762
3763 const Expr *getArg(unsigned I) const {
3764 assert(I < getNumArgs() && "Argument index out-of-range");
3765 return arg_begin()[I];
3766 }
3767
3768 void setArg(unsigned I, Expr *E) {
3769 assert(I < getNumArgs() && "Argument index out-of-range");
3770 arg_begin()[I] = E;
3771 }
3772
3773 SourceLocation getBeginLoc() const LLVM_READONLY;
3774 SourceLocation getEndLoc() const LLVM_READONLY {
3775 if (!RParenLoc.isValid() && getNumArgs() > 0)
3776 return getArg(I: getNumArgs() - 1)->getEndLoc();
3777 return RParenLoc;
3778 }
3779
3780 static bool classof(const Stmt *T) {
3781 return T->getStmtClass() == CXXUnresolvedConstructExprClass;
3782 }
3783
3784 // Iterators
3785 child_range children() {
3786 auto **begin = reinterpret_cast<Stmt **>(arg_begin());
3787 return child_range(begin, begin + getNumArgs());
3788 }
3789
3790 const_child_range children() const {
3791 auto **begin = reinterpret_cast<Stmt **>(
3792 const_cast<CXXUnresolvedConstructExpr *>(this)->arg_begin());
3793 return const_child_range(begin, begin + getNumArgs());
3794 }
3795};
3796
3797/// Represents a C++ member access expression where the actual
3798/// member referenced could not be resolved because the base
3799/// expression or the member name was dependent.
3800///
3801/// Like UnresolvedMemberExprs, these can be either implicit or
3802/// explicit accesses. It is only possible to get one of these with
3803/// an implicit access if a qualifier is provided.
3804class CXXDependentScopeMemberExpr final
3805 : public Expr,
3806 private llvm::TrailingObjects<CXXDependentScopeMemberExpr,
3807 ASTTemplateKWAndArgsInfo,
3808 TemplateArgumentLoc, NamedDecl *> {
3809 friend class ASTStmtReader;
3810 friend class ASTStmtWriter;
3811 friend TrailingObjects;
3812
3813 /// The expression for the base pointer or class reference,
3814 /// e.g., the \c x in x.f. Can be null in implicit accesses.
3815 Stmt *Base;
3816
3817 /// The type of the base expression. Never null, even for
3818 /// implicit accesses.
3819 QualType BaseType;
3820
3821 /// The nested-name-specifier that precedes the member name, if any.
3822 /// FIXME: This could be in principle store as a trailing object.
3823 /// However the performance impact of doing so should be investigated first.
3824 NestedNameSpecifierLoc QualifierLoc;
3825
3826 /// The member to which this member expression refers, which
3827 /// can be name, overloaded operator, or destructor.
3828 ///
3829 /// FIXME: could also be a template-id
3830 DeclarationNameInfo MemberNameInfo;
3831
3832 // CXXDependentScopeMemberExpr is followed by several trailing objects,
3833 // some of which optional. They are in order:
3834 //
3835 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3836 // template keyword and arguments. Present if and only if
3837 // hasTemplateKWAndArgsInfo().
3838 //
3839 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing location
3840 // information for the explicitly specified template arguments.
3841 //
3842 // * An optional NamedDecl *. In a qualified member access expression such
3843 // as t->Base::f, this member stores the resolves of name lookup in the
3844 // context of the member access expression, to be used at instantiation
3845 // time. Present if and only if hasFirstQualifierFoundInScope().
3846
3847 bool hasTemplateKWAndArgsInfo() const {
3848 return CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo;
3849 }
3850
3851 bool hasFirstQualifierFoundInScope() const {
3852 return CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope;
3853 }
3854
3855 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3856 return hasTemplateKWAndArgsInfo();
3857 }
3858
3859 unsigned numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
3860 return getNumTemplateArgs();
3861 }
3862
3863 CXXDependentScopeMemberExpr(const ASTContext &Ctx, Expr *Base,
3864 QualType BaseType, bool IsArrow,
3865 SourceLocation OperatorLoc,
3866 NestedNameSpecifierLoc QualifierLoc,
3867 SourceLocation TemplateKWLoc,
3868 NamedDecl *FirstQualifierFoundInScope,
3869 DeclarationNameInfo MemberNameInfo,
3870 const TemplateArgumentListInfo *TemplateArgs);
3871
3872 CXXDependentScopeMemberExpr(EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
3873 bool HasFirstQualifierFoundInScope);
3874
3875public:
3876 static CXXDependentScopeMemberExpr *
3877 Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
3878 SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
3879 SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
3880 DeclarationNameInfo MemberNameInfo,
3881 const TemplateArgumentListInfo *TemplateArgs);
3882
3883 static CXXDependentScopeMemberExpr *
3884 CreateEmpty(const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
3885 unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope);
3886
3887 /// True if this is an implicit access, i.e. one in which the
3888 /// member being accessed was not written in the source. The source
3889 /// location of the operator is invalid in this case.
3890 bool isImplicitAccess() const {
3891 if (!Base)
3892 return true;
3893 return cast<Expr>(Val: Base)->isImplicitCXXThis();
3894 }
3895
3896 /// Retrieve the base object of this member expressions,
3897 /// e.g., the \c x in \c x.m.
3898 Expr *getBase() const {
3899 assert(!isImplicitAccess());
3900 return cast<Expr>(Val: Base);
3901 }
3902
3903 QualType getBaseType() const { return BaseType; }
3904
3905 /// Determine whether this member expression used the '->'
3906 /// operator; otherwise, it used the '.' operator.
3907 bool isArrow() const { return CXXDependentScopeMemberExprBits.IsArrow; }
3908
3909 /// Retrieve the location of the '->' or '.' operator.
3910 SourceLocation getOperatorLoc() const {
3911 return CXXDependentScopeMemberExprBits.OperatorLoc;
3912 }
3913
3914 /// Retrieve the nested-name-specifier that qualifies the member name.
3915 NestedNameSpecifier *getQualifier() const {
3916 return QualifierLoc.getNestedNameSpecifier();
3917 }
3918
3919 /// Retrieve the nested-name-specifier that qualifies the member
3920 /// name, with source location information.
3921 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3922
3923 /// Retrieve the first part of the nested-name-specifier that was
3924 /// found in the scope of the member access expression when the member access
3925 /// was initially parsed.
3926 ///
3927 /// This function only returns a useful result when member access expression
3928 /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
3929 /// returned by this function describes what was found by unqualified name
3930 /// lookup for the identifier "Base" within the scope of the member access
3931 /// expression itself. At template instantiation time, this information is
3932 /// combined with the results of name lookup into the type of the object
3933 /// expression itself (the class type of x).
3934 NamedDecl *getFirstQualifierFoundInScope() const {
3935 if (!hasFirstQualifierFoundInScope())
3936 return nullptr;
3937 return *getTrailingObjects<NamedDecl *>();
3938 }
3939
3940 /// Retrieve the name of the member that this expression refers to.
3941 const DeclarationNameInfo &getMemberNameInfo() const {
3942 return MemberNameInfo;
3943 }
3944
3945 /// Retrieve the name of the member that this expression refers to.
3946 DeclarationName getMember() const { return MemberNameInfo.getName(); }
3947
3948 // Retrieve the location of the name of the member that this
3949 // expression refers to.
3950 SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
3951
3952 /// Retrieve the location of the template keyword preceding the
3953 /// member name, if any.
3954 SourceLocation getTemplateKeywordLoc() const {
3955 if (!hasTemplateKWAndArgsInfo())
3956 return SourceLocation();
3957 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3958 }
3959
3960 /// Retrieve the location of the left angle bracket starting the
3961 /// explicit template argument list following the member name, if any.
3962 SourceLocation getLAngleLoc() const {
3963 if (!hasTemplateKWAndArgsInfo())
3964 return SourceLocation();
3965 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3966 }
3967
3968 /// Retrieve the location of the right angle bracket ending the
3969 /// explicit template argument list following the member name, if any.
3970 SourceLocation getRAngleLoc() const {
3971 if (!hasTemplateKWAndArgsInfo())
3972 return SourceLocation();
3973 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3974 }
3975
3976 /// Determines whether the member name was preceded by the template keyword.
3977 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3978
3979 /// Determines whether this member expression actually had a C++
3980 /// template argument list explicitly specified, e.g., x.f<int>.
3981 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3982
3983 /// Copies the template arguments (if present) into the given
3984 /// structure.
3985 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3986 if (hasExplicitTemplateArgs())
3987 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3988 getTrailingObjects<TemplateArgumentLoc>(), List);
3989 }
3990
3991 /// Retrieve the template arguments provided as part of this
3992 /// template-id.
3993 const TemplateArgumentLoc *getTemplateArgs() const {
3994 if (!hasExplicitTemplateArgs())
3995 return nullptr;
3996
3997 return getTrailingObjects<TemplateArgumentLoc>();
3998 }
3999
4000 /// Retrieve the number of template arguments provided as part of this
4001 /// template-id.
4002 unsigned getNumTemplateArgs() const {
4003 if (!hasExplicitTemplateArgs())
4004 return 0;
4005
4006 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
4007 }
4008
4009 ArrayRef<TemplateArgumentLoc> template_arguments() const {
4010 return {getTemplateArgs(), getNumTemplateArgs()};
4011 }
4012
4013 SourceLocation getBeginLoc() const LLVM_READONLY {
4014 if (!isImplicitAccess())
4015 return Base->getBeginLoc();
4016 if (getQualifier())
4017 return getQualifierLoc().getBeginLoc();
4018 return MemberNameInfo.getBeginLoc();
4019 }
4020
4021 SourceLocation getEndLoc() const LLVM_READONLY {
4022 if (hasExplicitTemplateArgs())
4023 return getRAngleLoc();
4024 return MemberNameInfo.getEndLoc();
4025 }
4026
4027 static bool classof(const Stmt *T) {
4028 return T->getStmtClass() == CXXDependentScopeMemberExprClass;
4029 }
4030
4031 // Iterators
4032 child_range children() {
4033 if (isImplicitAccess())
4034 return child_range(child_iterator(), child_iterator());
4035 return child_range(&Base, &Base + 1);
4036 }
4037
4038 const_child_range children() const {
4039 if (isImplicitAccess())
4040 return const_child_range(const_child_iterator(), const_child_iterator());
4041 return const_child_range(&Base, &Base + 1);
4042 }
4043};
4044
4045/// Represents a C++ member access expression for which lookup
4046/// produced a set of overloaded functions.
4047///
4048/// The member access may be explicit or implicit:
4049/// \code
4050/// struct A {
4051/// int a, b;
4052/// int explicitAccess() { return this->a + this->A::b; }
4053/// int implicitAccess() { return a + A::b; }
4054/// };
4055/// \endcode
4056///
4057/// In the final AST, an explicit access always becomes a MemberExpr.
4058/// An implicit access may become either a MemberExpr or a
4059/// DeclRefExpr, depending on whether the member is static.
4060class UnresolvedMemberExpr final
4061 : public OverloadExpr,
4062 private llvm::TrailingObjects<UnresolvedMemberExpr, DeclAccessPair,
4063 ASTTemplateKWAndArgsInfo,
4064 TemplateArgumentLoc> {
4065 friend class ASTStmtReader;
4066 friend class OverloadExpr;
4067 friend TrailingObjects;
4068
4069 /// The expression for the base pointer or class reference,
4070 /// e.g., the \c x in x.f.
4071 ///
4072 /// This can be null if this is an 'unbased' member expression.
4073 Stmt *Base;
4074
4075 /// The type of the base expression; never null.
4076 QualType BaseType;
4077
4078 /// The location of the '->' or '.' operator.
4079 SourceLocation OperatorLoc;
4080
4081 // UnresolvedMemberExpr is followed by several trailing objects.
4082 // They are in order:
4083 //
4084 // * An array of getNumResults() DeclAccessPair for the results. These are
4085 // undesugared, which is to say, they may include UsingShadowDecls.
4086 // Access is relative to the naming class.
4087 //
4088 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
4089 // template keyword and arguments. Present if and only if
4090 // hasTemplateKWAndArgsInfo().
4091 //
4092 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
4093 // location information for the explicitly specified template arguments.
4094
4095 UnresolvedMemberExpr(const ASTContext &Context, bool HasUnresolvedUsing,
4096 Expr *Base, QualType BaseType, bool IsArrow,
4097 SourceLocation OperatorLoc,
4098 NestedNameSpecifierLoc QualifierLoc,
4099 SourceLocation TemplateKWLoc,
4100 const DeclarationNameInfo &MemberNameInfo,
4101 const TemplateArgumentListInfo *TemplateArgs,
4102 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
4103
4104 UnresolvedMemberExpr(EmptyShell Empty, unsigned NumResults,
4105 bool HasTemplateKWAndArgsInfo);
4106
4107 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
4108 return getNumDecls();
4109 }
4110
4111 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
4112 return hasTemplateKWAndArgsInfo();
4113 }
4114
4115public:
4116 static UnresolvedMemberExpr *
4117 Create(const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
4118 QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
4119 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
4120 const DeclarationNameInfo &MemberNameInfo,
4121 const TemplateArgumentListInfo *TemplateArgs,
4122 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
4123
4124 static UnresolvedMemberExpr *CreateEmpty(const ASTContext &Context,
4125 unsigned NumResults,
4126 bool HasTemplateKWAndArgsInfo,
4127 unsigned NumTemplateArgs);
4128
4129 /// True if this is an implicit access, i.e., one in which the
4130 /// member being accessed was not written in the source.
4131 ///
4132 /// The source location of the operator is invalid in this case.
4133 bool isImplicitAccess() const;
4134
4135 /// Retrieve the base object of this member expressions,
4136 /// e.g., the \c x in \c x.m.
4137 Expr *getBase() {
4138 assert(!isImplicitAccess());
4139 return cast<Expr>(Val: Base);
4140 }
4141 const Expr *getBase() const {
4142 assert(!isImplicitAccess());
4143 return cast<Expr>(Val: Base);
4144 }
4145
4146 QualType getBaseType() const { return BaseType; }
4147
4148 /// Determine whether the lookup results contain an unresolved using
4149 /// declaration.
4150 bool hasUnresolvedUsing() const {
4151 return UnresolvedMemberExprBits.HasUnresolvedUsing;
4152 }
4153
4154 /// Determine whether this member expression used the '->'
4155 /// operator; otherwise, it used the '.' operator.
4156 bool isArrow() const { return UnresolvedMemberExprBits.IsArrow; }
4157
4158 /// Retrieve the location of the '->' or '.' operator.
4159 SourceLocation getOperatorLoc() const { return OperatorLoc; }
4160
4161 /// Retrieve the naming class of this lookup.
4162 CXXRecordDecl *getNamingClass();
4163 const CXXRecordDecl *getNamingClass() const {
4164 return const_cast<UnresolvedMemberExpr *>(this)->getNamingClass();
4165 }
4166
4167 /// Retrieve the full name info for the member that this expression
4168 /// refers to.
4169 const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
4170
4171 /// Retrieve the name of the member that this expression refers to.
4172 DeclarationName getMemberName() const { return getName(); }
4173
4174 /// Retrieve the location of the name of the member that this
4175 /// expression refers to.
4176 SourceLocation getMemberLoc() const { return getNameLoc(); }
4177
4178 /// Return the preferred location (the member name) for the arrow when
4179 /// diagnosing a problem with this expression.
4180 SourceLocation getExprLoc() const LLVM_READONLY { return getMemberLoc(); }
4181
4182 SourceLocation getBeginLoc() const LLVM_READONLY {
4183 if (!isImplicitAccess())
4184 return Base->getBeginLoc();
4185 if (NestedNameSpecifierLoc l = getQualifierLoc())
4186 return l.getBeginLoc();
4187 return getMemberNameInfo().getBeginLoc();
4188 }
4189
4190 SourceLocation getEndLoc() const LLVM_READONLY {
4191 if (hasExplicitTemplateArgs())
4192 return getRAngleLoc();
4193 return getMemberNameInfo().getEndLoc();
4194 }
4195
4196 static bool classof(const Stmt *T) {
4197 return T->getStmtClass() == UnresolvedMemberExprClass;
4198 }
4199
4200 // Iterators
4201 child_range children() {
4202 if (isImplicitAccess())
4203 return child_range(child_iterator(), child_iterator());
4204 return child_range(&Base, &Base + 1);
4205 }
4206
4207 const_child_range children() const {
4208 if (isImplicitAccess())
4209 return const_child_range(const_child_iterator(), const_child_iterator());
4210 return const_child_range(&Base, &Base + 1);
4211 }
4212};
4213
4214DeclAccessPair *OverloadExpr::getTrailingResults() {
4215 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: this))
4216 return ULE->getTrailingObjects<DeclAccessPair>();
4217 return cast<UnresolvedMemberExpr>(Val: this)->getTrailingObjects<DeclAccessPair>();
4218}
4219
4220ASTTemplateKWAndArgsInfo *OverloadExpr::getTrailingASTTemplateKWAndArgsInfo() {
4221 if (!hasTemplateKWAndArgsInfo())
4222 return nullptr;
4223
4224 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: this))
4225 return ULE->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
4226 return cast<UnresolvedMemberExpr>(Val: this)
4227 ->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
4228}
4229
4230TemplateArgumentLoc *OverloadExpr::getTrailingTemplateArgumentLoc() {
4231 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: this))
4232 return ULE->getTrailingObjects<TemplateArgumentLoc>();
4233 return cast<UnresolvedMemberExpr>(Val: this)
4234 ->getTrailingObjects<TemplateArgumentLoc>();
4235}
4236
4237CXXRecordDecl *OverloadExpr::getNamingClass() {
4238 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: this))
4239 return ULE->getNamingClass();
4240 return cast<UnresolvedMemberExpr>(Val: this)->getNamingClass();
4241}
4242
4243/// Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
4244///
4245/// The noexcept expression tests whether a given expression might throw. Its
4246/// result is a boolean constant.
4247class CXXNoexceptExpr : public Expr {
4248 friend class ASTStmtReader;
4249
4250 Stmt *Operand;
4251 SourceRange Range;
4252
4253public:
4254 CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
4255 SourceLocation Keyword, SourceLocation RParen)
4256 : Expr(CXXNoexceptExprClass, Ty, VK_PRValue, OK_Ordinary),
4257 Operand(Operand), Range(Keyword, RParen) {
4258 CXXNoexceptExprBits.Value = Val == CT_Cannot;
4259 setDependence(computeDependence(E: this, CT: Val));
4260 }
4261
4262 CXXNoexceptExpr(EmptyShell Empty) : Expr(CXXNoexceptExprClass, Empty) {}
4263
4264 Expr *getOperand() const { return static_cast<Expr *>(Operand); }
4265
4266 SourceLocation getBeginLoc() const { return Range.getBegin(); }
4267 SourceLocation getEndLoc() const { return Range.getEnd(); }
4268 SourceRange getSourceRange() const { return Range; }
4269
4270 bool getValue() const { return CXXNoexceptExprBits.Value; }
4271
4272 static bool classof(const Stmt *T) {
4273 return T->getStmtClass() == CXXNoexceptExprClass;
4274 }
4275
4276 // Iterators
4277 child_range children() { return child_range(&Operand, &Operand + 1); }
4278
4279 const_child_range children() const {
4280 return const_child_range(&Operand, &Operand + 1);
4281 }
4282};
4283
4284/// Represents a C++11 pack expansion that produces a sequence of
4285/// expressions.
4286///
4287/// A pack expansion expression contains a pattern (which itself is an
4288/// expression) followed by an ellipsis. For example:
4289///
4290/// \code
4291/// template<typename F, typename ...Types>
4292/// void forward(F f, Types &&...args) {
4293/// f(static_cast<Types&&>(args)...);
4294/// }
4295/// \endcode
4296///
4297/// Here, the argument to the function object \c f is a pack expansion whose
4298/// pattern is \c static_cast<Types&&>(args). When the \c forward function
4299/// template is instantiated, the pack expansion will instantiate to zero or
4300/// or more function arguments to the function object \c f.
4301class PackExpansionExpr : public Expr {
4302 friend class ASTStmtReader;
4303 friend class ASTStmtWriter;
4304
4305 SourceLocation EllipsisLoc;
4306
4307 /// The number of expansions that will be produced by this pack
4308 /// expansion expression, if known.
4309 ///
4310 /// When zero, the number of expansions is not known. Otherwise, this value
4311 /// is the number of expansions + 1.
4312 unsigned NumExpansions;
4313
4314 Stmt *Pattern;
4315
4316public:
4317 PackExpansionExpr(Expr *Pattern, SourceLocation EllipsisLoc,
4318 UnsignedOrNone NumExpansions)
4319 : Expr(PackExpansionExprClass, Pattern->getType(),
4320 Pattern->getValueKind(), Pattern->getObjectKind()),
4321 EllipsisLoc(EllipsisLoc),
4322 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0),
4323 Pattern(Pattern) {
4324 setDependence(computeDependence(E: this));
4325 }
4326
4327 PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) {}
4328
4329 /// Retrieve the pattern of the pack expansion.
4330 Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
4331
4332 /// Retrieve the pattern of the pack expansion.
4333 const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
4334
4335 /// Retrieve the location of the ellipsis that describes this pack
4336 /// expansion.
4337 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4338
4339 /// Determine the number of expansions that will be produced when
4340 /// this pack expansion is instantiated, if already known.
4341 UnsignedOrNone getNumExpansions() const {
4342 if (NumExpansions)
4343 return NumExpansions - 1;
4344
4345 return std::nullopt;
4346 }
4347
4348 SourceLocation getBeginLoc() const LLVM_READONLY {
4349 return Pattern->getBeginLoc();
4350 }
4351
4352 SourceLocation getEndLoc() const LLVM_READONLY { return EllipsisLoc; }
4353
4354 static bool classof(const Stmt *T) {
4355 return T->getStmtClass() == PackExpansionExprClass;
4356 }
4357
4358 // Iterators
4359 child_range children() {
4360 return child_range(&Pattern, &Pattern + 1);
4361 }
4362
4363 const_child_range children() const {
4364 return const_child_range(&Pattern, &Pattern + 1);
4365 }
4366};
4367
4368/// Represents an expression that computes the length of a parameter
4369/// pack.
4370///
4371/// \code
4372/// template<typename ...Types>
4373/// struct count {
4374/// static const unsigned value = sizeof...(Types);
4375/// };
4376/// \endcode
4377class SizeOfPackExpr final
4378 : public Expr,
4379 private llvm::TrailingObjects<SizeOfPackExpr, TemplateArgument> {
4380 friend class ASTStmtReader;
4381 friend class ASTStmtWriter;
4382 friend TrailingObjects;
4383
4384 /// The location of the \c sizeof keyword.
4385 SourceLocation OperatorLoc;
4386
4387 /// The location of the name of the parameter pack.
4388 SourceLocation PackLoc;
4389
4390 /// The location of the closing parenthesis.
4391 SourceLocation RParenLoc;
4392
4393 /// The length of the parameter pack, if known.
4394 ///
4395 /// When this expression is not value-dependent, this is the length of
4396 /// the pack. When the expression was parsed rather than instantiated
4397 /// (and thus is value-dependent), this is zero.
4398 ///
4399 /// After partial substitution into a sizeof...(X) expression (for instance,
4400 /// within an alias template or during function template argument deduction),
4401 /// we store a trailing array of partially-substituted TemplateArguments,
4402 /// and this is the length of that array.
4403 unsigned Length;
4404
4405 /// The parameter pack.
4406 NamedDecl *Pack = nullptr;
4407
4408 /// Create an expression that computes the length of
4409 /// the given parameter pack.
4410 SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
4411 SourceLocation PackLoc, SourceLocation RParenLoc,
4412 UnsignedOrNone Length, ArrayRef<TemplateArgument> PartialArgs)
4413 : Expr(SizeOfPackExprClass, SizeType, VK_PRValue, OK_Ordinary),
4414 OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
4415 Length(Length ? *Length : PartialArgs.size()), Pack(Pack) {
4416 assert((!Length || PartialArgs.empty()) &&
4417 "have partial args for non-dependent sizeof... expression");
4418 auto *Args = getTrailingObjects();
4419 llvm::uninitialized_copy(PartialArgs, Args);
4420 setDependence(Length ? ExprDependence::None
4421 : ExprDependence::ValueInstantiation);
4422 }
4423
4424 /// Create an empty expression.
4425 SizeOfPackExpr(EmptyShell Empty, unsigned NumPartialArgs)
4426 : Expr(SizeOfPackExprClass, Empty), Length(NumPartialArgs) {}
4427
4428public:
4429 static SizeOfPackExpr *Create(ASTContext &Context, SourceLocation OperatorLoc,
4430 NamedDecl *Pack, SourceLocation PackLoc,
4431 SourceLocation RParenLoc,
4432 UnsignedOrNone Length = std::nullopt,
4433 ArrayRef<TemplateArgument> PartialArgs = {});
4434 static SizeOfPackExpr *CreateDeserialized(ASTContext &Context,
4435 unsigned NumPartialArgs);
4436
4437 /// Determine the location of the 'sizeof' keyword.
4438 SourceLocation getOperatorLoc() const { return OperatorLoc; }
4439
4440 /// Determine the location of the parameter pack.
4441 SourceLocation getPackLoc() const { return PackLoc; }
4442
4443 /// Determine the location of the right parenthesis.
4444 SourceLocation getRParenLoc() const { return RParenLoc; }
4445
4446 /// Retrieve the parameter pack.
4447 NamedDecl *getPack() const { return Pack; }
4448
4449 /// Retrieve the length of the parameter pack.
4450 ///
4451 /// This routine may only be invoked when the expression is not
4452 /// value-dependent.
4453 unsigned getPackLength() const {
4454 assert(!isValueDependent() &&
4455 "Cannot get the length of a value-dependent pack size expression");
4456 return Length;
4457 }
4458
4459 /// Determine whether this represents a partially-substituted sizeof...
4460 /// expression, such as is produced for:
4461 ///
4462 /// template<typename ...Ts> using X = int[sizeof...(Ts)];
4463 /// template<typename ...Us> void f(X<Us..., 1, 2, 3, Us...>);
4464 bool isPartiallySubstituted() const {
4465 return isValueDependent() && Length;
4466 }
4467
4468 /// Get
4469 ArrayRef<TemplateArgument> getPartialArguments() const {
4470 assert(isPartiallySubstituted());
4471 return getTrailingObjects(Length);
4472 }
4473
4474 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
4475 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4476
4477 static bool classof(const Stmt *T) {
4478 return T->getStmtClass() == SizeOfPackExprClass;
4479 }
4480
4481 // Iterators
4482 child_range children() {
4483 return child_range(child_iterator(), child_iterator());
4484 }
4485
4486 const_child_range children() const {
4487 return const_child_range(const_child_iterator(), const_child_iterator());
4488 }
4489};
4490
4491class PackIndexingExpr final
4492 : public Expr,
4493 private llvm::TrailingObjects<PackIndexingExpr, Expr *> {
4494 friend class ASTStmtReader;
4495 friend class ASTStmtWriter;
4496 friend TrailingObjects;
4497
4498 SourceLocation EllipsisLoc;
4499
4500 // The location of the closing bracket
4501 SourceLocation RSquareLoc;
4502
4503 // The pack being indexed, followed by the index
4504 Stmt *SubExprs[2];
4505
4506 PackIndexingExpr(QualType Type, SourceLocation EllipsisLoc,
4507 SourceLocation RSquareLoc, Expr *PackIdExpr, Expr *IndexExpr,
4508 ArrayRef<Expr *> SubstitutedExprs = {},
4509 bool FullySubstituted = false)
4510 : Expr(PackIndexingExprClass, Type, VK_LValue, OK_Ordinary),
4511 EllipsisLoc(EllipsisLoc), RSquareLoc(RSquareLoc),
4512 SubExprs{PackIdExpr, IndexExpr} {
4513 PackIndexingExprBits.TransformedExpressions = SubstitutedExprs.size();
4514 PackIndexingExprBits.FullySubstituted = FullySubstituted;
4515 llvm::uninitialized_copy(SubstitutedExprs, getTrailingObjects());
4516
4517 setDependence(computeDependence(E: this));
4518 if (!isInstantiationDependent())
4519 setValueKind(getSelectedExpr()->getValueKind());
4520 }
4521
4522 /// Create an empty expression.
4523 PackIndexingExpr(EmptyShell Empty) : Expr(PackIndexingExprClass, Empty) {}
4524
4525 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4526 return PackIndexingExprBits.TransformedExpressions;
4527 }
4528
4529public:
4530 static PackIndexingExpr *Create(ASTContext &Context,
4531 SourceLocation EllipsisLoc,
4532 SourceLocation RSquareLoc, Expr *PackIdExpr,
4533 Expr *IndexExpr, std::optional<int64_t> Index,
4534 ArrayRef<Expr *> SubstitutedExprs = {},
4535 bool FullySubstituted = false);
4536 static PackIndexingExpr *CreateDeserialized(ASTContext &Context,
4537 unsigned NumTransformedExprs);
4538
4539 // The index expression and all elements of the pack have been substituted.
4540 bool isFullySubstituted() const {
4541 return PackIndexingExprBits.FullySubstituted;
4542 }
4543
4544 /// Determine if the expression was expanded to empty.
4545 bool expandsToEmptyPack() const {
4546 return isFullySubstituted() &&
4547 PackIndexingExprBits.TransformedExpressions == 0;
4548 }
4549
4550 /// Determine the location of the 'sizeof' keyword.
4551 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4552
4553 /// Determine the location of the parameter pack.
4554 SourceLocation getPackLoc() const { return SubExprs[0]->getBeginLoc(); }
4555
4556 /// Determine the location of the right parenthesis.
4557 SourceLocation getRSquareLoc() const { return RSquareLoc; }
4558
4559 SourceLocation getBeginLoc() const LLVM_READONLY { return getPackLoc(); }
4560 SourceLocation getEndLoc() const LLVM_READONLY { return RSquareLoc; }
4561
4562 Expr *getPackIdExpression() const { return cast<Expr>(Val: SubExprs[0]); }
4563
4564 NamedDecl *getPackDecl() const;
4565
4566 Expr *getIndexExpr() const { return cast<Expr>(Val: SubExprs[1]); }
4567
4568 UnsignedOrNone getSelectedIndex() const {
4569 if (isInstantiationDependent())
4570 return std::nullopt;
4571 ConstantExpr *CE = cast<ConstantExpr>(Val: getIndexExpr());
4572 auto Index = CE->getResultAsAPSInt();
4573 assert(Index.isNonNegative() && "Invalid index");
4574 return static_cast<unsigned>(Index.getExtValue());
4575 }
4576
4577 Expr *getSelectedExpr() const {
4578 UnsignedOrNone Index = getSelectedIndex();
4579 assert(Index && "extracting the indexed expression of a dependant pack");
4580 return getTrailingObjects()[*Index];
4581 }
4582
4583 /// Return the trailing expressions, regardless of the expansion.
4584 ArrayRef<Expr *> getExpressions() const {
4585 return getTrailingObjects(PackIndexingExprBits.TransformedExpressions);
4586 }
4587
4588 static bool classof(const Stmt *T) {
4589 return T->getStmtClass() == PackIndexingExprClass;
4590 }
4591
4592 // Iterators
4593 child_range children() { return child_range(SubExprs, SubExprs + 2); }
4594
4595 const_child_range children() const {
4596 return const_child_range(SubExprs, SubExprs + 2);
4597 }
4598};
4599
4600/// Represents a reference to a non-type template parameter
4601/// that has been substituted with a template argument.
4602class SubstNonTypeTemplateParmExpr : public Expr {
4603 friend class ASTReader;
4604 friend class ASTStmtReader;
4605
4606 /// The replacement expression.
4607 Stmt *Replacement;
4608
4609 /// The associated declaration and a flag indicating if it was a reference
4610 /// parameter. For class NTTPs, we can't determine that based on the value
4611 /// category alone.
4612 llvm::PointerIntPair<Decl *, 1, bool> AssociatedDeclAndRef;
4613
4614 unsigned Index : 15;
4615 unsigned PackIndex : 15;
4616 LLVM_PREFERRED_TYPE(bool)
4617 unsigned Final : 1;
4618
4619 explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
4620 : Expr(SubstNonTypeTemplateParmExprClass, Empty) {}
4621
4622public:
4623 SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind,
4624 SourceLocation Loc, Expr *Replacement,
4625 Decl *AssociatedDecl, unsigned Index,
4626 UnsignedOrNone PackIndex, bool RefParam,
4627 bool Final)
4628 : Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary),
4629 Replacement(Replacement),
4630 AssociatedDeclAndRef(AssociatedDecl, RefParam), Index(Index),
4631 PackIndex(PackIndex.toInternalRepresentation()), Final(Final) {
4632 assert(AssociatedDecl != nullptr);
4633 SubstNonTypeTemplateParmExprBits.NameLoc = Loc;
4634 setDependence(computeDependence(E: this));
4635 }
4636
4637 SourceLocation getNameLoc() const {
4638 return SubstNonTypeTemplateParmExprBits.NameLoc;
4639 }
4640 SourceLocation getBeginLoc() const { return getNameLoc(); }
4641 SourceLocation getEndLoc() const { return getNameLoc(); }
4642
4643 Expr *getReplacement() const { return cast<Expr>(Val: Replacement); }
4644
4645 /// A template-like entity which owns the whole pattern being substituted.
4646 /// This will own a set of template parameters.
4647 Decl *getAssociatedDecl() const { return AssociatedDeclAndRef.getPointer(); }
4648
4649 /// Returns the index of the replaced parameter in the associated declaration.
4650 /// This should match the result of `getParameter()->getIndex()`.
4651 unsigned getIndex() const { return Index; }
4652
4653 UnsignedOrNone getPackIndex() const {
4654 return UnsignedOrNone::fromInternalRepresentation(Rep: PackIndex);
4655 }
4656
4657 // This substitution is Final, which means the substitution is fully
4658 // sugared: it doesn't need to be resugared later.
4659 bool getFinal() const { return Final; }
4660
4661 NonTypeTemplateParmDecl *getParameter() const;
4662
4663 bool isReferenceParameter() const { return AssociatedDeclAndRef.getInt(); }
4664
4665 /// Determine the substituted type of the template parameter.
4666 QualType getParameterType(const ASTContext &Ctx) const;
4667
4668 static bool classof(const Stmt *s) {
4669 return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
4670 }
4671
4672 // Iterators
4673 child_range children() { return child_range(&Replacement, &Replacement + 1); }
4674
4675 const_child_range children() const {
4676 return const_child_range(&Replacement, &Replacement + 1);
4677 }
4678};
4679
4680/// Represents a reference to a non-type template parameter pack that
4681/// has been substituted with a non-template argument pack.
4682///
4683/// When a pack expansion in the source code contains multiple parameter packs
4684/// and those parameter packs correspond to different levels of template
4685/// parameter lists, this node is used to represent a non-type template
4686/// parameter pack from an outer level, which has already had its argument pack
4687/// substituted but that still lives within a pack expansion that itself
4688/// could not be instantiated. When actually performing a substitution into
4689/// that pack expansion (e.g., when all template parameters have corresponding
4690/// arguments), this type will be replaced with the appropriate underlying
4691/// expression at the current pack substitution index.
4692class SubstNonTypeTemplateParmPackExpr : public Expr {
4693 friend class ASTReader;
4694 friend class ASTStmtReader;
4695
4696 /// The non-type template parameter pack itself.
4697 Decl *AssociatedDecl;
4698
4699 /// A pointer to the set of template arguments that this
4700 /// parameter pack is instantiated with.
4701 const TemplateArgument *Arguments;
4702
4703 /// The number of template arguments in \c Arguments.
4704 unsigned NumArguments : 15;
4705
4706 LLVM_PREFERRED_TYPE(bool)
4707 unsigned Final : 1;
4708
4709 unsigned Index : 16;
4710
4711 /// The location of the non-type template parameter pack reference.
4712 SourceLocation NameLoc;
4713
4714 explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
4715 : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) {}
4716
4717public:
4718 SubstNonTypeTemplateParmPackExpr(QualType T, ExprValueKind ValueKind,
4719 SourceLocation NameLoc,
4720 const TemplateArgument &ArgPack,
4721 Decl *AssociatedDecl, unsigned Index,
4722 bool Final);
4723
4724 /// A template-like entity which owns the whole pattern being substituted.
4725 /// This will own a set of template parameters.
4726 Decl *getAssociatedDecl() const { return AssociatedDecl; }
4727
4728 /// Returns the index of the replaced parameter in the associated declaration.
4729 /// This should match the result of `getParameterPack()->getIndex()`.
4730 unsigned getIndex() const { return Index; }
4731
4732 // This substitution will be Final, which means the substitution will be fully
4733 // sugared: it doesn't need to be resugared later.
4734 bool getFinal() const { return Final; }
4735
4736 /// Retrieve the non-type template parameter pack being substituted.
4737 NonTypeTemplateParmDecl *getParameterPack() const;
4738
4739 /// Retrieve the location of the parameter pack name.
4740 SourceLocation getParameterPackLocation() const { return NameLoc; }
4741
4742 /// Retrieve the template argument pack containing the substituted
4743 /// template arguments.
4744 TemplateArgument getArgumentPack() const;
4745
4746 SourceLocation getBeginLoc() const LLVM_READONLY { return NameLoc; }
4747 SourceLocation getEndLoc() const LLVM_READONLY { return NameLoc; }
4748
4749 static bool classof(const Stmt *T) {
4750 return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
4751 }
4752
4753 // Iterators
4754 child_range children() {
4755 return child_range(child_iterator(), child_iterator());
4756 }
4757
4758 const_child_range children() const {
4759 return const_child_range(const_child_iterator(), const_child_iterator());
4760 }
4761};
4762
4763/// Represents a reference to a function parameter pack, init-capture pack,
4764/// or binding pack that has been substituted but not yet expanded.
4765///
4766/// When a pack expansion contains multiple parameter packs at different levels,
4767/// this node is used to represent a function parameter pack at an outer level
4768/// which we have already substituted to refer to expanded parameters, but where
4769/// the containing pack expansion cannot yet be expanded.
4770///
4771/// \code
4772/// template<typename...Ts> struct S {
4773/// template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
4774/// };
4775/// template struct S<int, int>;
4776/// \endcode
4777class FunctionParmPackExpr final
4778 : public Expr,
4779 private llvm::TrailingObjects<FunctionParmPackExpr, ValueDecl *> {
4780 friend class ASTReader;
4781 friend class ASTStmtReader;
4782 friend TrailingObjects;
4783
4784 /// The function parameter pack which was referenced.
4785 ValueDecl *ParamPack;
4786
4787 /// The location of the function parameter pack reference.
4788 SourceLocation NameLoc;
4789
4790 /// The number of expansions of this pack.
4791 unsigned NumParameters;
4792
4793 FunctionParmPackExpr(QualType T, ValueDecl *ParamPack, SourceLocation NameLoc,
4794 unsigned NumParams, ValueDecl *const *Params);
4795
4796public:
4797 static FunctionParmPackExpr *Create(const ASTContext &Context, QualType T,
4798 ValueDecl *ParamPack,
4799 SourceLocation NameLoc,
4800 ArrayRef<ValueDecl *> Params);
4801 static FunctionParmPackExpr *CreateEmpty(const ASTContext &Context,
4802 unsigned NumParams);
4803
4804 /// Get the parameter pack which this expression refers to.
4805 ValueDecl *getParameterPack() const { return ParamPack; }
4806
4807 /// Get the location of the parameter pack.
4808 SourceLocation getParameterPackLocation() const { return NameLoc; }
4809
4810 /// Iterators over the parameters which the parameter pack expanded
4811 /// into.
4812 using iterator = ValueDecl *const *;
4813 iterator begin() const { return getTrailingObjects(); }
4814 iterator end() const { return begin() + NumParameters; }
4815
4816 /// Get the number of parameters in this parameter pack.
4817 unsigned getNumExpansions() const { return NumParameters; }
4818
4819 /// Get an expansion of the parameter pack by index.
4820 ValueDecl *getExpansion(unsigned I) const { return begin()[I]; }
4821
4822 SourceLocation getBeginLoc() const LLVM_READONLY { return NameLoc; }
4823 SourceLocation getEndLoc() const LLVM_READONLY { return NameLoc; }
4824
4825 static bool classof(const Stmt *T) {
4826 return T->getStmtClass() == FunctionParmPackExprClass;
4827 }
4828
4829 child_range children() {
4830 return child_range(child_iterator(), child_iterator());
4831 }
4832
4833 const_child_range children() const {
4834 return const_child_range(const_child_iterator(), const_child_iterator());
4835 }
4836};
4837
4838/// Represents a prvalue temporary that is written into memory so that
4839/// a reference can bind to it.
4840///
4841/// Prvalue expressions are materialized when they need to have an address
4842/// in memory for a reference to bind to. This happens when binding a
4843/// reference to the result of a conversion, e.g.,
4844///
4845/// \code
4846/// const int &r = 1.0;
4847/// \endcode
4848///
4849/// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
4850/// then materialized via a \c MaterializeTemporaryExpr, and the reference
4851/// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
4852/// (either an lvalue or an xvalue, depending on the kind of reference binding
4853/// to it), maintaining the invariant that references always bind to glvalues.
4854///
4855/// Reference binding and copy-elision can both extend the lifetime of a
4856/// temporary. When either happens, the expression will also track the
4857/// declaration which is responsible for the lifetime extension.
4858class MaterializeTemporaryExpr : public Expr {
4859private:
4860 friend class ASTStmtReader;
4861 friend class ASTStmtWriter;
4862
4863 llvm::PointerUnion<Stmt *, LifetimeExtendedTemporaryDecl *> State;
4864
4865public:
4866 MaterializeTemporaryExpr(QualType T, Expr *Temporary,
4867 bool BoundToLvalueReference,
4868 LifetimeExtendedTemporaryDecl *MTD = nullptr);
4869
4870 MaterializeTemporaryExpr(EmptyShell Empty)
4871 : Expr(MaterializeTemporaryExprClass, Empty) {}
4872
4873 /// Retrieve the temporary-generating subexpression whose value will
4874 /// be materialized into a glvalue.
4875 Expr *getSubExpr() const {
4876 return cast<Expr>(
4877 isa<Stmt *>(Val: State)
4878 ? cast<Stmt *>(Val: State)
4879 : cast<LifetimeExtendedTemporaryDecl *>(Val: State)->getTemporaryExpr());
4880 }
4881
4882 /// Retrieve the storage duration for the materialized temporary.
4883 StorageDuration getStorageDuration() const {
4884 return isa<Stmt *>(Val: State) ? SD_FullExpression
4885 : cast<LifetimeExtendedTemporaryDecl *>(Val: State)
4886 ->getStorageDuration();
4887 }
4888
4889 /// Get the storage for the constant value of a materialized temporary
4890 /// of static storage duration.
4891 APValue *getOrCreateValue(bool MayCreate) const {
4892 assert(isa<LifetimeExtendedTemporaryDecl *>(State) &&
4893 "the temporary has not been lifetime extended");
4894 return cast<LifetimeExtendedTemporaryDecl *>(Val: State)->getOrCreateValue(
4895 MayCreate);
4896 }
4897
4898 LifetimeExtendedTemporaryDecl *getLifetimeExtendedTemporaryDecl() {
4899 return State.dyn_cast<LifetimeExtendedTemporaryDecl *>();
4900 }
4901 const LifetimeExtendedTemporaryDecl *
4902 getLifetimeExtendedTemporaryDecl() const {
4903 return State.dyn_cast<LifetimeExtendedTemporaryDecl *>();
4904 }
4905
4906 /// Get the declaration which triggered the lifetime-extension of this
4907 /// temporary, if any.
4908 ValueDecl *getExtendingDecl() {
4909 return isa<Stmt *>(Val: State) ? nullptr
4910 : cast<LifetimeExtendedTemporaryDecl *>(Val&: State)
4911 ->getExtendingDecl();
4912 }
4913 const ValueDecl *getExtendingDecl() const {
4914 return const_cast<MaterializeTemporaryExpr *>(this)->getExtendingDecl();
4915 }
4916
4917 void setExtendingDecl(ValueDecl *ExtendedBy, unsigned ManglingNumber);
4918
4919 unsigned getManglingNumber() const {
4920 return isa<Stmt *>(Val: State) ? 0
4921 : cast<LifetimeExtendedTemporaryDecl *>(Val: State)
4922 ->getManglingNumber();
4923 }
4924
4925 /// Determine whether this materialized temporary is bound to an
4926 /// lvalue reference; otherwise, it's bound to an rvalue reference.
4927 bool isBoundToLvalueReference() const { return isLValue(); }
4928
4929 /// Determine whether this temporary object is usable in constant
4930 /// expressions, as specified in C++20 [expr.const]p4.
4931 bool isUsableInConstantExpressions(const ASTContext &Context) const;
4932
4933 SourceLocation getBeginLoc() const LLVM_READONLY {
4934 return getSubExpr()->getBeginLoc();
4935 }
4936
4937 SourceLocation getEndLoc() const LLVM_READONLY {
4938 return getSubExpr()->getEndLoc();
4939 }
4940
4941 static bool classof(const Stmt *T) {
4942 return T->getStmtClass() == MaterializeTemporaryExprClass;
4943 }
4944
4945 // Iterators
4946 child_range children() {
4947 return isa<Stmt *>(Val: State)
4948 ? child_range(State.getAddrOfPtr1(), State.getAddrOfPtr1() + 1)
4949 : cast<LifetimeExtendedTemporaryDecl *>(Val&: State)->childrenExpr();
4950 }
4951
4952 const_child_range children() const {
4953 return isa<Stmt *>(Val: State)
4954 ? const_child_range(State.getAddrOfPtr1(),
4955 State.getAddrOfPtr1() + 1)
4956 : const_cast<const LifetimeExtendedTemporaryDecl *>(
4957 cast<LifetimeExtendedTemporaryDecl *>(Val: State))
4958 ->childrenExpr();
4959 }
4960};
4961
4962/// Represents a folding of a pack over an operator.
4963///
4964/// This expression is always dependent and represents a pack expansion of the
4965/// forms:
4966///
4967/// ( expr op ... )
4968/// ( ... op expr )
4969/// ( expr op ... op expr )
4970class CXXFoldExpr : public Expr {
4971 friend class ASTStmtReader;
4972 friend class ASTStmtWriter;
4973
4974 enum SubExpr { Callee, LHS, RHS, Count };
4975
4976 SourceLocation LParenLoc;
4977 SourceLocation EllipsisLoc;
4978 SourceLocation RParenLoc;
4979 // When 0, the number of expansions is not known. Otherwise, this is one more
4980 // than the number of expansions.
4981 UnsignedOrNone NumExpansions = std::nullopt;
4982 Stmt *SubExprs[SubExpr::Count];
4983
4984public:
4985 CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee,
4986 SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Opcode,
4987 SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc,
4988 UnsignedOrNone NumExpansions);
4989
4990 CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
4991
4992 UnresolvedLookupExpr *getCallee() const {
4993 return static_cast<UnresolvedLookupExpr *>(SubExprs[SubExpr::Callee]);
4994 }
4995 Expr *getLHS() const { return static_cast<Expr*>(SubExprs[SubExpr::LHS]); }
4996 Expr *getRHS() const { return static_cast<Expr*>(SubExprs[SubExpr::RHS]); }
4997
4998 /// Does this produce a right-associated sequence of operators?
4999 bool isRightFold() const {
5000 return getLHS() && getLHS()->containsUnexpandedParameterPack();
5001 }
5002
5003 /// Does this produce a left-associated sequence of operators?
5004 bool isLeftFold() const { return !isRightFold(); }
5005
5006 /// Get the pattern, that is, the operand that contains an unexpanded pack.
5007 Expr *getPattern() const { return isLeftFold() ? getRHS() : getLHS(); }
5008
5009 /// Get the operand that doesn't contain a pack, for a binary fold.
5010 Expr *getInit() const { return isLeftFold() ? getLHS() : getRHS(); }
5011
5012 SourceLocation getLParenLoc() const { return LParenLoc; }
5013 SourceLocation getRParenLoc() const { return RParenLoc; }
5014 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
5015 BinaryOperatorKind getOperator() const { return CXXFoldExprBits.Opcode; }
5016
5017 UnsignedOrNone getNumExpansions() const { return NumExpansions; }
5018
5019 SourceLocation getBeginLoc() const LLVM_READONLY {
5020 if (LParenLoc.isValid())
5021 return LParenLoc;
5022 if (isLeftFold())
5023 return getEllipsisLoc();
5024 return getLHS()->getBeginLoc();
5025 }
5026
5027 SourceLocation getEndLoc() const LLVM_READONLY {
5028 if (RParenLoc.isValid())
5029 return RParenLoc;
5030 if (isRightFold())
5031 return getEllipsisLoc();
5032 return getRHS()->getEndLoc();
5033 }
5034
5035 static bool classof(const Stmt *T) {
5036 return T->getStmtClass() == CXXFoldExprClass;
5037 }
5038
5039 // Iterators
5040 child_range children() {
5041 return child_range(SubExprs, SubExprs + SubExpr::Count);
5042 }
5043
5044 const_child_range children() const {
5045 return const_child_range(SubExprs, SubExprs + SubExpr::Count);
5046 }
5047};
5048
5049/// Represents a list-initialization with parenthesis.
5050///
5051/// As per P0960R3, this is a C++20 feature that allows aggregate to
5052/// be initialized with a parenthesized list of values:
5053/// ```
5054/// struct A {
5055/// int a;
5056/// double b;
5057/// };
5058///
5059/// void foo() {
5060/// A a1(0); // Well-formed in C++20
5061/// A a2(1.5, 1.0); // Well-formed in C++20
5062/// }
5063/// ```
5064/// It has some sort of similiarity to braced
5065/// list-initialization, with some differences such as
5066/// it allows narrowing conversion whilst braced
5067/// list-initialization doesn't.
5068/// ```
5069/// struct A {
5070/// char a;
5071/// };
5072/// void foo() {
5073/// A a(1.5); // Well-formed in C++20
5074/// A b{1.5}; // Ill-formed !
5075/// }
5076/// ```
5077class CXXParenListInitExpr final
5078 : public Expr,
5079 private llvm::TrailingObjects<CXXParenListInitExpr, Expr *> {
5080 friend class TrailingObjects;
5081 friend class ASTStmtReader;
5082 friend class ASTStmtWriter;
5083
5084 unsigned NumExprs;
5085 unsigned NumUserSpecifiedExprs;
5086 SourceLocation InitLoc, LParenLoc, RParenLoc;
5087 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
5088
5089 CXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
5090 unsigned NumUserSpecifiedExprs, SourceLocation InitLoc,
5091 SourceLocation LParenLoc, SourceLocation RParenLoc)
5092 : Expr(CXXParenListInitExprClass, T, getValueKindForType(T), OK_Ordinary),
5093 NumExprs(Args.size()), NumUserSpecifiedExprs(NumUserSpecifiedExprs),
5094 InitLoc(InitLoc), LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
5095 llvm::copy(Args, getTrailingObjects());
5096 assert(NumExprs >= NumUserSpecifiedExprs &&
5097 "number of user specified inits is greater than the number of "
5098 "passed inits");
5099 setDependence(computeDependence(E: this));
5100 }
5101
5102 size_t numTrailingObjects(OverloadToken<Expr *>) const { return NumExprs; }
5103
5104public:
5105 static CXXParenListInitExpr *
5106 Create(ASTContext &C, ArrayRef<Expr *> Args, QualType T,
5107 unsigned NumUserSpecifiedExprs, SourceLocation InitLoc,
5108 SourceLocation LParenLoc, SourceLocation RParenLoc);
5109
5110 static CXXParenListInitExpr *CreateEmpty(ASTContext &C, unsigned numExprs,
5111 EmptyShell Empty);
5112
5113 explicit CXXParenListInitExpr(EmptyShell Empty, unsigned NumExprs)
5114 : Expr(CXXParenListInitExprClass, Empty), NumExprs(NumExprs),
5115 NumUserSpecifiedExprs(0) {}
5116
5117 void updateDependence() { setDependence(computeDependence(E: this)); }
5118
5119 MutableArrayRef<Expr *> getInitExprs() {
5120 return getTrailingObjects(NumExprs);
5121 }
5122
5123 ArrayRef<Expr *> getInitExprs() const { return getTrailingObjects(NumExprs); }
5124
5125 ArrayRef<Expr *> getUserSpecifiedInitExprs() {
5126 return getTrailingObjects(NumUserSpecifiedExprs);
5127 }
5128
5129 ArrayRef<Expr *> getUserSpecifiedInitExprs() const {
5130 return getTrailingObjects(NumUserSpecifiedExprs);
5131 }
5132
5133 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
5134
5135 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
5136
5137 SourceLocation getInitLoc() const LLVM_READONLY { return InitLoc; }
5138
5139 SourceRange getSourceRange() const LLVM_READONLY {
5140 return SourceRange(getBeginLoc(), getEndLoc());
5141 }
5142
5143 void setArrayFiller(Expr *E) { ArrayFillerOrUnionFieldInit = E; }
5144
5145 Expr *getArrayFiller() {
5146 return dyn_cast_if_present<Expr *>(Val&: ArrayFillerOrUnionFieldInit);
5147 }
5148
5149 const Expr *getArrayFiller() const {
5150 return dyn_cast_if_present<Expr *>(Val: ArrayFillerOrUnionFieldInit);
5151 }
5152
5153 void setInitializedFieldInUnion(FieldDecl *FD) {
5154 ArrayFillerOrUnionFieldInit = FD;
5155 }
5156
5157 FieldDecl *getInitializedFieldInUnion() {
5158 return dyn_cast_if_present<FieldDecl *>(Val&: ArrayFillerOrUnionFieldInit);
5159 }
5160
5161 const FieldDecl *getInitializedFieldInUnion() const {
5162 return dyn_cast_if_present<FieldDecl *>(Val: ArrayFillerOrUnionFieldInit);
5163 }
5164
5165 child_range children() {
5166 Stmt **Begin = reinterpret_cast<Stmt **>(getTrailingObjects());
5167 return child_range(Begin, Begin + NumExprs);
5168 }
5169
5170 const_child_range children() const {
5171 Stmt *const *Begin = reinterpret_cast<Stmt *const *>(getTrailingObjects());
5172 return const_child_range(Begin, Begin + NumExprs);
5173 }
5174
5175 static bool classof(const Stmt *T) {
5176 return T->getStmtClass() == CXXParenListInitExprClass;
5177 }
5178};
5179
5180/// Represents an expression that might suspend coroutine execution;
5181/// either a co_await or co_yield expression.
5182///
5183/// Evaluation of this expression first evaluates its 'ready' expression. If
5184/// that returns 'false':
5185/// -- execution of the coroutine is suspended
5186/// -- the 'suspend' expression is evaluated
5187/// -- if the 'suspend' expression returns 'false', the coroutine is
5188/// resumed
5189/// -- otherwise, control passes back to the resumer.
5190/// If the coroutine is not suspended, or when it is resumed, the 'resume'
5191/// expression is evaluated, and its result is the result of the overall
5192/// expression.
5193class CoroutineSuspendExpr : public Expr {
5194 friend class ASTStmtReader;
5195
5196 SourceLocation KeywordLoc;
5197
5198 enum SubExpr { Operand, Common, Ready, Suspend, Resume, Count };
5199
5200 Stmt *SubExprs[SubExpr::Count];
5201 OpaqueValueExpr *OpaqueValue = nullptr;
5202
5203public:
5204 // These types correspond to the three C++ 'await_suspend' return variants
5205 enum class SuspendReturnType { SuspendVoid, SuspendBool, SuspendHandle };
5206
5207 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, Expr *Operand,
5208 Expr *Common, Expr *Ready, Expr *Suspend, Expr *Resume,
5209 OpaqueValueExpr *OpaqueValue)
5210 : Expr(SC, Resume->getType(), Resume->getValueKind(),
5211 Resume->getObjectKind()),
5212 KeywordLoc(KeywordLoc), OpaqueValue(OpaqueValue) {
5213 SubExprs[SubExpr::Operand] = Operand;
5214 SubExprs[SubExpr::Common] = Common;
5215 SubExprs[SubExpr::Ready] = Ready;
5216 SubExprs[SubExpr::Suspend] = Suspend;
5217 SubExprs[SubExpr::Resume] = Resume;
5218 setDependence(computeDependence(E: this));
5219 }
5220
5221 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, QualType Ty,
5222 Expr *Operand, Expr *Common)
5223 : Expr(SC, Ty, VK_PRValue, OK_Ordinary), KeywordLoc(KeywordLoc) {
5224 assert(Common->isTypeDependent() && Ty->isDependentType() &&
5225 "wrong constructor for non-dependent co_await/co_yield expression");
5226 SubExprs[SubExpr::Operand] = Operand;
5227 SubExprs[SubExpr::Common] = Common;
5228 SubExprs[SubExpr::Ready] = nullptr;
5229 SubExprs[SubExpr::Suspend] = nullptr;
5230 SubExprs[SubExpr::Resume] = nullptr;
5231 setDependence(computeDependence(E: this));
5232 }
5233
5234 CoroutineSuspendExpr(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
5235 SubExprs[SubExpr::Operand] = nullptr;
5236 SubExprs[SubExpr::Common] = nullptr;
5237 SubExprs[SubExpr::Ready] = nullptr;
5238 SubExprs[SubExpr::Suspend] = nullptr;
5239 SubExprs[SubExpr::Resume] = nullptr;
5240 }
5241
5242 Expr *getCommonExpr() const {
5243 return static_cast<Expr*>(SubExprs[SubExpr::Common]);
5244 }
5245
5246 /// getOpaqueValue - Return the opaque value placeholder.
5247 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
5248
5249 Expr *getReadyExpr() const {
5250 return static_cast<Expr*>(SubExprs[SubExpr::Ready]);
5251 }
5252
5253 Expr *getSuspendExpr() const {
5254 return static_cast<Expr*>(SubExprs[SubExpr::Suspend]);
5255 }
5256
5257 Expr *getResumeExpr() const {
5258 return static_cast<Expr*>(SubExprs[SubExpr::Resume]);
5259 }
5260
5261 // The syntactic operand written in the code
5262 Expr *getOperand() const {
5263 return static_cast<Expr *>(SubExprs[SubExpr::Operand]);
5264 }
5265
5266 SuspendReturnType getSuspendReturnType() const {
5267 auto *SuspendExpr = getSuspendExpr();
5268 assert(SuspendExpr);
5269
5270 auto SuspendType = SuspendExpr->getType();
5271
5272 if (SuspendType->isVoidType())
5273 return SuspendReturnType::SuspendVoid;
5274 if (SuspendType->isBooleanType())
5275 return SuspendReturnType::SuspendBool;
5276
5277 // Void pointer is the type of handle.address(), which is returned
5278 // from the await suspend wrapper so that the temporary coroutine handle
5279 // value won't go to the frame by mistake
5280 assert(SuspendType->isVoidPointerType());
5281 return SuspendReturnType::SuspendHandle;
5282 }
5283
5284 SourceLocation getKeywordLoc() const { return KeywordLoc; }
5285
5286 SourceLocation getBeginLoc() const LLVM_READONLY { return KeywordLoc; }
5287
5288 SourceLocation getEndLoc() const LLVM_READONLY {
5289 return getOperand()->getEndLoc();
5290 }
5291
5292 child_range children() {
5293 return child_range(SubExprs, SubExprs + SubExpr::Count);
5294 }
5295
5296 const_child_range children() const {
5297 return const_child_range(SubExprs, SubExprs + SubExpr::Count);
5298 }
5299
5300 static bool classof(const Stmt *T) {
5301 return T->getStmtClass() == CoawaitExprClass ||
5302 T->getStmtClass() == CoyieldExprClass;
5303 }
5304};
5305
5306/// Represents a 'co_await' expression.
5307class CoawaitExpr : public CoroutineSuspendExpr {
5308 friend class ASTStmtReader;
5309
5310public:
5311 CoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand, Expr *Common,
5312 Expr *Ready, Expr *Suspend, Expr *Resume,
5313 OpaqueValueExpr *OpaqueValue, bool IsImplicit = false)
5314 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Operand, Common,
5315 Ready, Suspend, Resume, OpaqueValue) {
5316 CoawaitBits.IsImplicit = IsImplicit;
5317 }
5318
5319 CoawaitExpr(SourceLocation CoawaitLoc, QualType Ty, Expr *Operand,
5320 Expr *Common, bool IsImplicit = false)
5321 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Ty, Operand,
5322 Common) {
5323 CoawaitBits.IsImplicit = IsImplicit;
5324 }
5325
5326 CoawaitExpr(EmptyShell Empty)
5327 : CoroutineSuspendExpr(CoawaitExprClass, Empty) {}
5328
5329 bool isImplicit() const { return CoawaitBits.IsImplicit; }
5330 void setIsImplicit(bool value = true) { CoawaitBits.IsImplicit = value; }
5331
5332 static bool classof(const Stmt *T) {
5333 return T->getStmtClass() == CoawaitExprClass;
5334 }
5335};
5336
5337/// Represents a 'co_await' expression while the type of the promise
5338/// is dependent.
5339class DependentCoawaitExpr : public Expr {
5340 friend class ASTStmtReader;
5341
5342 SourceLocation KeywordLoc;
5343 Stmt *SubExprs[2];
5344
5345public:
5346 DependentCoawaitExpr(SourceLocation KeywordLoc, QualType Ty, Expr *Op,
5347 UnresolvedLookupExpr *OpCoawait)
5348 : Expr(DependentCoawaitExprClass, Ty, VK_PRValue, OK_Ordinary),
5349 KeywordLoc(KeywordLoc) {
5350 // NOTE: A co_await expression is dependent on the coroutines promise
5351 // type and may be dependent even when the `Op` expression is not.
5352 assert(Ty->isDependentType() &&
5353 "wrong constructor for non-dependent co_await/co_yield expression");
5354 SubExprs[0] = Op;
5355 SubExprs[1] = OpCoawait;
5356 setDependence(computeDependence(E: this));
5357 }
5358
5359 DependentCoawaitExpr(EmptyShell Empty)
5360 : Expr(DependentCoawaitExprClass, Empty) {}
5361
5362 Expr *getOperand() const { return cast<Expr>(Val: SubExprs[0]); }
5363
5364 UnresolvedLookupExpr *getOperatorCoawaitLookup() const {
5365 return cast<UnresolvedLookupExpr>(Val: SubExprs[1]);
5366 }
5367
5368 SourceLocation getKeywordLoc() const { return KeywordLoc; }
5369
5370 SourceLocation getBeginLoc() const LLVM_READONLY { return KeywordLoc; }
5371
5372 SourceLocation getEndLoc() const LLVM_READONLY {
5373 return getOperand()->getEndLoc();
5374 }
5375
5376 child_range children() { return child_range(SubExprs, SubExprs + 2); }
5377
5378 const_child_range children() const {
5379 return const_child_range(SubExprs, SubExprs + 2);
5380 }
5381
5382 static bool classof(const Stmt *T) {
5383 return T->getStmtClass() == DependentCoawaitExprClass;
5384 }
5385};
5386
5387/// Represents a 'co_yield' expression.
5388class CoyieldExpr : public CoroutineSuspendExpr {
5389 friend class ASTStmtReader;
5390
5391public:
5392 CoyieldExpr(SourceLocation CoyieldLoc, Expr *Operand, Expr *Common,
5393 Expr *Ready, Expr *Suspend, Expr *Resume,
5394 OpaqueValueExpr *OpaqueValue)
5395 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Operand, Common,
5396 Ready, Suspend, Resume, OpaqueValue) {}
5397 CoyieldExpr(SourceLocation CoyieldLoc, QualType Ty, Expr *Operand,
5398 Expr *Common)
5399 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Ty, Operand,
5400 Common) {}
5401 CoyieldExpr(EmptyShell Empty)
5402 : CoroutineSuspendExpr(CoyieldExprClass, Empty) {}
5403
5404 static bool classof(const Stmt *T) {
5405 return T->getStmtClass() == CoyieldExprClass;
5406 }
5407};
5408
5409/// Represents a C++2a __builtin_bit_cast(T, v) expression. Used to implement
5410/// std::bit_cast. These can sometimes be evaluated as part of a constant
5411/// expression, but otherwise CodeGen to a simple memcpy in general.
5412class BuiltinBitCastExpr final
5413 : public ExplicitCastExpr,
5414 private llvm::TrailingObjects<BuiltinBitCastExpr, CXXBaseSpecifier *> {
5415 friend class ASTStmtReader;
5416 friend class CastExpr;
5417 friend TrailingObjects;
5418
5419 SourceLocation KWLoc;
5420 SourceLocation RParenLoc;
5421
5422public:
5423 BuiltinBitCastExpr(QualType T, ExprValueKind VK, CastKind CK, Expr *SrcExpr,
5424 TypeSourceInfo *DstType, SourceLocation KWLoc,
5425 SourceLocation RParenLoc)
5426 : ExplicitCastExpr(BuiltinBitCastExprClass, T, VK, CK, SrcExpr, 0, false,
5427 DstType),
5428 KWLoc(KWLoc), RParenLoc(RParenLoc) {}
5429 BuiltinBitCastExpr(EmptyShell Empty)
5430 : ExplicitCastExpr(BuiltinBitCastExprClass, Empty, 0, false) {}
5431
5432 SourceLocation getBeginLoc() const LLVM_READONLY { return KWLoc; }
5433 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
5434
5435 static bool classof(const Stmt *T) {
5436 return T->getStmtClass() == BuiltinBitCastExprClass;
5437 }
5438};
5439
5440} // namespace clang
5441
5442#endif // LLVM_CLANG_AST_EXPRCXX_H
5443

source code of clang/include/clang/AST/ExprCXX.h