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