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