ExprCXX.h revision c65f03498f6c59b5ae5c14086f49ae6e7a173624
1//===--- ExprCXX.h - Classes for representing expressions -------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the 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/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/TemplateBase.h"
20#include "clang/AST/UnresolvedSet.h"
21#include "clang/Basic/ExpressionTraits.h"
22#include "clang/Basic/Lambda.h"
23#include "clang/Basic/TypeTraits.h"
24#include "llvm/Support/Compiler.h"
25
26namespace clang {
27
28class CXXConstructorDecl;
29class CXXDestructorDecl;
30class CXXMethodDecl;
31class CXXTemporary;
32class MSPropertyDecl;
33class TemplateArgumentListInfo;
34class UuidAttr;
35
36//===--------------------------------------------------------------------===//
37// C++ Expressions.
38//===--------------------------------------------------------------------===//
39
40/// \brief A call to an overloaded operator written using operator
41/// syntax.
42///
43/// Represents a call to an overloaded operator written using operator
44/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
45/// normal call, this AST node provides better information about the
46/// syntactic representation of the call.
47///
48/// In a C++ template, this expression node kind will be used whenever
49/// any of the arguments are type-dependent. In this case, the
50/// function itself will be a (possibly empty) set of functions and
51/// function templates that were found by name lookup at template
52/// definition time.
53class CXXOperatorCallExpr : public CallExpr {
54  /// \brief The overloaded operator.
55  OverloadedOperatorKind Operator;
56  SourceRange Range;
57
58  // Record the FP_CONTRACT state that applies to this operator call. Only
59  // meaningful for floating point types. For other types this value can be
60  // set to false.
61  unsigned FPContractable : 1;
62
63  SourceRange getSourceRangeImpl() const LLVM_READONLY;
64public:
65  CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn,
66                      ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
67                      SourceLocation operatorloc, bool fpContractable)
68    : CallExpr(C, CXXOperatorCallExprClass, fn, 0, args, t, VK,
69               operatorloc),
70      Operator(Op), FPContractable(fpContractable) {
71    Range = getSourceRangeImpl();
72  }
73  explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) :
74    CallExpr(C, CXXOperatorCallExprClass, Empty) { }
75
76
77  /// getOperator - Returns the kind of overloaded operator that this
78  /// expression refers to.
79  OverloadedOperatorKind getOperator() const { return Operator; }
80
81  /// getOperatorLoc - Returns the location of the operator symbol in
82  /// the expression. When @c getOperator()==OO_Call, this is the
83  /// location of the right parentheses; when @c
84  /// getOperator()==OO_Subscript, this is the location of the right
85  /// bracket.
86  SourceLocation getOperatorLoc() const { return getRParenLoc(); }
87
88  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
89  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
90  SourceRange getSourceRange() const { return Range; }
91
92  static bool classof(const Stmt *T) {
93    return T->getStmtClass() == CXXOperatorCallExprClass;
94  }
95
96  // Set the FP contractability status of this operator. Only meaningful for
97  // operations on floating point types.
98  void setFPContractable(bool FPC) { FPContractable = FPC; }
99
100  // Get the FP contractability status of this operator. Only meaningful for
101  // operations on floating point types.
102  bool isFPContractable() const { return FPContractable; }
103
104  friend class ASTStmtReader;
105  friend class ASTStmtWriter;
106};
107
108/// CXXMemberCallExpr - Represents a call to a member function that
109/// may be written either with member call syntax (e.g., "obj.func()"
110/// or "objptr->func()") or with normal function-call syntax
111/// ("func()") within a member function that ends up calling a member
112/// function. The callee in either case is a MemberExpr that contains
113/// both the object argument and the member function, while the
114/// arguments are the arguments within the parentheses (not including
115/// the object argument).
116class CXXMemberCallExpr : public CallExpr {
117public:
118  CXXMemberCallExpr(ASTContext &C, Expr *fn, ArrayRef<Expr*> args,
119                    QualType t, ExprValueKind VK, SourceLocation RP)
120    : CallExpr(C, CXXMemberCallExprClass, fn, 0, args, t, VK, RP) {}
121
122  CXXMemberCallExpr(ASTContext &C, EmptyShell Empty)
123    : CallExpr(C, CXXMemberCallExprClass, Empty) { }
124
125  /// getImplicitObjectArgument - Retrieves the implicit object
126  /// argument for the member call. For example, in "x.f(5)", this
127  /// operation would return "x".
128  Expr *getImplicitObjectArgument() const;
129
130  /// Retrieves the declaration of the called method.
131  CXXMethodDecl *getMethodDecl() const;
132
133  /// getRecordDecl - Retrieves the CXXRecordDecl for the underlying type of
134  /// the implicit object argument. Note that this is may not be the same
135  /// declaration as that of the class context of the CXXMethodDecl which this
136  /// function is calling.
137  /// FIXME: Returns 0 for member pointer call exprs.
138  CXXRecordDecl *getRecordDecl() const;
139
140  static bool classof(const Stmt *T) {
141    return T->getStmtClass() == CXXMemberCallExprClass;
142  }
143};
144
145/// CUDAKernelCallExpr - Represents a call to a CUDA kernel function.
146class CUDAKernelCallExpr : public CallExpr {
147private:
148  enum { CONFIG, END_PREARG };
149
150public:
151  CUDAKernelCallExpr(ASTContext &C, Expr *fn, CallExpr *Config,
152                     ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
153                     SourceLocation RP)
154    : CallExpr(C, CUDAKernelCallExprClass, fn, END_PREARG, args, t, VK, RP) {
155    setConfig(Config);
156  }
157
158  CUDAKernelCallExpr(ASTContext &C, EmptyShell Empty)
159    : CallExpr(C, CUDAKernelCallExprClass, END_PREARG, Empty) { }
160
161  const CallExpr *getConfig() const {
162    return cast_or_null<CallExpr>(getPreArg(CONFIG));
163  }
164  CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
165  void setConfig(CallExpr *E) { setPreArg(CONFIG, E); }
166
167  static bool classof(const Stmt *T) {
168    return T->getStmtClass() == CUDAKernelCallExprClass;
169  }
170};
171
172/// CXXNamedCastExpr - Abstract class common to all of the C++ "named"
173/// casts, @c static_cast, @c dynamic_cast, @c reinterpret_cast, or @c
174/// const_cast.
175///
176/// This abstract class is inherited by all of the classes
177/// representing "named" casts, e.g., CXXStaticCastExpr,
178/// CXXDynamicCastExpr, CXXReinterpretCastExpr, and CXXConstCastExpr.
179class CXXNamedCastExpr : public ExplicitCastExpr {
180private:
181  SourceLocation Loc; // the location of the casting op
182  SourceLocation RParenLoc; // the location of the right parenthesis
183  SourceRange AngleBrackets; // range for '<' '>'
184
185protected:
186  CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
187                   CastKind kind, Expr *op, unsigned PathSize,
188                   TypeSourceInfo *writtenTy, SourceLocation l,
189                   SourceLocation RParenLoc,
190                   SourceRange AngleBrackets)
191    : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
192      RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
193
194  explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
195    : ExplicitCastExpr(SC, Shell, PathSize) { }
196
197  friend class ASTStmtReader;
198
199public:
200  const char *getCastName() const;
201
202  /// \brief Retrieve the location of the cast operator keyword, e.g.,
203  /// "static_cast".
204  SourceLocation getOperatorLoc() const { return Loc; }
205
206  /// \brief Retrieve the location of the closing parenthesis.
207  SourceLocation getRParenLoc() const { return RParenLoc; }
208
209  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
210  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
211  SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
212
213  static bool classof(const Stmt *T) {
214    switch (T->getStmtClass()) {
215    case CXXStaticCastExprClass:
216    case CXXDynamicCastExprClass:
217    case CXXReinterpretCastExprClass:
218    case CXXConstCastExprClass:
219      return true;
220    default:
221      return false;
222    }
223  }
224};
225
226/// CXXStaticCastExpr - A C++ @c static_cast expression
227/// (C++ [expr.static.cast]).
228///
229/// This expression node represents a C++ static cast, e.g.,
230/// @c static_cast<int>(1.0).
231class CXXStaticCastExpr : public CXXNamedCastExpr {
232  CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
233                    unsigned pathSize, TypeSourceInfo *writtenTy,
234                    SourceLocation l, SourceLocation RParenLoc,
235                    SourceRange AngleBrackets)
236    : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
237                       writtenTy, l, RParenLoc, AngleBrackets) {}
238
239  explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
240    : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) { }
241
242public:
243  static CXXStaticCastExpr *Create(ASTContext &Context, QualType T,
244                                   ExprValueKind VK, CastKind K, Expr *Op,
245                                   const CXXCastPath *Path,
246                                   TypeSourceInfo *Written, SourceLocation L,
247                                   SourceLocation RParenLoc,
248                                   SourceRange AngleBrackets);
249  static CXXStaticCastExpr *CreateEmpty(ASTContext &Context,
250                                        unsigned PathSize);
251
252  static bool classof(const Stmt *T) {
253    return T->getStmtClass() == CXXStaticCastExprClass;
254  }
255};
256
257/// CXXDynamicCastExpr - A C++ @c dynamic_cast expression
258/// (C++ [expr.dynamic.cast]), which may perform a run-time check to
259/// determine how to perform the type cast.
260///
261/// This expression node represents a dynamic cast, e.g.,
262/// @c dynamic_cast<Derived*>(BasePtr).
263class CXXDynamicCastExpr : public CXXNamedCastExpr {
264  CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
265                     Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
266                     SourceLocation l, SourceLocation RParenLoc,
267                     SourceRange AngleBrackets)
268    : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
269                       writtenTy, l, RParenLoc, AngleBrackets) {}
270
271  explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
272    : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) { }
273
274public:
275  static CXXDynamicCastExpr *Create(ASTContext &Context, QualType T,
276                                    ExprValueKind VK, CastKind Kind, Expr *Op,
277                                    const CXXCastPath *Path,
278                                    TypeSourceInfo *Written, SourceLocation L,
279                                    SourceLocation RParenLoc,
280                                    SourceRange AngleBrackets);
281
282  static CXXDynamicCastExpr *CreateEmpty(ASTContext &Context,
283                                         unsigned pathSize);
284
285  bool isAlwaysNull() const;
286
287  static bool classof(const Stmt *T) {
288    return T->getStmtClass() == CXXDynamicCastExprClass;
289  }
290};
291
292/// CXXReinterpretCastExpr - A C++ @c reinterpret_cast expression (C++
293/// [expr.reinterpret.cast]), which provides a differently-typed view
294/// of a value but performs no actual work at run time.
295///
296/// This expression node represents a reinterpret cast, e.g.,
297/// @c reinterpret_cast<int>(VoidPtr).
298class CXXReinterpretCastExpr : public CXXNamedCastExpr {
299  CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
300                         Expr *op, unsigned pathSize,
301                         TypeSourceInfo *writtenTy, SourceLocation l,
302                         SourceLocation RParenLoc,
303                         SourceRange AngleBrackets)
304    : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
305                       pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
306
307  CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
308    : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) { }
309
310public:
311  static CXXReinterpretCastExpr *Create(ASTContext &Context, QualType T,
312                                        ExprValueKind VK, CastKind Kind,
313                                        Expr *Op, const CXXCastPath *Path,
314                                 TypeSourceInfo *WrittenTy, SourceLocation L,
315                                        SourceLocation RParenLoc,
316                                        SourceRange AngleBrackets);
317  static CXXReinterpretCastExpr *CreateEmpty(ASTContext &Context,
318                                             unsigned pathSize);
319
320  static bool classof(const Stmt *T) {
321    return T->getStmtClass() == CXXReinterpretCastExprClass;
322  }
323};
324
325/// CXXConstCastExpr - A C++ @c const_cast expression (C++ [expr.const.cast]),
326/// which can remove type qualifiers but does not change the underlying value.
327///
328/// This expression node represents a const cast, e.g.,
329/// @c const_cast<char*>(PtrToConstChar).
330class CXXConstCastExpr : public CXXNamedCastExpr {
331  CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
332                   TypeSourceInfo *writtenTy, SourceLocation l,
333                   SourceLocation RParenLoc, SourceRange AngleBrackets)
334    : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
335                       0, writtenTy, l, RParenLoc, AngleBrackets) {}
336
337  explicit CXXConstCastExpr(EmptyShell Empty)
338    : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) { }
339
340public:
341  static CXXConstCastExpr *Create(ASTContext &Context, QualType T,
342                                  ExprValueKind VK, Expr *Op,
343                                  TypeSourceInfo *WrittenTy, SourceLocation L,
344                                  SourceLocation RParenLoc,
345                                  SourceRange AngleBrackets);
346  static CXXConstCastExpr *CreateEmpty(ASTContext &Context);
347
348  static bool classof(const Stmt *T) {
349    return T->getStmtClass() == CXXConstCastExprClass;
350  }
351};
352
353/// UserDefinedLiteral - A call to a literal operator (C++11 [over.literal])
354/// written as a user-defined literal (C++11 [lit.ext]).
355///
356/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
357/// is semantically equivalent to a normal call, this AST node provides better
358/// information about the syntactic representation of the literal.
359///
360/// Since literal operators are never found by ADL and can only be declared at
361/// namespace scope, a user-defined literal is never dependent.
362class UserDefinedLiteral : public CallExpr {
363  /// \brief The location of a ud-suffix within the literal.
364  SourceLocation UDSuffixLoc;
365
366public:
367  UserDefinedLiteral(ASTContext &C, Expr *Fn, ArrayRef<Expr*> Args,
368                     QualType T, ExprValueKind VK, SourceLocation LitEndLoc,
369                     SourceLocation SuffixLoc)
370    : CallExpr(C, UserDefinedLiteralClass, Fn, 0, Args, T, VK, LitEndLoc),
371      UDSuffixLoc(SuffixLoc) {}
372  explicit UserDefinedLiteral(ASTContext &C, EmptyShell Empty)
373    : CallExpr(C, UserDefinedLiteralClass, Empty) {}
374
375  /// The kind of literal operator which is invoked.
376  enum LiteralOperatorKind {
377    LOK_Raw,      ///< Raw form: operator "" X (const char *)
378    LOK_Template, ///< Raw form: operator "" X<cs...> ()
379    LOK_Integer,  ///< operator "" X (unsigned long long)
380    LOK_Floating, ///< operator "" X (long double)
381    LOK_String,   ///< operator "" X (const CharT *, size_t)
382    LOK_Character ///< operator "" X (CharT)
383  };
384
385  /// getLiteralOperatorKind - Returns the kind of literal operator invocation
386  /// which this expression represents.
387  LiteralOperatorKind getLiteralOperatorKind() const;
388
389  /// getCookedLiteral - If this is not a raw user-defined literal, get the
390  /// underlying cooked literal (representing the literal with the suffix
391  /// removed).
392  Expr *getCookedLiteral();
393  const Expr *getCookedLiteral() const {
394    return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
395  }
396
397  SourceLocation getLocStart() const {
398    if (getLiteralOperatorKind() == LOK_Template)
399      return getRParenLoc();
400    return getArg(0)->getLocStart();
401  }
402  SourceLocation getLocEnd() const { return getRParenLoc(); }
403
404
405  /// getUDSuffixLoc - Returns the location of a ud-suffix in the expression.
406  /// For a string literal, there may be multiple identical suffixes. This
407  /// returns the first.
408  SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
409
410  /// getUDSuffix - Returns the ud-suffix specified for this literal.
411  const IdentifierInfo *getUDSuffix() const;
412
413  static bool classof(const Stmt *S) {
414    return S->getStmtClass() == UserDefinedLiteralClass;
415  }
416
417  friend class ASTStmtReader;
418  friend class ASTStmtWriter;
419};
420
421/// CXXBoolLiteralExpr - [C++ 2.13.5] C++ Boolean Literal.
422///
423class CXXBoolLiteralExpr : public Expr {
424  bool Value;
425  SourceLocation Loc;
426public:
427  CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) :
428    Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
429         false, false),
430    Value(val), Loc(l) {}
431
432  explicit CXXBoolLiteralExpr(EmptyShell Empty)
433    : Expr(CXXBoolLiteralExprClass, Empty) { }
434
435  bool getValue() const { return Value; }
436  void setValue(bool V) { Value = V; }
437
438  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
439  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
440
441  SourceLocation getLocation() const { return Loc; }
442  void setLocation(SourceLocation L) { Loc = L; }
443
444  static bool classof(const Stmt *T) {
445    return T->getStmtClass() == CXXBoolLiteralExprClass;
446  }
447
448  // Iterators
449  child_range children() { return child_range(); }
450};
451
452/// CXXNullPtrLiteralExpr - [C++0x 2.14.7] C++ Pointer Literal
453class CXXNullPtrLiteralExpr : public Expr {
454  SourceLocation Loc;
455public:
456  CXXNullPtrLiteralExpr(QualType Ty, SourceLocation l) :
457    Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
458         false, false),
459    Loc(l) {}
460
461  explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
462    : Expr(CXXNullPtrLiteralExprClass, Empty) { }
463
464  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
465  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
466
467  SourceLocation getLocation() const { return Loc; }
468  void setLocation(SourceLocation L) { Loc = L; }
469
470  static bool classof(const Stmt *T) {
471    return T->getStmtClass() == CXXNullPtrLiteralExprClass;
472  }
473
474  child_range children() { return child_range(); }
475};
476
477/// \brief Implicit construction of a std::initializer_list<T> object from an
478/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
479class CXXStdInitializerListExpr : public Expr {
480  Stmt *SubExpr;
481
482  CXXStdInitializerListExpr(EmptyShell Empty)
483    : Expr(CXXStdInitializerListExprClass, Empty), SubExpr(0) {}
484
485public:
486  CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
487    : Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
488           Ty->isDependentType(), SubExpr->isValueDependent(),
489           SubExpr->isInstantiationDependent(),
490           SubExpr->containsUnexpandedParameterPack()),
491      SubExpr(SubExpr) {}
492
493  Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
494  const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
495
496  SourceLocation getLocStart() const LLVM_READONLY {
497    return SubExpr->getLocStart();
498  }
499  SourceLocation getLocEnd() const LLVM_READONLY {
500    return SubExpr->getLocEnd();
501  }
502  SourceRange getSourceRange() const LLVM_READONLY {
503    return SubExpr->getSourceRange();
504  }
505
506  static bool classof(const Stmt *S) {
507    return S->getStmtClass() == CXXStdInitializerListExprClass;
508  }
509
510  child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
511
512  friend class ASTReader;
513  friend class ASTStmtReader;
514};
515
516/// CXXTypeidExpr - A C++ @c typeid expression (C++ [expr.typeid]), which gets
517/// the type_info that corresponds to the supplied type, or the (possibly
518/// dynamic) type of the supplied expression.
519///
520/// This represents code like @c typeid(int) or @c typeid(*objPtr)
521class CXXTypeidExpr : public Expr {
522private:
523  llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
524  SourceRange Range;
525
526public:
527  CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
528    : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
529           // typeid is never type-dependent (C++ [temp.dep.expr]p4)
530           false,
531           // typeid is value-dependent if the type or expression are dependent
532           Operand->getType()->isDependentType(),
533           Operand->getType()->isInstantiationDependentType(),
534           Operand->getType()->containsUnexpandedParameterPack()),
535      Operand(Operand), Range(R) { }
536
537  CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
538    : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
539        // typeid is never type-dependent (C++ [temp.dep.expr]p4)
540           false,
541        // typeid is value-dependent if the type or expression are dependent
542           Operand->isTypeDependent() || Operand->isValueDependent(),
543           Operand->isInstantiationDependent(),
544           Operand->containsUnexpandedParameterPack()),
545      Operand(Operand), Range(R) { }
546
547  CXXTypeidExpr(EmptyShell Empty, bool isExpr)
548    : Expr(CXXTypeidExprClass, Empty) {
549    if (isExpr)
550      Operand = (Expr*)0;
551    else
552      Operand = (TypeSourceInfo*)0;
553  }
554
555  /// Determine whether this typeid has a type operand which is potentially
556  /// evaluated, per C++11 [expr.typeid]p3.
557  bool isPotentiallyEvaluated() const;
558
559  bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
560
561  /// \brief Retrieves the type operand of this typeid() expression after
562  /// various required adjustments (removing reference types, cv-qualifiers).
563  QualType getTypeOperand() const;
564
565  /// \brief Retrieve source information for the type operand.
566  TypeSourceInfo *getTypeOperandSourceInfo() const {
567    assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
568    return Operand.get<TypeSourceInfo *>();
569  }
570
571  void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
572    assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
573    Operand = TSI;
574  }
575
576  Expr *getExprOperand() const {
577    assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
578    return static_cast<Expr*>(Operand.get<Stmt *>());
579  }
580
581  void setExprOperand(Expr *E) {
582    assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
583    Operand = E;
584  }
585
586  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
587  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
588  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
589  void setSourceRange(SourceRange R) { Range = R; }
590
591  static bool classof(const Stmt *T) {
592    return T->getStmtClass() == CXXTypeidExprClass;
593  }
594
595  // Iterators
596  child_range children() {
597    if (isTypeOperand()) return child_range();
598    Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
599    return child_range(begin, begin + 1);
600  }
601};
602
603/// A member reference to an MSPropertyDecl.  This expression always
604/// has pseudo-object type, and therefore it is typically not
605/// encountered in a fully-typechecked expression except within the
606/// syntactic form of a PseudoObjectExpr.
607class MSPropertyRefExpr : public Expr {
608  Expr *BaseExpr;
609  MSPropertyDecl *TheDecl;
610  SourceLocation MemberLoc;
611  bool IsArrow;
612  NestedNameSpecifierLoc QualifierLoc;
613
614public:
615  MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
616                    QualType ty, ExprValueKind VK,
617                    NestedNameSpecifierLoc qualifierLoc,
618                    SourceLocation nameLoc)
619  : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
620         /*type-dependent*/ false, baseExpr->isValueDependent(),
621         baseExpr->isInstantiationDependent(),
622         baseExpr->containsUnexpandedParameterPack()),
623    BaseExpr(baseExpr), TheDecl(decl),
624    MemberLoc(nameLoc), IsArrow(isArrow),
625    QualifierLoc(qualifierLoc) {}
626
627  MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
628
629  SourceRange getSourceRange() const LLVM_READONLY {
630    return SourceRange(getLocStart(), getLocEnd());
631  }
632  bool isImplicitAccess() const {
633    return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
634  }
635  SourceLocation getLocStart() const {
636    if (!isImplicitAccess())
637      return BaseExpr->getLocStart();
638    else if (QualifierLoc)
639      return QualifierLoc.getBeginLoc();
640    else
641        return MemberLoc;
642  }
643  SourceLocation getLocEnd() const { return getMemberLoc(); }
644
645  child_range children() {
646    return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
647  }
648  static bool classof(const Stmt *T) {
649    return T->getStmtClass() == MSPropertyRefExprClass;
650  }
651
652  Expr *getBaseExpr() const { return BaseExpr; }
653  MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
654  bool isArrow() const { return IsArrow; }
655  SourceLocation getMemberLoc() const { return MemberLoc; }
656  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
657
658  friend class ASTStmtReader;
659};
660
661/// CXXUuidofExpr - A microsoft C++ @c __uuidof expression, which gets
662/// the _GUID that corresponds to the supplied type or expression.
663///
664/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
665class CXXUuidofExpr : public Expr {
666private:
667  llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
668  SourceRange Range;
669
670public:
671  CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
672    : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
673           false, Operand->getType()->isDependentType(),
674           Operand->getType()->isInstantiationDependentType(),
675           Operand->getType()->containsUnexpandedParameterPack()),
676      Operand(Operand), Range(R) { }
677
678  CXXUuidofExpr(QualType Ty, Expr *Operand, SourceRange R)
679    : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
680           false, Operand->isTypeDependent(),
681           Operand->isInstantiationDependent(),
682           Operand->containsUnexpandedParameterPack()),
683      Operand(Operand), Range(R) { }
684
685  CXXUuidofExpr(EmptyShell Empty, bool isExpr)
686    : Expr(CXXUuidofExprClass, Empty) {
687    if (isExpr)
688      Operand = (Expr*)0;
689    else
690      Operand = (TypeSourceInfo*)0;
691  }
692
693  bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
694
695  /// \brief Retrieves the type operand of this __uuidof() expression after
696  /// various required adjustments (removing reference types, cv-qualifiers).
697  QualType getTypeOperand() const;
698
699  /// \brief Retrieve source information for the type operand.
700  TypeSourceInfo *getTypeOperandSourceInfo() const {
701    assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
702    return Operand.get<TypeSourceInfo *>();
703  }
704
705  void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
706    assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
707    Operand = TSI;
708  }
709
710  Expr *getExprOperand() const {
711    assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
712    return static_cast<Expr*>(Operand.get<Stmt *>());
713  }
714
715  void setExprOperand(Expr *E) {
716    assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
717    Operand = E;
718  }
719
720  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
721  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
722  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
723  void setSourceRange(SourceRange R) { Range = R; }
724
725  static bool classof(const Stmt *T) {
726    return T->getStmtClass() == CXXUuidofExprClass;
727  }
728
729  /// Grabs __declspec(uuid()) off a type, or returns 0 if there is none.
730  static UuidAttr *GetUuidAttrOfType(QualType QT);
731
732  // Iterators
733  child_range children() {
734    if (isTypeOperand()) return child_range();
735    Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
736    return child_range(begin, begin + 1);
737  }
738};
739
740/// CXXThisExpr - Represents the "this" expression in C++, which is a
741/// pointer to the object on which the current member function is
742/// executing (C++ [expr.prim]p3). Example:
743///
744/// @code
745/// class Foo {
746/// public:
747///   void bar();
748///   void test() { this->bar(); }
749/// };
750/// @endcode
751class CXXThisExpr : public Expr {
752  SourceLocation Loc;
753  bool Implicit : 1;
754
755public:
756  CXXThisExpr(SourceLocation L, QualType Type, bool isImplicit)
757    : Expr(CXXThisExprClass, Type, VK_RValue, OK_Ordinary,
758           // 'this' is type-dependent if the class type of the enclosing
759           // member function is dependent (C++ [temp.dep.expr]p2)
760           Type->isDependentType(), Type->isDependentType(),
761           Type->isInstantiationDependentType(),
762           /*ContainsUnexpandedParameterPack=*/false),
763      Loc(L), Implicit(isImplicit) { }
764
765  CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
766
767  SourceLocation getLocation() const { return Loc; }
768  void setLocation(SourceLocation L) { Loc = L; }
769
770  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
771  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
772
773  bool isImplicit() const { return Implicit; }
774  void setImplicit(bool I) { Implicit = I; }
775
776  static bool classof(const Stmt *T) {
777    return T->getStmtClass() == CXXThisExprClass;
778  }
779
780  // Iterators
781  child_range children() { return child_range(); }
782};
783
784///  CXXThrowExpr - [C++ 15] C++ Throw Expression.  This handles
785///  'throw' and 'throw' assignment-expression.  When
786///  assignment-expression isn't present, Op will be null.
787///
788class CXXThrowExpr : public Expr {
789  Stmt *Op;
790  SourceLocation ThrowLoc;
791  /// \brief Whether the thrown variable (if any) is in scope.
792  unsigned IsThrownVariableInScope : 1;
793
794  friend class ASTStmtReader;
795
796public:
797  // Ty is the void type which is used as the result type of the
798  // exepression.  The l is the location of the throw keyword.  expr
799  // can by null, if the optional expression to throw isn't present.
800  CXXThrowExpr(Expr *expr, QualType Ty, SourceLocation l,
801               bool IsThrownVariableInScope) :
802    Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
803         expr && expr->isInstantiationDependent(),
804         expr && expr->containsUnexpandedParameterPack()),
805    Op(expr), ThrowLoc(l), IsThrownVariableInScope(IsThrownVariableInScope) {}
806  CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
807
808  const Expr *getSubExpr() const { return cast_or_null<Expr>(Op); }
809  Expr *getSubExpr() { return cast_or_null<Expr>(Op); }
810
811  SourceLocation getThrowLoc() const { return ThrowLoc; }
812
813  /// \brief Determines whether the variable thrown by this expression (if any!)
814  /// is within the innermost try block.
815  ///
816  /// This information is required to determine whether the NRVO can apply to
817  /// this variable.
818  bool isThrownVariableInScope() const { return IsThrownVariableInScope; }
819
820  SourceLocation getLocStart() const LLVM_READONLY { return ThrowLoc; }
821  SourceLocation getLocEnd() const LLVM_READONLY {
822    if (getSubExpr() == 0)
823      return ThrowLoc;
824    return getSubExpr()->getLocEnd();
825  }
826
827  static bool classof(const Stmt *T) {
828    return T->getStmtClass() == CXXThrowExprClass;
829  }
830
831  // Iterators
832  child_range children() {
833    return child_range(&Op, Op ? &Op+1 : &Op);
834  }
835};
836
837/// CXXDefaultArgExpr - C++ [dcl.fct.default]. This wraps up a
838/// function call argument that was created from the corresponding
839/// parameter's default argument, when the call did not explicitly
840/// supply arguments for all of the parameters.
841class CXXDefaultArgExpr : public Expr {
842  /// \brief The parameter whose default is being used.
843  ///
844  /// When the bit is set, the subexpression is stored after the
845  /// CXXDefaultArgExpr itself. When the bit is clear, the parameter's
846  /// actual default expression is the subexpression.
847  llvm::PointerIntPair<ParmVarDecl *, 1, bool> Param;
848
849  /// \brief The location where the default argument expression was used.
850  SourceLocation Loc;
851
852  CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param)
853    : Expr(SC,
854           param->hasUnparsedDefaultArg()
855             ? param->getType().getNonReferenceType()
856             : param->getDefaultArg()->getType(),
857           param->getDefaultArg()->getValueKind(),
858           param->getDefaultArg()->getObjectKind(), false, false, false, false),
859      Param(param, false), Loc(Loc) { }
860
861  CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param,
862                    Expr *SubExpr)
863    : Expr(SC, SubExpr->getType(),
864           SubExpr->getValueKind(), SubExpr->getObjectKind(),
865           false, false, false, false),
866      Param(param, true), Loc(Loc) {
867    *reinterpret_cast<Expr **>(this + 1) = SubExpr;
868  }
869
870public:
871  CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
872
873
874  // Param is the parameter whose default argument is used by this
875  // expression.
876  static CXXDefaultArgExpr *Create(ASTContext &C, SourceLocation Loc,
877                                   ParmVarDecl *Param) {
878    return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param);
879  }
880
881  // Param is the parameter whose default argument is used by this
882  // expression, and SubExpr is the expression that will actually be used.
883  static CXXDefaultArgExpr *Create(ASTContext &C,
884                                   SourceLocation Loc,
885                                   ParmVarDecl *Param,
886                                   Expr *SubExpr);
887
888  // Retrieve the parameter that the argument was created from.
889  const ParmVarDecl *getParam() const { return Param.getPointer(); }
890  ParmVarDecl *getParam() { return Param.getPointer(); }
891
892  // Retrieve the actual argument to the function call.
893  const Expr *getExpr() const {
894    if (Param.getInt())
895      return *reinterpret_cast<Expr const * const*> (this + 1);
896    return getParam()->getDefaultArg();
897  }
898  Expr *getExpr() {
899    if (Param.getInt())
900      return *reinterpret_cast<Expr **> (this + 1);
901    return getParam()->getDefaultArg();
902  }
903
904  /// \brief Retrieve the location where this default argument was actually
905  /// used.
906  SourceLocation getUsedLocation() const { return Loc; }
907
908  // Default argument expressions have no representation in the
909  // source, so they have an empty source range.
910  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
911  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
912
913  SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
914
915  static bool classof(const Stmt *T) {
916    return T->getStmtClass() == CXXDefaultArgExprClass;
917  }
918
919  // Iterators
920  child_range children() { return child_range(); }
921
922  friend class ASTStmtReader;
923  friend class ASTStmtWriter;
924};
925
926/// \brief This wraps a use of a C++ default initializer (technically,
927/// a brace-or-equal-initializer for a non-static data member) when it
928/// is implicitly used in a mem-initializer-list in a constructor
929/// (C++11 [class.base.init]p8) or in aggregate initialization
930/// (C++1y [dcl.init.aggr]p7).
931class CXXDefaultInitExpr : public Expr {
932  /// \brief The field whose default is being used.
933  FieldDecl *Field;
934
935  /// \brief The location where the default initializer expression was used.
936  SourceLocation Loc;
937
938  CXXDefaultInitExpr(ASTContext &C, SourceLocation Loc, FieldDecl *Field,
939                     QualType T);
940
941  CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
942
943public:
944  // Field is the non-static data member whose default initializer is used
945  // by this expression.
946  static CXXDefaultInitExpr *Create(ASTContext &C, SourceLocation Loc,
947                                    FieldDecl *Field) {
948    return new (C) CXXDefaultInitExpr(C, Loc, Field, Field->getType());
949  }
950
951  // Get the field whose initializer will be used.
952  FieldDecl *getField() { return Field; }
953  const FieldDecl *getField() const { return Field; }
954
955  // Get the initialization expression that will be used.
956  const Expr *getExpr() const { return Field->getInClassInitializer(); }
957  Expr *getExpr() { return Field->getInClassInitializer(); }
958
959  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
960  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
961
962  static bool classof(const Stmt *T) {
963    return T->getStmtClass() == CXXDefaultInitExprClass;
964  }
965
966  // Iterators
967  child_range children() { return child_range(); }
968
969  friend class ASTReader;
970  friend class ASTStmtReader;
971};
972
973/// CXXTemporary - Represents a C++ temporary.
974class CXXTemporary {
975  /// Destructor - The destructor that needs to be called.
976  const CXXDestructorDecl *Destructor;
977
978  CXXTemporary(const CXXDestructorDecl *destructor)
979    : Destructor(destructor) { }
980
981public:
982  static CXXTemporary *Create(ASTContext &C,
983                              const CXXDestructorDecl *Destructor);
984
985  const CXXDestructorDecl *getDestructor() const { return Destructor; }
986  void setDestructor(const CXXDestructorDecl *Dtor) {
987    Destructor = Dtor;
988  }
989};
990
991/// \brief Represents binding an expression to a temporary.
992///
993/// This ensures the destructor is called for the temporary. It should only be
994/// needed for non-POD, non-trivially destructable class types. For example:
995///
996/// \code
997///   struct S {
998///     S() { }  // User defined constructor makes S non-POD.
999///     ~S() { } // User defined destructor makes it non-trivial.
1000///   };
1001///   void test() {
1002///     const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1003///   }
1004/// \endcode
1005class CXXBindTemporaryExpr : public Expr {
1006  CXXTemporary *Temp;
1007
1008  Stmt *SubExpr;
1009
1010  CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
1011   : Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
1012          VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
1013          SubExpr->isValueDependent(),
1014          SubExpr->isInstantiationDependent(),
1015          SubExpr->containsUnexpandedParameterPack()),
1016     Temp(temp), SubExpr(SubExpr) { }
1017
1018public:
1019  CXXBindTemporaryExpr(EmptyShell Empty)
1020    : Expr(CXXBindTemporaryExprClass, Empty), Temp(0), SubExpr(0) {}
1021
1022  static CXXBindTemporaryExpr *Create(ASTContext &C, CXXTemporary *Temp,
1023                                      Expr* SubExpr);
1024
1025  CXXTemporary *getTemporary() { return Temp; }
1026  const CXXTemporary *getTemporary() const { return Temp; }
1027  void setTemporary(CXXTemporary *T) { Temp = T; }
1028
1029  const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1030  Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1031  void setSubExpr(Expr *E) { SubExpr = E; }
1032
1033  SourceLocation getLocStart() const LLVM_READONLY {
1034    return SubExpr->getLocStart();
1035  }
1036  SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
1037
1038  // Implement isa/cast/dyncast/etc.
1039  static bool classof(const Stmt *T) {
1040    return T->getStmtClass() == CXXBindTemporaryExprClass;
1041  }
1042
1043  // Iterators
1044  child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1045};
1046
1047/// \brief Represents a call to a C++ constructor.
1048class CXXConstructExpr : public Expr {
1049public:
1050  enum ConstructionKind {
1051    CK_Complete,
1052    CK_NonVirtualBase,
1053    CK_VirtualBase,
1054    CK_Delegating
1055  };
1056
1057private:
1058  CXXConstructorDecl *Constructor;
1059
1060  SourceLocation Loc;
1061  SourceRange ParenRange;
1062  unsigned NumArgs : 16;
1063  bool Elidable : 1;
1064  bool HadMultipleCandidates : 1;
1065  bool ListInitialization : 1;
1066  bool ZeroInitialization : 1;
1067  unsigned ConstructKind : 2;
1068  Stmt **Args;
1069
1070protected:
1071  CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T,
1072                   SourceLocation Loc,
1073                   CXXConstructorDecl *d, bool elidable,
1074                   ArrayRef<Expr *> Args,
1075                   bool HadMultipleCandidates,
1076                   bool ListInitialization,
1077                   bool ZeroInitialization,
1078                   ConstructionKind ConstructKind,
1079                   SourceRange ParenRange);
1080
1081  /// \brief Construct an empty C++ construction expression.
1082  CXXConstructExpr(StmtClass SC, EmptyShell Empty)
1083    : Expr(SC, Empty), Constructor(0), NumArgs(0), Elidable(false),
1084      HadMultipleCandidates(false), ListInitialization(false),
1085      ZeroInitialization(false), ConstructKind(0), Args(0)
1086  { }
1087
1088public:
1089  /// \brief Construct an empty C++ construction expression.
1090  explicit CXXConstructExpr(EmptyShell Empty)
1091    : Expr(CXXConstructExprClass, Empty), Constructor(0),
1092      NumArgs(0), Elidable(false), HadMultipleCandidates(false),
1093      ListInitialization(false), ZeroInitialization(false),
1094      ConstructKind(0), Args(0)
1095  { }
1096
1097  static CXXConstructExpr *Create(ASTContext &C, QualType T,
1098                                  SourceLocation Loc,
1099                                  CXXConstructorDecl *D, bool Elidable,
1100                                  ArrayRef<Expr *> Args,
1101                                  bool HadMultipleCandidates,
1102                                  bool ListInitialization,
1103                                  bool ZeroInitialization,
1104                                  ConstructionKind ConstructKind,
1105                                  SourceRange ParenRange);
1106
1107  CXXConstructorDecl* getConstructor() const { return Constructor; }
1108  void setConstructor(CXXConstructorDecl *C) { Constructor = C; }
1109
1110  SourceLocation getLocation() const { return Loc; }
1111  void setLocation(SourceLocation Loc) { this->Loc = Loc; }
1112
1113  /// \brief Whether this construction is elidable.
1114  bool isElidable() const { return Elidable; }
1115  void setElidable(bool E) { Elidable = E; }
1116
1117  /// \brief Whether the referred constructor was resolved from
1118  /// an overloaded set having size greater than 1.
1119  bool hadMultipleCandidates() const { return HadMultipleCandidates; }
1120  void setHadMultipleCandidates(bool V) { HadMultipleCandidates = V; }
1121
1122  /// \brief Whether this constructor call was written as list-initialization.
1123  bool isListInitialization() const { return ListInitialization; }
1124  void setListInitialization(bool V) { ListInitialization = V; }
1125
1126  /// \brief Whether this construction first requires
1127  /// zero-initialization before the initializer is called.
1128  bool requiresZeroInitialization() const { return ZeroInitialization; }
1129  void setRequiresZeroInitialization(bool ZeroInit) {
1130    ZeroInitialization = ZeroInit;
1131  }
1132
1133  /// \brief Determines whether this constructor is actually constructing
1134  /// a base class (rather than a complete object).
1135  ConstructionKind getConstructionKind() const {
1136    return (ConstructionKind)ConstructKind;
1137  }
1138  void setConstructionKind(ConstructionKind CK) {
1139    ConstructKind = CK;
1140  }
1141
1142  typedef ExprIterator arg_iterator;
1143  typedef ConstExprIterator const_arg_iterator;
1144
1145  arg_iterator arg_begin() { return Args; }
1146  arg_iterator arg_end() { return Args + NumArgs; }
1147  const_arg_iterator arg_begin() const { return Args; }
1148  const_arg_iterator arg_end() const { return Args + NumArgs; }
1149
1150  Expr **getArgs() const { return reinterpret_cast<Expr **>(Args); }
1151  unsigned getNumArgs() const { return NumArgs; }
1152
1153  /// getArg - Return the specified argument.
1154  Expr *getArg(unsigned Arg) {
1155    assert(Arg < NumArgs && "Arg access out of range!");
1156    return cast<Expr>(Args[Arg]);
1157  }
1158  const Expr *getArg(unsigned Arg) const {
1159    assert(Arg < NumArgs && "Arg access out of range!");
1160    return cast<Expr>(Args[Arg]);
1161  }
1162
1163  /// setArg - Set the specified argument.
1164  void setArg(unsigned Arg, Expr *ArgExpr) {
1165    assert(Arg < NumArgs && "Arg access out of range!");
1166    Args[Arg] = ArgExpr;
1167  }
1168
1169  SourceLocation getLocStart() const LLVM_READONLY;
1170  SourceLocation getLocEnd() const LLVM_READONLY;
1171  SourceRange getParenRange() const { return ParenRange; }
1172  void setParenRange(SourceRange Range) { ParenRange = Range; }
1173
1174  static bool classof(const Stmt *T) {
1175    return T->getStmtClass() == CXXConstructExprClass ||
1176      T->getStmtClass() == CXXTemporaryObjectExprClass;
1177  }
1178
1179  // Iterators
1180  child_range children() {
1181    return child_range(&Args[0], &Args[0]+NumArgs);
1182  }
1183
1184  friend class ASTStmtReader;
1185};
1186
1187/// \brief Represents an explicit C++ type conversion that uses "functional"
1188/// notation (C++ [expr.type.conv]).
1189///
1190/// Example:
1191/// @code
1192///   x = int(0.5);
1193/// @endcode
1194class CXXFunctionalCastExpr : public ExplicitCastExpr {
1195  SourceLocation TyBeginLoc;
1196  SourceLocation RParenLoc;
1197
1198  CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1199                        TypeSourceInfo *writtenTy,
1200                        SourceLocation tyBeginLoc, CastKind kind,
1201                        Expr *castExpr, unsigned pathSize,
1202                        SourceLocation rParenLoc)
1203    : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
1204                       castExpr, pathSize, writtenTy),
1205      TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {}
1206
1207  explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
1208    : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) { }
1209
1210public:
1211  static CXXFunctionalCastExpr *Create(ASTContext &Context, QualType T,
1212                                       ExprValueKind VK,
1213                                       TypeSourceInfo *Written,
1214                                       SourceLocation TyBeginLoc,
1215                                       CastKind Kind, Expr *Op,
1216                                       const CXXCastPath *Path,
1217                                       SourceLocation RPLoc);
1218  static CXXFunctionalCastExpr *CreateEmpty(ASTContext &Context,
1219                                            unsigned PathSize);
1220
1221  SourceLocation getTypeBeginLoc() const { return TyBeginLoc; }
1222  void setTypeBeginLoc(SourceLocation L) { TyBeginLoc = L; }
1223  SourceLocation getRParenLoc() const { return RParenLoc; }
1224  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1225
1226  SourceLocation getLocStart() const LLVM_READONLY { return TyBeginLoc; }
1227  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1228
1229  static bool classof(const Stmt *T) {
1230    return T->getStmtClass() == CXXFunctionalCastExprClass;
1231  }
1232};
1233
1234/// @brief Represents a C++ functional cast expression that builds a
1235/// temporary object.
1236///
1237/// This expression type represents a C++ "functional" cast
1238/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1239/// constructor to build a temporary object. With N == 1 arguments the
1240/// functional cast expression will be represented by CXXFunctionalCastExpr.
1241/// Example:
1242/// @code
1243/// struct X { X(int, float); }
1244///
1245/// X create_X() {
1246///   return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1247/// };
1248/// @endcode
1249class CXXTemporaryObjectExpr : public CXXConstructExpr {
1250  TypeSourceInfo *Type;
1251
1252public:
1253  CXXTemporaryObjectExpr(ASTContext &C, CXXConstructorDecl *Cons,
1254                         TypeSourceInfo *Type,
1255                         ArrayRef<Expr *> Args,
1256                         SourceRange parenRange,
1257                         bool HadMultipleCandidates,
1258                         bool ListInitialization,
1259                         bool ZeroInitialization);
1260  explicit CXXTemporaryObjectExpr(EmptyShell Empty)
1261    : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty), Type() { }
1262
1263  TypeSourceInfo *getTypeSourceInfo() const { return Type; }
1264
1265  SourceLocation getLocStart() const LLVM_READONLY;
1266  SourceLocation getLocEnd() const LLVM_READONLY;
1267
1268  static bool classof(const Stmt *T) {
1269    return T->getStmtClass() == CXXTemporaryObjectExprClass;
1270  }
1271
1272  friend class ASTStmtReader;
1273};
1274
1275/// \brief A C++ lambda expression, which produces a function object
1276/// (of unspecified type) that can be invoked later.
1277///
1278/// Example:
1279/// \code
1280/// void low_pass_filter(std::vector<double> &values, double cutoff) {
1281///   values.erase(std::remove_if(values.begin(), values.end(),
1282///                               [=](double value) { return value > cutoff; });
1283/// }
1284/// \endcode
1285///
1286/// C++11 lambda expressions can capture local variables, either by copying
1287/// the values of those local variables at the time the function
1288/// object is constructed (not when it is called!) or by holding a
1289/// reference to the local variable. These captures can occur either
1290/// implicitly or can be written explicitly between the square
1291/// brackets ([...]) that start the lambda expression.
1292///
1293/// C++1y introduces a new form of "capture" called an init-capture that
1294/// includes an initializing expression (rather than capturing a variable),
1295/// and which can never occur implicitly.
1296class LambdaExpr : public Expr {
1297  enum {
1298    /// \brief Flag used by the Capture class to indicate that the given
1299    /// capture was implicit.
1300    Capture_Implicit = 0x01,
1301
1302    /// \brief Flag used by the Capture class to indicate that the
1303    /// given capture was by-copy.
1304    ///
1305    /// This includes the case of a non-reference init-capture.
1306    Capture_ByCopy = 0x02
1307  };
1308
1309  /// \brief The source range that covers the lambda introducer ([...]).
1310  SourceRange IntroducerRange;
1311
1312  /// \brief The number of captures.
1313  unsigned NumCaptures : 16;
1314
1315  /// \brief The default capture kind, which is a value of type
1316  /// LambdaCaptureDefault.
1317  unsigned CaptureDefault : 2;
1318
1319  /// \brief Whether this lambda had an explicit parameter list vs. an
1320  /// implicit (and empty) parameter list.
1321  unsigned ExplicitParams : 1;
1322
1323  /// \brief Whether this lambda had the result type explicitly specified.
1324  unsigned ExplicitResultType : 1;
1325
1326  /// \brief Whether there are any array index variables stored at the end of
1327  /// this lambda expression.
1328  unsigned HasArrayIndexVars : 1;
1329
1330  /// \brief The location of the closing brace ('}') that completes
1331  /// the lambda.
1332  ///
1333  /// The location of the brace is also available by looking up the
1334  /// function call operator in the lambda class. However, it is
1335  /// stored here to improve the performance of getSourceRange(), and
1336  /// to avoid having to deserialize the function call operator from a
1337  /// module file just to determine the source range.
1338  SourceLocation ClosingBrace;
1339
1340  // Note: The capture initializers are stored directly after the lambda
1341  // expression, along with the index variables used to initialize by-copy
1342  // array captures.
1343
1344public:
1345  /// \brief Describes the capture of a variable or of \c this, or of a
1346  /// C++1y init-capture.
1347  class Capture {
1348    llvm::PointerIntPair<Decl *, 2> DeclAndBits;
1349    SourceLocation Loc;
1350    SourceLocation EllipsisLoc;
1351
1352    friend class ASTStmtReader;
1353    friend class ASTStmtWriter;
1354
1355  public:
1356    /// \brief Create a new capture of a variable or of \c this.
1357    ///
1358    /// \param Loc The source location associated with this capture.
1359    ///
1360    /// \param Kind The kind of capture (this, byref, bycopy), which must
1361    /// not be init-capture.
1362    ///
1363    /// \param Implicit Whether the capture was implicit or explicit.
1364    ///
1365    /// \param Var The local variable being captured, or null if capturing
1366    /// \c this.
1367    ///
1368    /// \param EllipsisLoc The location of the ellipsis (...) for a
1369    /// capture that is a pack expansion, or an invalid source
1370    /// location to indicate that this is not a pack expansion.
1371    Capture(SourceLocation Loc, bool Implicit,
1372            LambdaCaptureKind Kind, VarDecl *Var = 0,
1373            SourceLocation EllipsisLoc = SourceLocation());
1374
1375    /// \brief Create a new init-capture.
1376    Capture(FieldDecl *Field);
1377
1378    /// \brief Determine the kind of capture.
1379    LambdaCaptureKind getCaptureKind() const;
1380
1381    /// \brief Determine whether this capture handles the C++ \c this
1382    /// pointer.
1383    bool capturesThis() const { return DeclAndBits.getPointer() == 0; }
1384
1385    /// \brief Determine whether this capture handles a variable.
1386    bool capturesVariable() const {
1387      return dyn_cast_or_null<VarDecl>(DeclAndBits.getPointer());
1388    }
1389
1390    /// \brief Determine whether this is an init-capture.
1391    bool isInitCapture() const { return getCaptureKind() == LCK_Init; }
1392
1393    /// \brief Retrieve the declaration of the local variable being
1394    /// captured.
1395    ///
1396    /// This operation is only valid if this capture is a variable capture
1397    /// (other than a capture of \c this).
1398    VarDecl *getCapturedVar() const {
1399      assert(capturesVariable() && "No variable available for 'this' capture");
1400      return cast<VarDecl>(DeclAndBits.getPointer());
1401    }
1402
1403    /// \brief Retrieve the field for an init-capture.
1404    ///
1405    /// This works only for an init-capture.  To retrieve the FieldDecl for
1406    /// a captured variable or for a capture of \c this, use
1407    /// LambdaExpr::getLambdaClass and CXXRecordDecl::getCaptureFields.
1408    FieldDecl *getInitCaptureField() const {
1409      assert(getCaptureKind() == LCK_Init && "no field for non-init-capture");
1410      return cast<FieldDecl>(DeclAndBits.getPointer());
1411    }
1412
1413    /// \brief Determine whether this was an implicit capture (not
1414    /// written between the square brackets introducing the lambda).
1415    bool isImplicit() const { return DeclAndBits.getInt() & Capture_Implicit; }
1416
1417    /// \brief Determine whether this was an explicit capture (written
1418    /// between the square brackets introducing the lambda).
1419    bool isExplicit() const { return !isImplicit(); }
1420
1421    /// \brief Retrieve the source location of the capture.
1422    ///
1423    /// For an explicit capture, this returns the location of the
1424    /// explicit capture in the source. For an implicit capture, this
1425    /// returns the location at which the variable or \c this was first
1426    /// used.
1427    SourceLocation getLocation() const { return Loc; }
1428
1429    /// \brief Determine whether this capture is a pack expansion,
1430    /// which captures a function parameter pack.
1431    bool isPackExpansion() const { return EllipsisLoc.isValid(); }
1432
1433    /// \brief Retrieve the location of the ellipsis for a capture
1434    /// that is a pack expansion.
1435    SourceLocation getEllipsisLoc() const {
1436      assert(isPackExpansion() && "No ellipsis location for a non-expansion");
1437      return EllipsisLoc;
1438    }
1439  };
1440
1441private:
1442  /// \brief Construct a lambda expression.
1443  LambdaExpr(QualType T, SourceRange IntroducerRange,
1444             LambdaCaptureDefault CaptureDefault,
1445             ArrayRef<Capture> Captures,
1446             bool ExplicitParams,
1447             bool ExplicitResultType,
1448             ArrayRef<Expr *> CaptureInits,
1449             ArrayRef<VarDecl *> ArrayIndexVars,
1450             ArrayRef<unsigned> ArrayIndexStarts,
1451             SourceLocation ClosingBrace,
1452             bool ContainsUnexpandedParameterPack);
1453
1454  /// \brief Construct an empty lambda expression.
1455  LambdaExpr(EmptyShell Empty, unsigned NumCaptures, bool HasArrayIndexVars)
1456    : Expr(LambdaExprClass, Empty),
1457      NumCaptures(NumCaptures), CaptureDefault(LCD_None), ExplicitParams(false),
1458      ExplicitResultType(false), HasArrayIndexVars(true) {
1459    getStoredStmts()[NumCaptures] = 0;
1460  }
1461
1462  Stmt **getStoredStmts() const {
1463    return reinterpret_cast<Stmt **>(const_cast<LambdaExpr *>(this) + 1);
1464  }
1465
1466  /// \brief Retrieve the mapping from captures to the first array index
1467  /// variable.
1468  unsigned *getArrayIndexStarts() const {
1469    return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1);
1470  }
1471
1472  /// \brief Retrieve the complete set of array-index variables.
1473  VarDecl **getArrayIndexVars() const {
1474    unsigned ArrayIndexSize =
1475        llvm::RoundUpToAlignment(sizeof(unsigned) * (NumCaptures + 1),
1476                                 llvm::alignOf<VarDecl*>());
1477    return reinterpret_cast<VarDecl **>(
1478        reinterpret_cast<char*>(getArrayIndexStarts()) + ArrayIndexSize);
1479  }
1480
1481public:
1482  /// \brief Construct a new lambda expression.
1483  static LambdaExpr *Create(ASTContext &C,
1484                            CXXRecordDecl *Class,
1485                            SourceRange IntroducerRange,
1486                            LambdaCaptureDefault CaptureDefault,
1487                            ArrayRef<Capture> Captures,
1488                            bool ExplicitParams,
1489                            bool ExplicitResultType,
1490                            ArrayRef<Expr *> CaptureInits,
1491                            ArrayRef<VarDecl *> ArrayIndexVars,
1492                            ArrayRef<unsigned> ArrayIndexStarts,
1493                            SourceLocation ClosingBrace,
1494                            bool ContainsUnexpandedParameterPack);
1495
1496  /// \brief Construct a new lambda expression that will be deserialized from
1497  /// an external source.
1498  static LambdaExpr *CreateDeserialized(ASTContext &C, unsigned NumCaptures,
1499                                        unsigned NumArrayIndexVars);
1500
1501  /// \brief Determine the default capture kind for this lambda.
1502  LambdaCaptureDefault getCaptureDefault() const {
1503    return static_cast<LambdaCaptureDefault>(CaptureDefault);
1504  }
1505
1506  /// \brief An iterator that walks over the captures of the lambda,
1507  /// both implicit and explicit.
1508  typedef const Capture *capture_iterator;
1509
1510  /// \brief Retrieve an iterator pointing to the first lambda capture.
1511  capture_iterator capture_begin() const;
1512
1513  /// \brief Retrieve an iterator pointing past the end of the
1514  /// sequence of lambda captures.
1515  capture_iterator capture_end() const;
1516
1517  /// \brief Determine the number of captures in this lambda.
1518  unsigned capture_size() const { return NumCaptures; }
1519
1520  /// \brief Retrieve an iterator pointing to the first explicit
1521  /// lambda capture.
1522  capture_iterator explicit_capture_begin() const;
1523
1524  /// \brief Retrieve an iterator pointing past the end of the sequence of
1525  /// explicit lambda captures.
1526  capture_iterator explicit_capture_end() const;
1527
1528  /// \brief Retrieve an iterator pointing to the first implicit
1529  /// lambda capture.
1530  capture_iterator implicit_capture_begin() const;
1531
1532  /// \brief Retrieve an iterator pointing past the end of the sequence of
1533  /// implicit lambda captures.
1534  capture_iterator implicit_capture_end() const;
1535
1536  /// \brief Iterator that walks over the capture initialization
1537  /// arguments.
1538  typedef Expr **capture_init_iterator;
1539
1540  /// \brief Retrieve the first initialization argument for this
1541  /// lambda expression (which initializes the first capture field).
1542  capture_init_iterator capture_init_begin() const {
1543    return reinterpret_cast<Expr **>(getStoredStmts());
1544  }
1545
1546  /// \brief Retrieve the iterator pointing one past the last
1547  /// initialization argument for this lambda expression.
1548  capture_init_iterator capture_init_end() const {
1549    return capture_init_begin() + NumCaptures;
1550  }
1551
1552  /// \brief Retrieve the initializer for an init-capture.
1553  Expr *getInitCaptureInit(capture_iterator Capture) {
1554    assert(Capture >= explicit_capture_begin() &&
1555           Capture <= explicit_capture_end() && Capture->isInitCapture());
1556    return capture_init_begin()[Capture - capture_begin()];
1557  }
1558  const Expr *getInitCaptureInit(capture_iterator Capture) const {
1559    return const_cast<LambdaExpr*>(this)->getInitCaptureInit(Capture);
1560  }
1561
1562  /// \brief Retrieve the set of index variables used in the capture
1563  /// initializer of an array captured by copy.
1564  ///
1565  /// \param Iter The iterator that points at the capture initializer for
1566  /// which we are extracting the corresponding index variables.
1567  ArrayRef<VarDecl *> getCaptureInitIndexVars(capture_init_iterator Iter) const;
1568
1569  /// \brief Retrieve the source range covering the lambda introducer,
1570  /// which contains the explicit capture list surrounded by square
1571  /// brackets ([...]).
1572  SourceRange getIntroducerRange() const { return IntroducerRange; }
1573
1574  /// \brief Retrieve the class that corresponds to the lambda, which
1575  /// stores the captures in its fields and provides the various
1576  /// operations permitted on a lambda (copying, calling).
1577  CXXRecordDecl *getLambdaClass() const;
1578
1579  /// \brief Retrieve the function call operator associated with this
1580  /// lambda expression.
1581  CXXMethodDecl *getCallOperator() const;
1582
1583  /// \brief Retrieve the body of the lambda.
1584  CompoundStmt *getBody() const;
1585
1586  /// \brief Determine whether the lambda is mutable, meaning that any
1587  /// captures values can be modified.
1588  bool isMutable() const;
1589
1590  /// \brief Determine whether this lambda has an explicit parameter
1591  /// list vs. an implicit (empty) parameter list.
1592  bool hasExplicitParameters() const { return ExplicitParams; }
1593
1594  /// \brief Whether this lambda had its result type explicitly specified.
1595  bool hasExplicitResultType() const { return ExplicitResultType; }
1596
1597  static bool classof(const Stmt *T) {
1598    return T->getStmtClass() == LambdaExprClass;
1599  }
1600
1601  SourceLocation getLocStart() const LLVM_READONLY {
1602    return IntroducerRange.getBegin();
1603  }
1604  SourceLocation getLocEnd() const LLVM_READONLY { return ClosingBrace; }
1605
1606  child_range children() {
1607    return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
1608  }
1609
1610  friend class ASTStmtReader;
1611  friend class ASTStmtWriter;
1612};
1613
1614/// CXXScalarValueInitExpr - [C++ 5.2.3p2]
1615/// Expression "T()" which creates a value-initialized rvalue of type
1616/// T, which is a non-class type.
1617///
1618class CXXScalarValueInitExpr : public Expr {
1619  SourceLocation RParenLoc;
1620  TypeSourceInfo *TypeInfo;
1621
1622  friend class ASTStmtReader;
1623
1624public:
1625  /// \brief Create an explicitly-written scalar-value initialization
1626  /// expression.
1627  CXXScalarValueInitExpr(QualType Type,
1628                         TypeSourceInfo *TypeInfo,
1629                         SourceLocation rParenLoc ) :
1630    Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
1631         false, false, Type->isInstantiationDependentType(), false),
1632    RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
1633
1634  explicit CXXScalarValueInitExpr(EmptyShell Shell)
1635    : Expr(CXXScalarValueInitExprClass, Shell) { }
1636
1637  TypeSourceInfo *getTypeSourceInfo() const {
1638    return TypeInfo;
1639  }
1640
1641  SourceLocation getRParenLoc() const { return RParenLoc; }
1642
1643  SourceLocation getLocStart() const LLVM_READONLY;
1644  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1645
1646  static bool classof(const Stmt *T) {
1647    return T->getStmtClass() == CXXScalarValueInitExprClass;
1648  }
1649
1650  // Iterators
1651  child_range children() { return child_range(); }
1652};
1653
1654/// @brief Represents a new-expression for memory allocation and constructor
1655// calls, e.g: "new CXXNewExpr(foo)".
1656class CXXNewExpr : public Expr {
1657  // Contains an optional array size expression, an optional initialization
1658  // expression, and any number of optional placement arguments, in that order.
1659  Stmt **SubExprs;
1660  /// \brief Points to the allocation function used.
1661  FunctionDecl *OperatorNew;
1662  /// \brief Points to the deallocation function used in case of error. May be
1663  /// null.
1664  FunctionDecl *OperatorDelete;
1665
1666  /// \brief The allocated type-source information, as written in the source.
1667  TypeSourceInfo *AllocatedTypeInfo;
1668
1669  /// \brief If the allocated type was expressed as a parenthesized type-id,
1670  /// the source range covering the parenthesized type-id.
1671  SourceRange TypeIdParens;
1672
1673  /// \brief Range of the entire new expression.
1674  SourceRange Range;
1675
1676  /// \brief Source-range of a paren-delimited initializer.
1677  SourceRange DirectInitRange;
1678
1679  // Was the usage ::new, i.e. is the global new to be used?
1680  bool GlobalNew : 1;
1681  // Do we allocate an array? If so, the first SubExpr is the size expression.
1682  bool Array : 1;
1683  // If this is an array allocation, does the usual deallocation
1684  // function for the allocated type want to know the allocated size?
1685  bool UsualArrayDeleteWantsSize : 1;
1686  // The number of placement new arguments.
1687  unsigned NumPlacementArgs : 13;
1688  // What kind of initializer do we have? Could be none, parens, or braces.
1689  // In storage, we distinguish between "none, and no initializer expr", and
1690  // "none, but an implicit initializer expr".
1691  unsigned StoredInitializationStyle : 2;
1692
1693  friend class ASTStmtReader;
1694  friend class ASTStmtWriter;
1695public:
1696  enum InitializationStyle {
1697    NoInit,   ///< New-expression has no initializer as written.
1698    CallInit, ///< New-expression has a C++98 paren-delimited initializer.
1699    ListInit  ///< New-expression has a C++11 list-initializer.
1700  };
1701
1702  CXXNewExpr(ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
1703             FunctionDecl *operatorDelete, bool usualArrayDeleteWantsSize,
1704             ArrayRef<Expr*> placementArgs,
1705             SourceRange typeIdParens, Expr *arraySize,
1706             InitializationStyle initializationStyle, Expr *initializer,
1707             QualType ty, TypeSourceInfo *AllocatedTypeInfo,
1708             SourceRange Range, SourceRange directInitRange);
1709  explicit CXXNewExpr(EmptyShell Shell)
1710    : Expr(CXXNewExprClass, Shell), SubExprs(0) { }
1711
1712  void AllocateArgsArray(ASTContext &C, bool isArray, unsigned numPlaceArgs,
1713                         bool hasInitializer);
1714
1715  QualType getAllocatedType() const {
1716    assert(getType()->isPointerType());
1717    return getType()->getAs<PointerType>()->getPointeeType();
1718  }
1719
1720  TypeSourceInfo *getAllocatedTypeSourceInfo() const {
1721    return AllocatedTypeInfo;
1722  }
1723
1724  /// \brief True if the allocation result needs to be null-checked.
1725  /// C++0x [expr.new]p13:
1726  ///   If the allocation function returns null, initialization shall
1727  ///   not be done, the deallocation function shall not be called,
1728  ///   and the value of the new-expression shall be null.
1729  /// An allocation function is not allowed to return null unless it
1730  /// has a non-throwing exception-specification.  The '03 rule is
1731  /// identical except that the definition of a non-throwing
1732  /// exception specification is just "is it throw()?".
1733  bool shouldNullCheckAllocation(ASTContext &Ctx) const;
1734
1735  FunctionDecl *getOperatorNew() const { return OperatorNew; }
1736  void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
1737  FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
1738  void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
1739
1740  bool isArray() const { return Array; }
1741  Expr *getArraySize() {
1742    return Array ? cast<Expr>(SubExprs[0]) : 0;
1743  }
1744  const Expr *getArraySize() const {
1745    return Array ? cast<Expr>(SubExprs[0]) : 0;
1746  }
1747
1748  unsigned getNumPlacementArgs() const { return NumPlacementArgs; }
1749  Expr **getPlacementArgs() {
1750    return reinterpret_cast<Expr **>(SubExprs + Array + hasInitializer());
1751  }
1752
1753  Expr *getPlacementArg(unsigned i) {
1754    assert(i < NumPlacementArgs && "Index out of range");
1755    return getPlacementArgs()[i];
1756  }
1757  const Expr *getPlacementArg(unsigned i) const {
1758    assert(i < NumPlacementArgs && "Index out of range");
1759    return const_cast<CXXNewExpr*>(this)->getPlacementArg(i);
1760  }
1761
1762  bool isParenTypeId() const { return TypeIdParens.isValid(); }
1763  SourceRange getTypeIdParens() const { return TypeIdParens; }
1764
1765  bool isGlobalNew() const { return GlobalNew; }
1766
1767  /// \brief Whether this new-expression has any initializer at all.
1768  bool hasInitializer() const { return StoredInitializationStyle > 0; }
1769
1770  /// \brief The kind of initializer this new-expression has.
1771  InitializationStyle getInitializationStyle() const {
1772    if (StoredInitializationStyle == 0)
1773      return NoInit;
1774    return static_cast<InitializationStyle>(StoredInitializationStyle-1);
1775  }
1776
1777  /// \brief The initializer of this new-expression.
1778  Expr *getInitializer() {
1779    return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
1780  }
1781  const Expr *getInitializer() const {
1782    return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
1783  }
1784
1785  /// \brief Returns the CXXConstructExpr from this new-expression, or NULL.
1786  const CXXConstructExpr* getConstructExpr() const {
1787    return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
1788  }
1789
1790  /// Answers whether the usual array deallocation function for the
1791  /// allocated type expects the size of the allocation as a
1792  /// parameter.
1793  bool doesUsualArrayDeleteWantSize() const {
1794    return UsualArrayDeleteWantsSize;
1795  }
1796
1797  typedef ExprIterator arg_iterator;
1798  typedef ConstExprIterator const_arg_iterator;
1799
1800  arg_iterator placement_arg_begin() {
1801    return SubExprs + Array + hasInitializer();
1802  }
1803  arg_iterator placement_arg_end() {
1804    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1805  }
1806  const_arg_iterator placement_arg_begin() const {
1807    return SubExprs + Array + hasInitializer();
1808  }
1809  const_arg_iterator placement_arg_end() const {
1810    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1811  }
1812
1813  typedef Stmt **raw_arg_iterator;
1814  raw_arg_iterator raw_arg_begin() { return SubExprs; }
1815  raw_arg_iterator raw_arg_end() {
1816    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1817  }
1818  const_arg_iterator raw_arg_begin() const { return SubExprs; }
1819  const_arg_iterator raw_arg_end() const {
1820    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1821  }
1822
1823  SourceLocation getStartLoc() const { return Range.getBegin(); }
1824  SourceLocation getEndLoc() const { return Range.getEnd(); }
1825
1826  SourceRange getDirectInitRange() const { return DirectInitRange; }
1827
1828  SourceRange getSourceRange() const LLVM_READONLY {
1829    return Range;
1830  }
1831  SourceLocation getLocStart() const LLVM_READONLY { return getStartLoc(); }
1832  SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1833
1834  static bool classof(const Stmt *T) {
1835    return T->getStmtClass() == CXXNewExprClass;
1836  }
1837
1838  // Iterators
1839  child_range children() {
1840    return child_range(raw_arg_begin(), raw_arg_end());
1841  }
1842};
1843
1844/// \brief Represents a \c delete expression for memory deallocation and
1845/// destructor calls, e.g. "delete[] pArray".
1846class CXXDeleteExpr : public Expr {
1847  // Points to the operator delete overload that is used. Could be a member.
1848  FunctionDecl *OperatorDelete;
1849  // The pointer expression to be deleted.
1850  Stmt *Argument;
1851  // Location of the expression.
1852  SourceLocation Loc;
1853  // Is this a forced global delete, i.e. "::delete"?
1854  bool GlobalDelete : 1;
1855  // Is this the array form of delete, i.e. "delete[]"?
1856  bool ArrayForm : 1;
1857  // ArrayFormAsWritten can be different from ArrayForm if 'delete' is applied
1858  // to pointer-to-array type (ArrayFormAsWritten will be false while ArrayForm
1859  // will be true).
1860  bool ArrayFormAsWritten : 1;
1861  // Does the usual deallocation function for the element type require
1862  // a size_t argument?
1863  bool UsualArrayDeleteWantsSize : 1;
1864public:
1865  CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm,
1866                bool arrayFormAsWritten, bool usualArrayDeleteWantsSize,
1867                FunctionDecl *operatorDelete, Expr *arg, SourceLocation loc)
1868    : Expr(CXXDeleteExprClass, ty, VK_RValue, OK_Ordinary, false, false,
1869           arg->isInstantiationDependent(),
1870           arg->containsUnexpandedParameterPack()),
1871      OperatorDelete(operatorDelete), Argument(arg), Loc(loc),
1872      GlobalDelete(globalDelete),
1873      ArrayForm(arrayForm), ArrayFormAsWritten(arrayFormAsWritten),
1874      UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) { }
1875  explicit CXXDeleteExpr(EmptyShell Shell)
1876    : Expr(CXXDeleteExprClass, Shell), OperatorDelete(0), Argument(0) { }
1877
1878  bool isGlobalDelete() const { return GlobalDelete; }
1879  bool isArrayForm() const { return ArrayForm; }
1880  bool isArrayFormAsWritten() const { return ArrayFormAsWritten; }
1881
1882  /// Answers whether the usual array deallocation function for the
1883  /// allocated type expects the size of the allocation as a
1884  /// parameter.  This can be true even if the actual deallocation
1885  /// function that we're using doesn't want a size.
1886  bool doesUsualArrayDeleteWantSize() const {
1887    return UsualArrayDeleteWantsSize;
1888  }
1889
1890  FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
1891
1892  Expr *getArgument() { return cast<Expr>(Argument); }
1893  const Expr *getArgument() const { return cast<Expr>(Argument); }
1894
1895  /// \brief Retrieve the type being destroyed.  If the type being
1896  /// destroyed is a dependent type which may or may not be a pointer,
1897  /// return an invalid type.
1898  QualType getDestroyedType() const;
1899
1900  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1901  SourceLocation getLocEnd() const LLVM_READONLY {return Argument->getLocEnd();}
1902
1903  static bool classof(const Stmt *T) {
1904    return T->getStmtClass() == CXXDeleteExprClass;
1905  }
1906
1907  // Iterators
1908  child_range children() { return child_range(&Argument, &Argument+1); }
1909
1910  friend class ASTStmtReader;
1911};
1912
1913/// \brief Stores the type being destroyed by a pseudo-destructor expression.
1914class PseudoDestructorTypeStorage {
1915  /// \brief Either the type source information or the name of the type, if
1916  /// it couldn't be resolved due to type-dependence.
1917  llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
1918
1919  /// \brief The starting source location of the pseudo-destructor type.
1920  SourceLocation Location;
1921
1922public:
1923  PseudoDestructorTypeStorage() { }
1924
1925  PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
1926    : Type(II), Location(Loc) { }
1927
1928  PseudoDestructorTypeStorage(TypeSourceInfo *Info);
1929
1930  TypeSourceInfo *getTypeSourceInfo() const {
1931    return Type.dyn_cast<TypeSourceInfo *>();
1932  }
1933
1934  IdentifierInfo *getIdentifier() const {
1935    return Type.dyn_cast<IdentifierInfo *>();
1936  }
1937
1938  SourceLocation getLocation() const { return Location; }
1939};
1940
1941/// \brief Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
1942///
1943/// A pseudo-destructor is an expression that looks like a member access to a
1944/// destructor of a scalar type, except that scalar types don't have
1945/// destructors. For example:
1946///
1947/// \code
1948/// typedef int T;
1949/// void f(int *p) {
1950///   p->T::~T();
1951/// }
1952/// \endcode
1953///
1954/// Pseudo-destructors typically occur when instantiating templates such as:
1955///
1956/// \code
1957/// template<typename T>
1958/// void destroy(T* ptr) {
1959///   ptr->T::~T();
1960/// }
1961/// \endcode
1962///
1963/// for scalar types. A pseudo-destructor expression has no run-time semantics
1964/// beyond evaluating the base expression.
1965class CXXPseudoDestructorExpr : public Expr {
1966  /// \brief The base expression (that is being destroyed).
1967  Stmt *Base;
1968
1969  /// \brief Whether the operator was an arrow ('->'); otherwise, it was a
1970  /// period ('.').
1971  bool IsArrow : 1;
1972
1973  /// \brief The location of the '.' or '->' operator.
1974  SourceLocation OperatorLoc;
1975
1976  /// \brief The nested-name-specifier that follows the operator, if present.
1977  NestedNameSpecifierLoc QualifierLoc;
1978
1979  /// \brief The type that precedes the '::' in a qualified pseudo-destructor
1980  /// expression.
1981  TypeSourceInfo *ScopeType;
1982
1983  /// \brief The location of the '::' in a qualified pseudo-destructor
1984  /// expression.
1985  SourceLocation ColonColonLoc;
1986
1987  /// \brief The location of the '~'.
1988  SourceLocation TildeLoc;
1989
1990  /// \brief The type being destroyed, or its name if we were unable to
1991  /// resolve the name.
1992  PseudoDestructorTypeStorage DestroyedType;
1993
1994  friend class ASTStmtReader;
1995
1996public:
1997  CXXPseudoDestructorExpr(ASTContext &Context,
1998                          Expr *Base, bool isArrow, SourceLocation OperatorLoc,
1999                          NestedNameSpecifierLoc QualifierLoc,
2000                          TypeSourceInfo *ScopeType,
2001                          SourceLocation ColonColonLoc,
2002                          SourceLocation TildeLoc,
2003                          PseudoDestructorTypeStorage DestroyedType);
2004
2005  explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2006    : Expr(CXXPseudoDestructorExprClass, Shell),
2007      Base(0), IsArrow(false), QualifierLoc(), ScopeType(0) { }
2008
2009  Expr *getBase() const { return cast<Expr>(Base); }
2010
2011  /// \brief Determines whether this member expression actually had
2012  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2013  /// x->Base::foo.
2014  bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2015
2016  /// \brief Retrieves the nested-name-specifier that qualifies the type name,
2017  /// with source-location information.
2018  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2019
2020  /// \brief If the member name was qualified, retrieves the
2021  /// nested-name-specifier that precedes the member name. Otherwise, returns
2022  /// NULL.
2023  NestedNameSpecifier *getQualifier() const {
2024    return QualifierLoc.getNestedNameSpecifier();
2025  }
2026
2027  /// \brief Determine whether this pseudo-destructor expression was written
2028  /// using an '->' (otherwise, it used a '.').
2029  bool isArrow() const { return IsArrow; }
2030
2031  /// \brief Retrieve the location of the '.' or '->' operator.
2032  SourceLocation getOperatorLoc() const { return OperatorLoc; }
2033
2034  /// \brief Retrieve the scope type in a qualified pseudo-destructor
2035  /// expression.
2036  ///
2037  /// Pseudo-destructor expressions can have extra qualification within them
2038  /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2039  /// Here, if the object type of the expression is (or may be) a scalar type,
2040  /// \p T may also be a scalar type and, therefore, cannot be part of a
2041  /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2042  /// destructor expression.
2043  TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2044
2045  /// \brief Retrieve the location of the '::' in a qualified pseudo-destructor
2046  /// expression.
2047  SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2048
2049  /// \brief Retrieve the location of the '~'.
2050  SourceLocation getTildeLoc() const { return TildeLoc; }
2051
2052  /// \brief Retrieve the source location information for the type
2053  /// being destroyed.
2054  ///
2055  /// This type-source information is available for non-dependent
2056  /// pseudo-destructor expressions and some dependent pseudo-destructor
2057  /// expressions. Returns NULL if we only have the identifier for a
2058  /// dependent pseudo-destructor expression.
2059  TypeSourceInfo *getDestroyedTypeInfo() const {
2060    return DestroyedType.getTypeSourceInfo();
2061  }
2062
2063  /// \brief In a dependent pseudo-destructor expression for which we do not
2064  /// have full type information on the destroyed type, provides the name
2065  /// of the destroyed type.
2066  IdentifierInfo *getDestroyedTypeIdentifier() const {
2067    return DestroyedType.getIdentifier();
2068  }
2069
2070  /// \brief Retrieve the type being destroyed.
2071  QualType getDestroyedType() const;
2072
2073  /// \brief Retrieve the starting location of the type being destroyed.
2074  SourceLocation getDestroyedTypeLoc() const {
2075    return DestroyedType.getLocation();
2076  }
2077
2078  /// \brief Set the name of destroyed type for a dependent pseudo-destructor
2079  /// expression.
2080  void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2081    DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2082  }
2083
2084  /// \brief Set the destroyed type.
2085  void setDestroyedType(TypeSourceInfo *Info) {
2086    DestroyedType = PseudoDestructorTypeStorage(Info);
2087  }
2088
2089  SourceLocation getLocStart() const LLVM_READONLY {return Base->getLocStart();}
2090  SourceLocation getLocEnd() const LLVM_READONLY;
2091
2092  static bool classof(const Stmt *T) {
2093    return T->getStmtClass() == CXXPseudoDestructorExprClass;
2094  }
2095
2096  // Iterators
2097  child_range children() { return child_range(&Base, &Base + 1); }
2098};
2099
2100/// \brief Represents a GCC or MS unary type trait, as used in the
2101/// implementation of TR1/C++11 type trait templates.
2102///
2103/// Example:
2104/// @code
2105///   __is_pod(int) == true
2106///   __is_enum(std::string) == false
2107/// @endcode
2108class UnaryTypeTraitExpr : public Expr {
2109  /// UTT - The trait. A UnaryTypeTrait enum in MSVC compat unsigned.
2110  unsigned UTT : 31;
2111  /// The value of the type trait. Unspecified if dependent.
2112  bool Value : 1;
2113
2114  /// Loc - The location of the type trait keyword.
2115  SourceLocation Loc;
2116
2117  /// RParen - The location of the closing paren.
2118  SourceLocation RParen;
2119
2120  /// The type being queried.
2121  TypeSourceInfo *QueriedType;
2122
2123public:
2124  UnaryTypeTraitExpr(SourceLocation loc, UnaryTypeTrait utt,
2125                     TypeSourceInfo *queried, bool value,
2126                     SourceLocation rparen, QualType ty)
2127    : Expr(UnaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2128           false,  queried->getType()->isDependentType(),
2129           queried->getType()->isInstantiationDependentType(),
2130           queried->getType()->containsUnexpandedParameterPack()),
2131      UTT(utt), Value(value), Loc(loc), RParen(rparen), QueriedType(queried) { }
2132
2133  explicit UnaryTypeTraitExpr(EmptyShell Empty)
2134    : Expr(UnaryTypeTraitExprClass, Empty), UTT(0), Value(false),
2135      QueriedType() { }
2136
2137  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2138  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2139
2140  UnaryTypeTrait getTrait() const { return static_cast<UnaryTypeTrait>(UTT); }
2141
2142  QualType getQueriedType() const { return QueriedType->getType(); }
2143
2144  TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2145
2146  bool getValue() const { return Value; }
2147
2148  static bool classof(const Stmt *T) {
2149    return T->getStmtClass() == UnaryTypeTraitExprClass;
2150  }
2151
2152  // Iterators
2153  child_range children() { return child_range(); }
2154
2155  friend class ASTStmtReader;
2156};
2157
2158/// \brief Represents a GCC or MS binary type trait, as used in the
2159/// implementation of TR1/C++11 type trait templates.
2160///
2161/// Example:
2162/// @code
2163///   __is_base_of(Base, Derived) == true
2164/// @endcode
2165class BinaryTypeTraitExpr : public Expr {
2166  /// BTT - The trait. A BinaryTypeTrait enum in MSVC compat unsigned.
2167  unsigned BTT : 8;
2168
2169  /// The value of the type trait. Unspecified if dependent.
2170  bool Value : 1;
2171
2172  /// Loc - The location of the type trait keyword.
2173  SourceLocation Loc;
2174
2175  /// RParen - The location of the closing paren.
2176  SourceLocation RParen;
2177
2178  /// The lhs type being queried.
2179  TypeSourceInfo *LhsType;
2180
2181  /// The rhs type being queried.
2182  TypeSourceInfo *RhsType;
2183
2184public:
2185  BinaryTypeTraitExpr(SourceLocation loc, BinaryTypeTrait btt,
2186                     TypeSourceInfo *lhsType, TypeSourceInfo *rhsType,
2187                     bool value, SourceLocation rparen, QualType ty)
2188    : Expr(BinaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary, false,
2189           lhsType->getType()->isDependentType() ||
2190           rhsType->getType()->isDependentType(),
2191           (lhsType->getType()->isInstantiationDependentType() ||
2192            rhsType->getType()->isInstantiationDependentType()),
2193           (lhsType->getType()->containsUnexpandedParameterPack() ||
2194            rhsType->getType()->containsUnexpandedParameterPack())),
2195      BTT(btt), Value(value), Loc(loc), RParen(rparen),
2196      LhsType(lhsType), RhsType(rhsType) { }
2197
2198
2199  explicit BinaryTypeTraitExpr(EmptyShell Empty)
2200    : Expr(BinaryTypeTraitExprClass, Empty), BTT(0), Value(false),
2201      LhsType(), RhsType() { }
2202
2203  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2204  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2205
2206  BinaryTypeTrait getTrait() const {
2207    return static_cast<BinaryTypeTrait>(BTT);
2208  }
2209
2210  QualType getLhsType() const { return LhsType->getType(); }
2211  QualType getRhsType() const { return RhsType->getType(); }
2212
2213  TypeSourceInfo *getLhsTypeSourceInfo() const { return LhsType; }
2214  TypeSourceInfo *getRhsTypeSourceInfo() const { return RhsType; }
2215
2216  bool getValue() const { assert(!isTypeDependent()); return Value; }
2217
2218  static bool classof(const Stmt *T) {
2219    return T->getStmtClass() == BinaryTypeTraitExprClass;
2220  }
2221
2222  // Iterators
2223  child_range children() { return child_range(); }
2224
2225  friend class ASTStmtReader;
2226};
2227
2228/// \brief A type trait used in the implementation of various C++11 and
2229/// Library TR1 trait templates.
2230///
2231/// \code
2232///   __is_trivially_constructible(vector<int>, int*, int*)
2233/// \endcode
2234class TypeTraitExpr : public Expr {
2235  /// \brief The location of the type trait keyword.
2236  SourceLocation Loc;
2237
2238  /// \brief  The location of the closing parenthesis.
2239  SourceLocation RParenLoc;
2240
2241  // Note: The TypeSourceInfos for the arguments are allocated after the
2242  // TypeTraitExpr.
2243
2244  TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2245                ArrayRef<TypeSourceInfo *> Args,
2246                SourceLocation RParenLoc,
2247                bool Value);
2248
2249  TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) { }
2250
2251  /// \brief Retrieve the argument types.
2252  TypeSourceInfo **getTypeSourceInfos() {
2253    return reinterpret_cast<TypeSourceInfo **>(this+1);
2254  }
2255
2256  /// \brief Retrieve the argument types.
2257  TypeSourceInfo * const *getTypeSourceInfos() const {
2258    return reinterpret_cast<TypeSourceInfo * const*>(this+1);
2259  }
2260
2261public:
2262  /// \brief Create a new type trait expression.
2263  static TypeTraitExpr *Create(ASTContext &C, QualType T, SourceLocation Loc,
2264                               TypeTrait Kind,
2265                               ArrayRef<TypeSourceInfo *> Args,
2266                               SourceLocation RParenLoc,
2267                               bool Value);
2268
2269  static TypeTraitExpr *CreateDeserialized(ASTContext &C, unsigned NumArgs);
2270
2271  /// \brief Determine which type trait this expression uses.
2272  TypeTrait getTrait() const {
2273    return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2274  }
2275
2276  bool getValue() const {
2277    assert(!isValueDependent());
2278    return TypeTraitExprBits.Value;
2279  }
2280
2281  /// \brief Determine the number of arguments to this type trait.
2282  unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2283
2284  /// \brief Retrieve the Ith argument.
2285  TypeSourceInfo *getArg(unsigned I) const {
2286    assert(I < getNumArgs() && "Argument out-of-range");
2287    return getArgs()[I];
2288  }
2289
2290  /// \brief Retrieve the argument types.
2291  ArrayRef<TypeSourceInfo *> getArgs() const {
2292    return ArrayRef<TypeSourceInfo *>(getTypeSourceInfos(), getNumArgs());
2293  }
2294
2295  typedef TypeSourceInfo **arg_iterator;
2296  arg_iterator arg_begin() {
2297    return getTypeSourceInfos();
2298  }
2299  arg_iterator arg_end() {
2300    return getTypeSourceInfos() + getNumArgs();
2301  }
2302
2303  typedef TypeSourceInfo const * const *arg_const_iterator;
2304  arg_const_iterator arg_begin() const { return getTypeSourceInfos(); }
2305  arg_const_iterator arg_end() const {
2306    return getTypeSourceInfos() + getNumArgs();
2307  }
2308
2309  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2310  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2311
2312  static bool classof(const Stmt *T) {
2313    return T->getStmtClass() == TypeTraitExprClass;
2314  }
2315
2316  // Iterators
2317  child_range children() { return child_range(); }
2318
2319  friend class ASTStmtReader;
2320  friend class ASTStmtWriter;
2321
2322};
2323
2324/// \brief An Embarcadero array type trait, as used in the implementation of
2325/// __array_rank and __array_extent.
2326///
2327/// Example:
2328/// @code
2329///   __array_rank(int[10][20]) == 2
2330///   __array_extent(int, 1)    == 20
2331/// @endcode
2332class ArrayTypeTraitExpr : public Expr {
2333  virtual void anchor();
2334
2335  /// \brief The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2336  unsigned ATT : 2;
2337
2338  /// \brief The value of the type trait. Unspecified if dependent.
2339  uint64_t Value;
2340
2341  /// \brief The array dimension being queried, or -1 if not used.
2342  Expr *Dimension;
2343
2344  /// \brief The location of the type trait keyword.
2345  SourceLocation Loc;
2346
2347  /// \brief The location of the closing paren.
2348  SourceLocation RParen;
2349
2350  /// \brief The type being queried.
2351  TypeSourceInfo *QueriedType;
2352
2353public:
2354  ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2355                     TypeSourceInfo *queried, uint64_t value,
2356                     Expr *dimension, SourceLocation rparen, QualType ty)
2357    : Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2358           false, queried->getType()->isDependentType(),
2359           (queried->getType()->isInstantiationDependentType() ||
2360            (dimension && dimension->isInstantiationDependent())),
2361           queried->getType()->containsUnexpandedParameterPack()),
2362      ATT(att), Value(value), Dimension(dimension),
2363      Loc(loc), RParen(rparen), QueriedType(queried) { }
2364
2365
2366  explicit ArrayTypeTraitExpr(EmptyShell Empty)
2367    : Expr(ArrayTypeTraitExprClass, Empty), ATT(0), Value(false),
2368      QueriedType() { }
2369
2370  virtual ~ArrayTypeTraitExpr() { }
2371
2372  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2373  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2374
2375  ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2376
2377  QualType getQueriedType() const { return QueriedType->getType(); }
2378
2379  TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2380
2381  uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
2382
2383  Expr *getDimensionExpression() const { return Dimension; }
2384
2385  static bool classof(const Stmt *T) {
2386    return T->getStmtClass() == ArrayTypeTraitExprClass;
2387  }
2388
2389  // Iterators
2390  child_range children() { return child_range(); }
2391
2392  friend class ASTStmtReader;
2393};
2394
2395/// \brief An expression trait intrinsic.
2396///
2397/// Example:
2398/// @code
2399///   __is_lvalue_expr(std::cout) == true
2400///   __is_lvalue_expr(1) == false
2401/// @endcode
2402class ExpressionTraitExpr : public Expr {
2403  /// \brief The trait. A ExpressionTrait enum in MSVC compat unsigned.
2404  unsigned ET : 31;
2405  /// \brief The value of the type trait. Unspecified if dependent.
2406  bool Value : 1;
2407
2408  /// \brief The location of the type trait keyword.
2409  SourceLocation Loc;
2410
2411  /// \brief The location of the closing paren.
2412  SourceLocation RParen;
2413
2414  /// \brief The expression being queried.
2415  Expr* QueriedExpression;
2416public:
2417  ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
2418                     Expr *queried, bool value,
2419                     SourceLocation rparen, QualType resultType)
2420    : Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2421           false, // Not type-dependent
2422           // Value-dependent if the argument is type-dependent.
2423           queried->isTypeDependent(),
2424           queried->isInstantiationDependent(),
2425           queried->containsUnexpandedParameterPack()),
2426      ET(et), Value(value), Loc(loc), RParen(rparen),
2427      QueriedExpression(queried) { }
2428
2429  explicit ExpressionTraitExpr(EmptyShell Empty)
2430    : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false),
2431      QueriedExpression() { }
2432
2433  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2434  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2435
2436  ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2437
2438  Expr *getQueriedExpression() const { return QueriedExpression; }
2439
2440  bool getValue() const { return Value; }
2441
2442  static bool classof(const Stmt *T) {
2443    return T->getStmtClass() == ExpressionTraitExprClass;
2444  }
2445
2446  // Iterators
2447  child_range children() { return child_range(); }
2448
2449  friend class ASTStmtReader;
2450};
2451
2452
2453/// \brief A reference to an overloaded function set, either an
2454/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2455class OverloadExpr : public Expr {
2456  /// \brief The common name of these declarations.
2457  DeclarationNameInfo NameInfo;
2458
2459  /// \brief The nested-name-specifier that qualifies the name, if any.
2460  NestedNameSpecifierLoc QualifierLoc;
2461
2462  /// The results.  These are undesugared, which is to say, they may
2463  /// include UsingShadowDecls.  Access is relative to the naming
2464  /// class.
2465  // FIXME: Allocate this data after the OverloadExpr subclass.
2466  DeclAccessPair *Results;
2467  unsigned NumResults;
2468
2469protected:
2470  /// \brief Whether the name includes info for explicit template
2471  /// keyword and arguments.
2472  bool HasTemplateKWAndArgsInfo;
2473
2474  /// \brief Return the optional template keyword and arguments info.
2475  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo(); // defined far below.
2476
2477  /// \brief Return the optional template keyword and arguments info.
2478  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2479    return const_cast<OverloadExpr*>(this)->getTemplateKWAndArgsInfo();
2480  }
2481
2482  OverloadExpr(StmtClass K, ASTContext &C,
2483               NestedNameSpecifierLoc QualifierLoc,
2484               SourceLocation TemplateKWLoc,
2485               const DeclarationNameInfo &NameInfo,
2486               const TemplateArgumentListInfo *TemplateArgs,
2487               UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2488               bool KnownDependent,
2489               bool KnownInstantiationDependent,
2490               bool KnownContainsUnexpandedParameterPack);
2491
2492  OverloadExpr(StmtClass K, EmptyShell Empty)
2493    : Expr(K, Empty), QualifierLoc(), Results(0), NumResults(0),
2494      HasTemplateKWAndArgsInfo(false) { }
2495
2496  void initializeResults(ASTContext &C,
2497                         UnresolvedSetIterator Begin,
2498                         UnresolvedSetIterator End);
2499
2500public:
2501  struct FindResult {
2502    OverloadExpr *Expression;
2503    bool IsAddressOfOperand;
2504    bool HasFormOfMemberPointer;
2505  };
2506
2507  /// Finds the overloaded expression in the given expression of
2508  /// OverloadTy.
2509  ///
2510  /// \return the expression (which must be there) and true if it has
2511  /// the particular form of a member pointer expression
2512  static FindResult find(Expr *E) {
2513    assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
2514
2515    FindResult Result;
2516
2517    E = E->IgnoreParens();
2518    if (isa<UnaryOperator>(E)) {
2519      assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
2520      E = cast<UnaryOperator>(E)->getSubExpr();
2521      OverloadExpr *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2522
2523      Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2524      Result.IsAddressOfOperand = true;
2525      Result.Expression = Ovl;
2526    } else {
2527      Result.HasFormOfMemberPointer = false;
2528      Result.IsAddressOfOperand = false;
2529      Result.Expression = cast<OverloadExpr>(E);
2530    }
2531
2532    return Result;
2533  }
2534
2535  /// \brief Gets the naming class of this lookup, if any.
2536  CXXRecordDecl *getNamingClass() const;
2537
2538  typedef UnresolvedSetImpl::iterator decls_iterator;
2539  decls_iterator decls_begin() const { return UnresolvedSetIterator(Results); }
2540  decls_iterator decls_end() const {
2541    return UnresolvedSetIterator(Results + NumResults);
2542  }
2543
2544  /// \brief Gets the number of declarations in the unresolved set.
2545  unsigned getNumDecls() const { return NumResults; }
2546
2547  /// \brief Gets the full name info.
2548  const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2549
2550  /// \brief Gets the name looked up.
2551  DeclarationName getName() const { return NameInfo.getName(); }
2552
2553  /// \brief Gets the location of the name.
2554  SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
2555
2556  /// \brief Fetches the nested-name qualifier, if one was given.
2557  NestedNameSpecifier *getQualifier() const {
2558    return QualifierLoc.getNestedNameSpecifier();
2559  }
2560
2561  /// \brief Fetches the nested-name qualifier with source-location
2562  /// information, if one was given.
2563  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2564
2565  /// \brief Retrieve the location of the template keyword preceding
2566  /// this name, if any.
2567  SourceLocation getTemplateKeywordLoc() const {
2568    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2569    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2570  }
2571
2572  /// \brief Retrieve the location of the left angle bracket starting the
2573  /// explicit template argument list following the name, if any.
2574  SourceLocation getLAngleLoc() const {
2575    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2576    return getTemplateKWAndArgsInfo()->LAngleLoc;
2577  }
2578
2579  /// \brief Retrieve the location of the right angle bracket ending the
2580  /// explicit template argument list following the name, if any.
2581  SourceLocation getRAngleLoc() const {
2582    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2583    return getTemplateKWAndArgsInfo()->RAngleLoc;
2584  }
2585
2586  /// \brief Determines whether the name was preceded by the template keyword.
2587  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2588
2589  /// \brief Determines whether this expression had explicit template arguments.
2590  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2591
2592  // Note that, inconsistently with the explicit-template-argument AST
2593  // nodes, users are *forbidden* from calling these methods on objects
2594  // without explicit template arguments.
2595
2596  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2597    assert(hasExplicitTemplateArgs());
2598    return *getTemplateKWAndArgsInfo();
2599  }
2600
2601  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2602    return const_cast<OverloadExpr*>(this)->getExplicitTemplateArgs();
2603  }
2604
2605  TemplateArgumentLoc const *getTemplateArgs() const {
2606    return getExplicitTemplateArgs().getTemplateArgs();
2607  }
2608
2609  unsigned getNumTemplateArgs() const {
2610    return getExplicitTemplateArgs().NumTemplateArgs;
2611  }
2612
2613  /// \brief Copies the template arguments into the given structure.
2614  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2615    getExplicitTemplateArgs().copyInto(List);
2616  }
2617
2618  /// \brief Retrieves the optional explicit template arguments.
2619  ///
2620  /// This points to the same data as getExplicitTemplateArgs(), but
2621  /// returns null if there are no explicit template arguments.
2622  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2623    if (!hasExplicitTemplateArgs()) return 0;
2624    return &getExplicitTemplateArgs();
2625  }
2626
2627  static bool classof(const Stmt *T) {
2628    return T->getStmtClass() == UnresolvedLookupExprClass ||
2629           T->getStmtClass() == UnresolvedMemberExprClass;
2630  }
2631
2632  friend class ASTStmtReader;
2633  friend class ASTStmtWriter;
2634};
2635
2636/// \brief A reference to a name which we were able to look up during
2637/// parsing but could not resolve to a specific declaration.
2638///
2639/// This arises in several ways:
2640///   * we might be waiting for argument-dependent lookup
2641///   * the name might resolve to an overloaded function
2642/// and eventually:
2643///   * the lookup might have included a function template
2644/// These never include UnresolvedUsingValueDecls, which are always class
2645/// members and therefore appear only in UnresolvedMemberLookupExprs.
2646class UnresolvedLookupExpr : public OverloadExpr {
2647  /// True if these lookup results should be extended by
2648  /// argument-dependent lookup if this is the operand of a function
2649  /// call.
2650  bool RequiresADL;
2651
2652  /// True if these lookup results are overloaded.  This is pretty
2653  /// trivially rederivable if we urgently need to kill this field.
2654  bool Overloaded;
2655
2656  /// The naming class (C++ [class.access.base]p5) of the lookup, if
2657  /// any.  This can generally be recalculated from the context chain,
2658  /// but that can be fairly expensive for unqualified lookups.  If we
2659  /// want to improve memory use here, this could go in a union
2660  /// against the qualified-lookup bits.
2661  CXXRecordDecl *NamingClass;
2662
2663  UnresolvedLookupExpr(ASTContext &C,
2664                       CXXRecordDecl *NamingClass,
2665                       NestedNameSpecifierLoc QualifierLoc,
2666                       SourceLocation TemplateKWLoc,
2667                       const DeclarationNameInfo &NameInfo,
2668                       bool RequiresADL, bool Overloaded,
2669                       const TemplateArgumentListInfo *TemplateArgs,
2670                       UnresolvedSetIterator Begin, UnresolvedSetIterator End)
2671    : OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, TemplateKWLoc,
2672                   NameInfo, TemplateArgs, Begin, End, false, false, false),
2673      RequiresADL(RequiresADL),
2674      Overloaded(Overloaded), NamingClass(NamingClass)
2675  {}
2676
2677  UnresolvedLookupExpr(EmptyShell Empty)
2678    : OverloadExpr(UnresolvedLookupExprClass, Empty),
2679      RequiresADL(false), Overloaded(false), NamingClass(0)
2680  {}
2681
2682  friend class ASTStmtReader;
2683
2684public:
2685  static UnresolvedLookupExpr *Create(ASTContext &C,
2686                                      CXXRecordDecl *NamingClass,
2687                                      NestedNameSpecifierLoc QualifierLoc,
2688                                      const DeclarationNameInfo &NameInfo,
2689                                      bool ADL, bool Overloaded,
2690                                      UnresolvedSetIterator Begin,
2691                                      UnresolvedSetIterator End) {
2692    return new(C) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
2693                                       SourceLocation(), NameInfo,
2694                                       ADL, Overloaded, 0, Begin, End);
2695  }
2696
2697  static UnresolvedLookupExpr *Create(ASTContext &C,
2698                                      CXXRecordDecl *NamingClass,
2699                                      NestedNameSpecifierLoc QualifierLoc,
2700                                      SourceLocation TemplateKWLoc,
2701                                      const DeclarationNameInfo &NameInfo,
2702                                      bool ADL,
2703                                      const TemplateArgumentListInfo *Args,
2704                                      UnresolvedSetIterator Begin,
2705                                      UnresolvedSetIterator End);
2706
2707  static UnresolvedLookupExpr *CreateEmpty(ASTContext &C,
2708                                           bool HasTemplateKWAndArgsInfo,
2709                                           unsigned NumTemplateArgs);
2710
2711  /// True if this declaration should be extended by
2712  /// argument-dependent lookup.
2713  bool requiresADL() const { return RequiresADL; }
2714
2715  /// True if this lookup is overloaded.
2716  bool isOverloaded() const { return Overloaded; }
2717
2718  /// Gets the 'naming class' (in the sense of C++0x
2719  /// [class.access.base]p5) of the lookup.  This is the scope
2720  /// that was looked in to find these results.
2721  CXXRecordDecl *getNamingClass() const { return NamingClass; }
2722
2723  SourceLocation getLocStart() const LLVM_READONLY {
2724    if (NestedNameSpecifierLoc l = getQualifierLoc())
2725      return l.getBeginLoc();
2726    return getNameInfo().getLocStart();
2727  }
2728  SourceLocation getLocEnd() const LLVM_READONLY {
2729    if (hasExplicitTemplateArgs())
2730      return getRAngleLoc();
2731    return getNameInfo().getLocEnd();
2732  }
2733
2734  child_range children() { return child_range(); }
2735
2736  static bool classof(const Stmt *T) {
2737    return T->getStmtClass() == UnresolvedLookupExprClass;
2738  }
2739};
2740
2741/// \brief A qualified reference to a name whose declaration cannot
2742/// yet be resolved.
2743///
2744/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
2745/// it expresses a reference to a declaration such as
2746/// X<T>::value. The difference, however, is that an
2747/// DependentScopeDeclRefExpr node is used only within C++ templates when
2748/// the qualification (e.g., X<T>::) refers to a dependent type. In
2749/// this case, X<T>::value cannot resolve to a declaration because the
2750/// declaration will differ from on instantiation of X<T> to the
2751/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
2752/// qualifier (X<T>::) and the name of the entity being referenced
2753/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
2754/// declaration can be found.
2755class DependentScopeDeclRefExpr : public Expr {
2756  /// \brief The nested-name-specifier that qualifies this unresolved
2757  /// declaration name.
2758  NestedNameSpecifierLoc QualifierLoc;
2759
2760  /// The name of the entity we will be referencing.
2761  DeclarationNameInfo NameInfo;
2762
2763  /// \brief Whether the name includes info for explicit template
2764  /// keyword and arguments.
2765  bool HasTemplateKWAndArgsInfo;
2766
2767  /// \brief Return the optional template keyword and arguments info.
2768  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2769    if (!HasTemplateKWAndArgsInfo) return 0;
2770    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
2771  }
2772  /// \brief Return the optional template keyword and arguments info.
2773  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2774    return const_cast<DependentScopeDeclRefExpr*>(this)
2775      ->getTemplateKWAndArgsInfo();
2776  }
2777
2778  DependentScopeDeclRefExpr(QualType T,
2779                            NestedNameSpecifierLoc QualifierLoc,
2780                            SourceLocation TemplateKWLoc,
2781                            const DeclarationNameInfo &NameInfo,
2782                            const TemplateArgumentListInfo *Args);
2783
2784public:
2785  static DependentScopeDeclRefExpr *Create(ASTContext &C,
2786                                           NestedNameSpecifierLoc QualifierLoc,
2787                                           SourceLocation TemplateKWLoc,
2788                                           const DeclarationNameInfo &NameInfo,
2789                              const TemplateArgumentListInfo *TemplateArgs);
2790
2791  static DependentScopeDeclRefExpr *CreateEmpty(ASTContext &C,
2792                                                bool HasTemplateKWAndArgsInfo,
2793                                                unsigned NumTemplateArgs);
2794
2795  /// \brief Retrieve the name that this expression refers to.
2796  const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2797
2798  /// \brief Retrieve the name that this expression refers to.
2799  DeclarationName getDeclName() const { return NameInfo.getName(); }
2800
2801  /// \brief Retrieve the location of the name within the expression.
2802  SourceLocation getLocation() const { return NameInfo.getLoc(); }
2803
2804  /// \brief Retrieve the nested-name-specifier that qualifies the
2805  /// name, with source location information.
2806  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2807
2808
2809  /// \brief Retrieve the nested-name-specifier that qualifies this
2810  /// declaration.
2811  NestedNameSpecifier *getQualifier() const {
2812    return QualifierLoc.getNestedNameSpecifier();
2813  }
2814
2815  /// \brief Retrieve the location of the template keyword preceding
2816  /// this name, if any.
2817  SourceLocation getTemplateKeywordLoc() const {
2818    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2819    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2820  }
2821
2822  /// \brief Retrieve the location of the left angle bracket starting the
2823  /// explicit template argument list following the name, if any.
2824  SourceLocation getLAngleLoc() const {
2825    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2826    return getTemplateKWAndArgsInfo()->LAngleLoc;
2827  }
2828
2829  /// \brief Retrieve the location of the right angle bracket ending the
2830  /// explicit template argument list following the name, if any.
2831  SourceLocation getRAngleLoc() const {
2832    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2833    return getTemplateKWAndArgsInfo()->RAngleLoc;
2834  }
2835
2836  /// Determines whether the name was preceded by the template keyword.
2837  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2838
2839  /// Determines whether this lookup had explicit template arguments.
2840  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2841
2842  // Note that, inconsistently with the explicit-template-argument AST
2843  // nodes, users are *forbidden* from calling these methods on objects
2844  // without explicit template arguments.
2845
2846  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2847    assert(hasExplicitTemplateArgs());
2848    return *reinterpret_cast<ASTTemplateArgumentListInfo*>(this + 1);
2849  }
2850
2851  /// Gets a reference to the explicit template argument list.
2852  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2853    assert(hasExplicitTemplateArgs());
2854    return *reinterpret_cast<const ASTTemplateArgumentListInfo*>(this + 1);
2855  }
2856
2857  /// \brief Retrieves the optional explicit template arguments.
2858  /// This points to the same data as getExplicitTemplateArgs(), but
2859  /// returns null if there are no explicit template arguments.
2860  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2861    if (!hasExplicitTemplateArgs()) return 0;
2862    return &getExplicitTemplateArgs();
2863  }
2864
2865  /// \brief Copies the template arguments (if present) into the given
2866  /// structure.
2867  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2868    getExplicitTemplateArgs().copyInto(List);
2869  }
2870
2871  TemplateArgumentLoc const *getTemplateArgs() const {
2872    return getExplicitTemplateArgs().getTemplateArgs();
2873  }
2874
2875  unsigned getNumTemplateArgs() const {
2876    return getExplicitTemplateArgs().NumTemplateArgs;
2877  }
2878
2879  SourceLocation getLocStart() const LLVM_READONLY {
2880    return QualifierLoc.getBeginLoc();
2881  }
2882  SourceLocation getLocEnd() const LLVM_READONLY {
2883    if (hasExplicitTemplateArgs())
2884      return getRAngleLoc();
2885    return getLocation();
2886  }
2887
2888  static bool classof(const Stmt *T) {
2889    return T->getStmtClass() == DependentScopeDeclRefExprClass;
2890  }
2891
2892  child_range children() { return child_range(); }
2893
2894  friend class ASTStmtReader;
2895  friend class ASTStmtWriter;
2896};
2897
2898/// Represents an expression --- generally a full-expression --- which
2899/// introduces cleanups to be run at the end of the sub-expression's
2900/// evaluation.  The most common source of expression-introduced
2901/// cleanups is temporary objects in C++, but several other kinds of
2902/// expressions can create cleanups, including basically every
2903/// call in ARC that returns an Objective-C pointer.
2904///
2905/// This expression also tracks whether the sub-expression contains a
2906/// potentially-evaluated block literal.  The lifetime of a block
2907/// literal is the extent of the enclosing scope.
2908class ExprWithCleanups : public Expr {
2909public:
2910  /// The type of objects that are kept in the cleanup.
2911  /// It's useful to remember the set of blocks;  we could also
2912  /// remember the set of temporaries, but there's currently
2913  /// no need.
2914  typedef BlockDecl *CleanupObject;
2915
2916private:
2917  Stmt *SubExpr;
2918
2919  ExprWithCleanups(EmptyShell, unsigned NumObjects);
2920  ExprWithCleanups(Expr *SubExpr, ArrayRef<CleanupObject> Objects);
2921
2922  CleanupObject *getObjectsBuffer() {
2923    return reinterpret_cast<CleanupObject*>(this + 1);
2924  }
2925  const CleanupObject *getObjectsBuffer() const {
2926    return reinterpret_cast<const CleanupObject*>(this + 1);
2927  }
2928  friend class ASTStmtReader;
2929
2930public:
2931  static ExprWithCleanups *Create(ASTContext &C, EmptyShell empty,
2932                                  unsigned numObjects);
2933
2934  static ExprWithCleanups *Create(ASTContext &C, Expr *subexpr,
2935                                  ArrayRef<CleanupObject> objects);
2936
2937  ArrayRef<CleanupObject> getObjects() const {
2938    return ArrayRef<CleanupObject>(getObjectsBuffer(), getNumObjects());
2939  }
2940
2941  unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
2942
2943  CleanupObject getObject(unsigned i) const {
2944    assert(i < getNumObjects() && "Index out of range");
2945    return getObjects()[i];
2946  }
2947
2948  Expr *getSubExpr() { return cast<Expr>(SubExpr); }
2949  const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
2950
2951  /// setSubExpr - As with any mutator of the AST, be very careful
2952  /// when modifying an existing AST to preserve its invariants.
2953  void setSubExpr(Expr *E) { SubExpr = E; }
2954
2955  SourceLocation getLocStart() const LLVM_READONLY {
2956    return SubExpr->getLocStart();
2957  }
2958  SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
2959
2960  // Implement isa/cast/dyncast/etc.
2961  static bool classof(const Stmt *T) {
2962    return T->getStmtClass() == ExprWithCleanupsClass;
2963  }
2964
2965  // Iterators
2966  child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
2967};
2968
2969/// \brief Describes an explicit type conversion that uses functional
2970/// notion but could not be resolved because one or more arguments are
2971/// type-dependent.
2972///
2973/// The explicit type conversions expressed by
2974/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
2975/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
2976/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
2977/// type-dependent. For example, this would occur in a template such
2978/// as:
2979///
2980/// \code
2981///   template<typename T, typename A1>
2982///   inline T make_a(const A1& a1) {
2983///     return T(a1);
2984///   }
2985/// \endcode
2986///
2987/// When the returned expression is instantiated, it may resolve to a
2988/// constructor call, conversion function call, or some kind of type
2989/// conversion.
2990class CXXUnresolvedConstructExpr : public Expr {
2991  /// \brief The type being constructed.
2992  TypeSourceInfo *Type;
2993
2994  /// \brief The location of the left parentheses ('(').
2995  SourceLocation LParenLoc;
2996
2997  /// \brief The location of the right parentheses (')').
2998  SourceLocation RParenLoc;
2999
3000  /// \brief The number of arguments used to construct the type.
3001  unsigned NumArgs;
3002
3003  CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
3004                             SourceLocation LParenLoc,
3005                             ArrayRef<Expr*> Args,
3006                             SourceLocation RParenLoc);
3007
3008  CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
3009    : Expr(CXXUnresolvedConstructExprClass, Empty), Type(), NumArgs(NumArgs) { }
3010
3011  friend class ASTStmtReader;
3012
3013public:
3014  static CXXUnresolvedConstructExpr *Create(ASTContext &C,
3015                                            TypeSourceInfo *Type,
3016                                            SourceLocation LParenLoc,
3017                                            ArrayRef<Expr*> Args,
3018                                            SourceLocation RParenLoc);
3019
3020  static CXXUnresolvedConstructExpr *CreateEmpty(ASTContext &C,
3021                                                 unsigned NumArgs);
3022
3023  /// \brief Retrieve the type that is being constructed, as specified
3024  /// in the source code.
3025  QualType getTypeAsWritten() const { return Type->getType(); }
3026
3027  /// \brief Retrieve the type source information for the type being
3028  /// constructed.
3029  TypeSourceInfo *getTypeSourceInfo() const { return Type; }
3030
3031  /// \brief Retrieve the location of the left parentheses ('(') that
3032  /// precedes the argument list.
3033  SourceLocation getLParenLoc() const { return LParenLoc; }
3034  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3035
3036  /// \brief Retrieve the location of the right parentheses (')') that
3037  /// follows the argument list.
3038  SourceLocation getRParenLoc() const { return RParenLoc; }
3039  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3040
3041  /// \brief Retrieve the number of arguments.
3042  unsigned arg_size() const { return NumArgs; }
3043
3044  typedef Expr** arg_iterator;
3045  arg_iterator arg_begin() { return reinterpret_cast<Expr**>(this + 1); }
3046  arg_iterator arg_end() { return arg_begin() + NumArgs; }
3047
3048  typedef const Expr* const * const_arg_iterator;
3049  const_arg_iterator arg_begin() const {
3050    return reinterpret_cast<const Expr* const *>(this + 1);
3051  }
3052  const_arg_iterator arg_end() const {
3053    return arg_begin() + NumArgs;
3054  }
3055
3056  Expr *getArg(unsigned I) {
3057    assert(I < NumArgs && "Argument index out-of-range");
3058    return *(arg_begin() + I);
3059  }
3060
3061  const Expr *getArg(unsigned I) const {
3062    assert(I < NumArgs && "Argument index out-of-range");
3063    return *(arg_begin() + I);
3064  }
3065
3066  void setArg(unsigned I, Expr *E) {
3067    assert(I < NumArgs && "Argument index out-of-range");
3068    *(arg_begin() + I) = E;
3069  }
3070
3071  SourceLocation getLocStart() const LLVM_READONLY;
3072  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3073
3074  static bool classof(const Stmt *T) {
3075    return T->getStmtClass() == CXXUnresolvedConstructExprClass;
3076  }
3077
3078  // Iterators
3079  child_range children() {
3080    Stmt **begin = reinterpret_cast<Stmt**>(this+1);
3081    return child_range(begin, begin + NumArgs);
3082  }
3083};
3084
3085/// \brief Represents a C++ member access expression where the actual
3086/// member referenced could not be resolved because the base
3087/// expression or the member name was dependent.
3088///
3089/// Like UnresolvedMemberExprs, these can be either implicit or
3090/// explicit accesses.  It is only possible to get one of these with
3091/// an implicit access if a qualifier is provided.
3092class CXXDependentScopeMemberExpr : public Expr {
3093  /// \brief The expression for the base pointer or class reference,
3094  /// e.g., the \c x in x.f.  Can be null in implicit accesses.
3095  Stmt *Base;
3096
3097  /// \brief The type of the base expression.  Never null, even for
3098  /// implicit accesses.
3099  QualType BaseType;
3100
3101  /// \brief Whether this member expression used the '->' operator or
3102  /// the '.' operator.
3103  bool IsArrow : 1;
3104
3105  /// \brief Whether this member expression has info for explicit template
3106  /// keyword and arguments.
3107  bool HasTemplateKWAndArgsInfo : 1;
3108
3109  /// \brief The location of the '->' or '.' operator.
3110  SourceLocation OperatorLoc;
3111
3112  /// \brief The nested-name-specifier that precedes the member name, if any.
3113  NestedNameSpecifierLoc QualifierLoc;
3114
3115  /// \brief In a qualified member access expression such as t->Base::f, this
3116  /// member stores the resolves of name lookup in the context of the member
3117  /// access expression, to be used at instantiation time.
3118  ///
3119  /// FIXME: This member, along with the QualifierLoc, could
3120  /// be stuck into a structure that is optionally allocated at the end of
3121  /// the CXXDependentScopeMemberExpr, to save space in the common case.
3122  NamedDecl *FirstQualifierFoundInScope;
3123
3124  /// \brief The member to which this member expression refers, which
3125  /// can be name, overloaded operator, or destructor.
3126  /// FIXME: could also be a template-id
3127  DeclarationNameInfo MemberNameInfo;
3128
3129  /// \brief Return the optional template keyword and arguments info.
3130  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
3131    if (!HasTemplateKWAndArgsInfo) return 0;
3132    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
3133  }
3134  /// \brief Return the optional template keyword and arguments info.
3135  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
3136    return const_cast<CXXDependentScopeMemberExpr*>(this)
3137      ->getTemplateKWAndArgsInfo();
3138  }
3139
3140  CXXDependentScopeMemberExpr(ASTContext &C,
3141                          Expr *Base, QualType BaseType, bool IsArrow,
3142                          SourceLocation OperatorLoc,
3143                          NestedNameSpecifierLoc QualifierLoc,
3144                          SourceLocation TemplateKWLoc,
3145                          NamedDecl *FirstQualifierFoundInScope,
3146                          DeclarationNameInfo MemberNameInfo,
3147                          const TemplateArgumentListInfo *TemplateArgs);
3148
3149public:
3150  CXXDependentScopeMemberExpr(ASTContext &C,
3151                              Expr *Base, QualType BaseType,
3152                              bool IsArrow,
3153                              SourceLocation OperatorLoc,
3154                              NestedNameSpecifierLoc QualifierLoc,
3155                              NamedDecl *FirstQualifierFoundInScope,
3156                              DeclarationNameInfo MemberNameInfo);
3157
3158  static CXXDependentScopeMemberExpr *
3159  Create(ASTContext &C,
3160         Expr *Base, QualType BaseType, bool IsArrow,
3161         SourceLocation OperatorLoc,
3162         NestedNameSpecifierLoc QualifierLoc,
3163         SourceLocation TemplateKWLoc,
3164         NamedDecl *FirstQualifierFoundInScope,
3165         DeclarationNameInfo MemberNameInfo,
3166         const TemplateArgumentListInfo *TemplateArgs);
3167
3168  static CXXDependentScopeMemberExpr *
3169  CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
3170              unsigned NumTemplateArgs);
3171
3172  /// \brief True if this is an implicit access, i.e. one in which the
3173  /// member being accessed was not written in the source.  The source
3174  /// location of the operator is invalid in this case.
3175  bool isImplicitAccess() const;
3176
3177  /// \brief Retrieve the base object of this member expressions,
3178  /// e.g., the \c x in \c x.m.
3179  Expr *getBase() const {
3180    assert(!isImplicitAccess());
3181    return cast<Expr>(Base);
3182  }
3183
3184  QualType getBaseType() const { return BaseType; }
3185
3186  /// \brief Determine whether this member expression used the '->'
3187  /// operator; otherwise, it used the '.' operator.
3188  bool isArrow() const { return IsArrow; }
3189
3190  /// \brief Retrieve the location of the '->' or '.' operator.
3191  SourceLocation getOperatorLoc() const { return OperatorLoc; }
3192
3193  /// \brief Retrieve the nested-name-specifier that qualifies the member
3194  /// name.
3195  NestedNameSpecifier *getQualifier() const {
3196    return QualifierLoc.getNestedNameSpecifier();
3197  }
3198
3199  /// \brief Retrieve the nested-name-specifier that qualifies the member
3200  /// name, with source location information.
3201  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3202
3203
3204  /// \brief Retrieve the first part of the nested-name-specifier that was
3205  /// found in the scope of the member access expression when the member access
3206  /// was initially parsed.
3207  ///
3208  /// This function only returns a useful result when member access expression
3209  /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
3210  /// returned by this function describes what was found by unqualified name
3211  /// lookup for the identifier "Base" within the scope of the member access
3212  /// expression itself. At template instantiation time, this information is
3213  /// combined with the results of name lookup into the type of the object
3214  /// expression itself (the class type of x).
3215  NamedDecl *getFirstQualifierFoundInScope() const {
3216    return FirstQualifierFoundInScope;
3217  }
3218
3219  /// \brief Retrieve the name of the member that this expression
3220  /// refers to.
3221  const DeclarationNameInfo &getMemberNameInfo() const {
3222    return MemberNameInfo;
3223  }
3224
3225  /// \brief Retrieve the name of the member that this expression
3226  /// refers to.
3227  DeclarationName getMember() const { return MemberNameInfo.getName(); }
3228
3229  // \brief Retrieve the location of the name of the member that this
3230  // expression refers to.
3231  SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
3232
3233  /// \brief Retrieve the location of the template keyword preceding the
3234  /// member name, if any.
3235  SourceLocation getTemplateKeywordLoc() const {
3236    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3237    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
3238  }
3239
3240  /// \brief Retrieve the location of the left angle bracket starting the
3241  /// explicit template argument list following the member name, if any.
3242  SourceLocation getLAngleLoc() const {
3243    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3244    return getTemplateKWAndArgsInfo()->LAngleLoc;
3245  }
3246
3247  /// \brief Retrieve the location of the right angle bracket ending the
3248  /// explicit template argument list following the member name, if any.
3249  SourceLocation getRAngleLoc() const {
3250    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3251    return getTemplateKWAndArgsInfo()->RAngleLoc;
3252  }
3253
3254  /// Determines whether the member name was preceded by the template keyword.
3255  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3256
3257  /// \brief Determines whether this member expression actually had a C++
3258  /// template argument list explicitly specified, e.g., x.f<int>.
3259  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3260
3261  /// \brief Retrieve the explicit template argument list that followed the
3262  /// member template name, if any.
3263  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
3264    assert(hasExplicitTemplateArgs());
3265    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
3266  }
3267
3268  /// \brief Retrieve the explicit template argument list that followed the
3269  /// member template name, if any.
3270  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
3271    return const_cast<CXXDependentScopeMemberExpr *>(this)
3272             ->getExplicitTemplateArgs();
3273  }
3274
3275  /// \brief Retrieves the optional explicit template arguments.
3276  /// This points to the same data as getExplicitTemplateArgs(), but
3277  /// returns null if there are no explicit template arguments.
3278  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
3279    if (!hasExplicitTemplateArgs()) return 0;
3280    return &getExplicitTemplateArgs();
3281  }
3282
3283  /// \brief Copies the template arguments (if present) into the given
3284  /// structure.
3285  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3286    getExplicitTemplateArgs().copyInto(List);
3287  }
3288
3289  /// \brief Initializes the template arguments using the given structure.
3290  void initializeTemplateArgumentsFrom(const TemplateArgumentListInfo &List) {
3291    getExplicitTemplateArgs().initializeFrom(List);
3292  }
3293
3294  /// \brief Retrieve the template arguments provided as part of this
3295  /// template-id.
3296  const TemplateArgumentLoc *getTemplateArgs() const {
3297    return getExplicitTemplateArgs().getTemplateArgs();
3298  }
3299
3300  /// \brief Retrieve the number of template arguments provided as part of this
3301  /// template-id.
3302  unsigned getNumTemplateArgs() const {
3303    return getExplicitTemplateArgs().NumTemplateArgs;
3304  }
3305
3306  SourceLocation getLocStart() const LLVM_READONLY {
3307    if (!isImplicitAccess())
3308      return Base->getLocStart();
3309    if (getQualifier())
3310      return getQualifierLoc().getBeginLoc();
3311    return MemberNameInfo.getBeginLoc();
3312
3313  }
3314  SourceLocation getLocEnd() const LLVM_READONLY {
3315    if (hasExplicitTemplateArgs())
3316      return getRAngleLoc();
3317    return MemberNameInfo.getEndLoc();
3318  }
3319
3320  static bool classof(const Stmt *T) {
3321    return T->getStmtClass() == CXXDependentScopeMemberExprClass;
3322  }
3323
3324  // Iterators
3325  child_range children() {
3326    if (isImplicitAccess()) return child_range();
3327    return child_range(&Base, &Base + 1);
3328  }
3329
3330  friend class ASTStmtReader;
3331  friend class ASTStmtWriter;
3332};
3333
3334/// \brief Represents a C++ member access expression for which lookup
3335/// produced a set of overloaded functions.
3336///
3337/// The member access may be explicit or implicit:
3338///    struct A {
3339///      int a, b;
3340///      int explicitAccess() { return this->a + this->A::b; }
3341///      int implicitAccess() { return a + A::b; }
3342///    };
3343///
3344/// In the final AST, an explicit access always becomes a MemberExpr.
3345/// An implicit access may become either a MemberExpr or a
3346/// DeclRefExpr, depending on whether the member is static.
3347class UnresolvedMemberExpr : public OverloadExpr {
3348  /// \brief Whether this member expression used the '->' operator or
3349  /// the '.' operator.
3350  bool IsArrow : 1;
3351
3352  /// \brief Whether the lookup results contain an unresolved using
3353  /// declaration.
3354  bool HasUnresolvedUsing : 1;
3355
3356  /// \brief The expression for the base pointer or class reference,
3357  /// e.g., the \c x in x.f.  This can be null if this is an 'unbased'
3358  /// member expression
3359  Stmt *Base;
3360
3361  /// \brief The type of the base expression;  never null.
3362  QualType BaseType;
3363
3364  /// \brief The location of the '->' or '.' operator.
3365  SourceLocation OperatorLoc;
3366
3367  UnresolvedMemberExpr(ASTContext &C, bool HasUnresolvedUsing,
3368                       Expr *Base, QualType BaseType, bool IsArrow,
3369                       SourceLocation OperatorLoc,
3370                       NestedNameSpecifierLoc QualifierLoc,
3371                       SourceLocation TemplateKWLoc,
3372                       const DeclarationNameInfo &MemberNameInfo,
3373                       const TemplateArgumentListInfo *TemplateArgs,
3374                       UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3375
3376  UnresolvedMemberExpr(EmptyShell Empty)
3377    : OverloadExpr(UnresolvedMemberExprClass, Empty), IsArrow(false),
3378      HasUnresolvedUsing(false), Base(0) { }
3379
3380  friend class ASTStmtReader;
3381
3382public:
3383  static UnresolvedMemberExpr *
3384  Create(ASTContext &C, bool HasUnresolvedUsing,
3385         Expr *Base, QualType BaseType, bool IsArrow,
3386         SourceLocation OperatorLoc,
3387         NestedNameSpecifierLoc QualifierLoc,
3388         SourceLocation TemplateKWLoc,
3389         const DeclarationNameInfo &MemberNameInfo,
3390         const TemplateArgumentListInfo *TemplateArgs,
3391         UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3392
3393  static UnresolvedMemberExpr *
3394  CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
3395              unsigned NumTemplateArgs);
3396
3397  /// \brief True if this is an implicit access, i.e. one in which the
3398  /// member being accessed was not written in the source.  The source
3399  /// location of the operator is invalid in this case.
3400  bool isImplicitAccess() const;
3401
3402  /// \brief Retrieve the base object of this member expressions,
3403  /// e.g., the \c x in \c x.m.
3404  Expr *getBase() {
3405    assert(!isImplicitAccess());
3406    return cast<Expr>(Base);
3407  }
3408  const Expr *getBase() const {
3409    assert(!isImplicitAccess());
3410    return cast<Expr>(Base);
3411  }
3412
3413  QualType getBaseType() const { return BaseType; }
3414
3415  /// \brief Determine whether the lookup results contain an unresolved using
3416  /// declaration.
3417  bool hasUnresolvedUsing() const { return HasUnresolvedUsing; }
3418
3419  /// \brief Determine whether this member expression used the '->'
3420  /// operator; otherwise, it used the '.' operator.
3421  bool isArrow() const { return IsArrow; }
3422
3423  /// \brief Retrieve the location of the '->' or '.' operator.
3424  SourceLocation getOperatorLoc() const { return OperatorLoc; }
3425
3426  /// \brief Retrieves the naming class of this lookup.
3427  CXXRecordDecl *getNamingClass() const;
3428
3429  /// \brief Retrieve the full name info for the member that this expression
3430  /// refers to.
3431  const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
3432
3433  /// \brief Retrieve the name of the member that this expression
3434  /// refers to.
3435  DeclarationName getMemberName() const { return getName(); }
3436
3437  // \brief Retrieve the location of the name of the member that this
3438  // expression refers to.
3439  SourceLocation getMemberLoc() const { return getNameLoc(); }
3440
3441  // \brief Return the preferred location (the member name) for the arrow when
3442  // diagnosing a problem with this expression.
3443  SourceLocation getExprLoc() const LLVM_READONLY { return getMemberLoc(); }
3444
3445  SourceLocation getLocStart() const LLVM_READONLY {
3446    if (!isImplicitAccess())
3447      return Base->getLocStart();
3448    if (NestedNameSpecifierLoc l = getQualifierLoc())
3449      return l.getBeginLoc();
3450    return getMemberNameInfo().getLocStart();
3451  }
3452  SourceLocation getLocEnd() const LLVM_READONLY {
3453    if (hasExplicitTemplateArgs())
3454      return getRAngleLoc();
3455    return getMemberNameInfo().getLocEnd();
3456  }
3457
3458  static bool classof(const Stmt *T) {
3459    return T->getStmtClass() == UnresolvedMemberExprClass;
3460  }
3461
3462  // Iterators
3463  child_range children() {
3464    if (isImplicitAccess()) return child_range();
3465    return child_range(&Base, &Base + 1);
3466  }
3467};
3468
3469/// \brief Represents a C++0x noexcept expression (C++ [expr.unary.noexcept]).
3470///
3471/// The noexcept expression tests whether a given expression might throw. Its
3472/// result is a boolean constant.
3473class CXXNoexceptExpr : public Expr {
3474  bool Value : 1;
3475  Stmt *Operand;
3476  SourceRange Range;
3477
3478  friend class ASTStmtReader;
3479
3480public:
3481  CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
3482                  SourceLocation Keyword, SourceLocation RParen)
3483    : Expr(CXXNoexceptExprClass, Ty, VK_RValue, OK_Ordinary,
3484           /*TypeDependent*/false,
3485           /*ValueDependent*/Val == CT_Dependent,
3486           Val == CT_Dependent || Operand->isInstantiationDependent(),
3487           Operand->containsUnexpandedParameterPack()),
3488      Value(Val == CT_Cannot), Operand(Operand), Range(Keyword, RParen)
3489  { }
3490
3491  CXXNoexceptExpr(EmptyShell Empty)
3492    : Expr(CXXNoexceptExprClass, Empty)
3493  { }
3494
3495  Expr *getOperand() const { return static_cast<Expr*>(Operand); }
3496
3497  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
3498  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
3499  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
3500
3501  bool getValue() const { return Value; }
3502
3503  static bool classof(const Stmt *T) {
3504    return T->getStmtClass() == CXXNoexceptExprClass;
3505  }
3506
3507  // Iterators
3508  child_range children() { return child_range(&Operand, &Operand + 1); }
3509};
3510
3511/// \brief Represents a C++0x pack expansion that produces a sequence of
3512/// expressions.
3513///
3514/// A pack expansion expression contains a pattern (which itself is an
3515/// expression) followed by an ellipsis. For example:
3516///
3517/// \code
3518/// template<typename F, typename ...Types>
3519/// void forward(F f, Types &&...args) {
3520///   f(static_cast<Types&&>(args)...);
3521/// }
3522/// \endcode
3523///
3524/// Here, the argument to the function object \c f is a pack expansion whose
3525/// pattern is \c static_cast<Types&&>(args). When the \c forward function
3526/// template is instantiated, the pack expansion will instantiate to zero or
3527/// or more function arguments to the function object \c f.
3528class PackExpansionExpr : public Expr {
3529  SourceLocation EllipsisLoc;
3530
3531  /// \brief The number of expansions that will be produced by this pack
3532  /// expansion expression, if known.
3533  ///
3534  /// When zero, the number of expansions is not known. Otherwise, this value
3535  /// is the number of expansions + 1.
3536  unsigned NumExpansions;
3537
3538  Stmt *Pattern;
3539
3540  friend class ASTStmtReader;
3541  friend class ASTStmtWriter;
3542
3543public:
3544  PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
3545                    Optional<unsigned> NumExpansions)
3546    : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
3547           Pattern->getObjectKind(), /*TypeDependent=*/true,
3548           /*ValueDependent=*/true, /*InstantiationDependent=*/true,
3549           /*ContainsUnexpandedParameterPack=*/false),
3550      EllipsisLoc(EllipsisLoc),
3551      NumExpansions(NumExpansions? *NumExpansions + 1 : 0),
3552      Pattern(Pattern) { }
3553
3554  PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) { }
3555
3556  /// \brief Retrieve the pattern of the pack expansion.
3557  Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
3558
3559  /// \brief Retrieve the pattern of the pack expansion.
3560  const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
3561
3562  /// \brief Retrieve the location of the ellipsis that describes this pack
3563  /// expansion.
3564  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
3565
3566  /// \brief Determine the number of expansions that will be produced when
3567  /// this pack expansion is instantiated, if already known.
3568  Optional<unsigned> getNumExpansions() const {
3569    if (NumExpansions)
3570      return NumExpansions - 1;
3571
3572    return None;
3573  }
3574
3575  SourceLocation getLocStart() const LLVM_READONLY {
3576    return Pattern->getLocStart();
3577  }
3578  SourceLocation getLocEnd() const LLVM_READONLY { return EllipsisLoc; }
3579
3580  static bool classof(const Stmt *T) {
3581    return T->getStmtClass() == PackExpansionExprClass;
3582  }
3583
3584  // Iterators
3585  child_range children() {
3586    return child_range(&Pattern, &Pattern + 1);
3587  }
3588};
3589
3590inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
3591  if (!HasTemplateKWAndArgsInfo) return 0;
3592  if (isa<UnresolvedLookupExpr>(this))
3593    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
3594      (cast<UnresolvedLookupExpr>(this) + 1);
3595  else
3596    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
3597      (cast<UnresolvedMemberExpr>(this) + 1);
3598}
3599
3600/// \brief Represents an expression that computes the length of a parameter
3601/// pack.
3602///
3603/// \code
3604/// template<typename ...Types>
3605/// struct count {
3606///   static const unsigned value = sizeof...(Types);
3607/// };
3608/// \endcode
3609class SizeOfPackExpr : public Expr {
3610  /// \brief The location of the 'sizeof' keyword.
3611  SourceLocation OperatorLoc;
3612
3613  /// \brief The location of the name of the parameter pack.
3614  SourceLocation PackLoc;
3615
3616  /// \brief The location of the closing parenthesis.
3617  SourceLocation RParenLoc;
3618
3619  /// \brief The length of the parameter pack, if known.
3620  ///
3621  /// When this expression is value-dependent, the length of the parameter pack
3622  /// is unknown. When this expression is not value-dependent, the length is
3623  /// known.
3624  unsigned Length;
3625
3626  /// \brief The parameter pack itself.
3627  NamedDecl *Pack;
3628
3629  friend class ASTStmtReader;
3630  friend class ASTStmtWriter;
3631
3632public:
3633  /// \brief Creates a value-dependent expression that computes the length of
3634  /// the given parameter pack.
3635  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
3636                 SourceLocation PackLoc, SourceLocation RParenLoc)
3637    : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
3638           /*TypeDependent=*/false, /*ValueDependent=*/true,
3639           /*InstantiationDependent=*/true,
3640           /*ContainsUnexpandedParameterPack=*/false),
3641      OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
3642      Length(0), Pack(Pack) { }
3643
3644  /// \brief Creates an expression that computes the length of
3645  /// the given parameter pack, which is already known.
3646  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
3647                 SourceLocation PackLoc, SourceLocation RParenLoc,
3648                 unsigned Length)
3649  : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
3650         /*TypeDependent=*/false, /*ValueDependent=*/false,
3651         /*InstantiationDependent=*/false,
3652         /*ContainsUnexpandedParameterPack=*/false),
3653    OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
3654    Length(Length), Pack(Pack) { }
3655
3656  /// \brief Create an empty expression.
3657  SizeOfPackExpr(EmptyShell Empty) : Expr(SizeOfPackExprClass, Empty) { }
3658
3659  /// \brief Determine the location of the 'sizeof' keyword.
3660  SourceLocation getOperatorLoc() const { return OperatorLoc; }
3661
3662  /// \brief Determine the location of the parameter pack.
3663  SourceLocation getPackLoc() const { return PackLoc; }
3664
3665  /// \brief Determine the location of the right parenthesis.
3666  SourceLocation getRParenLoc() const { return RParenLoc; }
3667
3668  /// \brief Retrieve the parameter pack.
3669  NamedDecl *getPack() const { return Pack; }
3670
3671  /// \brief Retrieve the length of the parameter pack.
3672  ///
3673  /// This routine may only be invoked when the expression is not
3674  /// value-dependent.
3675  unsigned getPackLength() const {
3676    assert(!isValueDependent() &&
3677           "Cannot get the length of a value-dependent pack size expression");
3678    return Length;
3679  }
3680
3681  SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
3682  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3683
3684  static bool classof(const Stmt *T) {
3685    return T->getStmtClass() == SizeOfPackExprClass;
3686  }
3687
3688  // Iterators
3689  child_range children() { return child_range(); }
3690};
3691
3692/// \brief Represents a reference to a non-type template parameter
3693/// that has been substituted with a template argument.
3694class SubstNonTypeTemplateParmExpr : public Expr {
3695  /// \brief The replaced parameter.
3696  NonTypeTemplateParmDecl *Param;
3697
3698  /// \brief The replacement expression.
3699  Stmt *Replacement;
3700
3701  /// \brief The location of the non-type template parameter reference.
3702  SourceLocation NameLoc;
3703
3704  friend class ASTReader;
3705  friend class ASTStmtReader;
3706  explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
3707    : Expr(SubstNonTypeTemplateParmExprClass, Empty) { }
3708
3709public:
3710  SubstNonTypeTemplateParmExpr(QualType type,
3711                               ExprValueKind valueKind,
3712                               SourceLocation loc,
3713                               NonTypeTemplateParmDecl *param,
3714                               Expr *replacement)
3715    : Expr(SubstNonTypeTemplateParmExprClass, type, valueKind, OK_Ordinary,
3716           replacement->isTypeDependent(), replacement->isValueDependent(),
3717           replacement->isInstantiationDependent(),
3718           replacement->containsUnexpandedParameterPack()),
3719      Param(param), Replacement(replacement), NameLoc(loc) {}
3720
3721  SourceLocation getNameLoc() const { return NameLoc; }
3722  SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3723  SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3724
3725  Expr *getReplacement() const { return cast<Expr>(Replacement); }
3726
3727  NonTypeTemplateParmDecl *getParameter() const { return Param; }
3728
3729  static bool classof(const Stmt *s) {
3730    return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
3731  }
3732
3733  // Iterators
3734  child_range children() { return child_range(&Replacement, &Replacement+1); }
3735};
3736
3737/// \brief Represents a reference to a non-type template parameter pack that
3738/// has been substituted with a non-template argument pack.
3739///
3740/// When a pack expansion in the source code contains multiple parameter packs
3741/// and those parameter packs correspond to different levels of template
3742/// parameter lists, this node is used to represent a non-type template
3743/// parameter pack from an outer level, which has already had its argument pack
3744/// substituted but that still lives within a pack expansion that itself
3745/// could not be instantiated. When actually performing a substitution into
3746/// that pack expansion (e.g., when all template parameters have corresponding
3747/// arguments), this type will be replaced with the appropriate underlying
3748/// expression at the current pack substitution index.
3749class SubstNonTypeTemplateParmPackExpr : public Expr {
3750  /// \brief The non-type template parameter pack itself.
3751  NonTypeTemplateParmDecl *Param;
3752
3753  /// \brief A pointer to the set of template arguments that this
3754  /// parameter pack is instantiated with.
3755  const TemplateArgument *Arguments;
3756
3757  /// \brief The number of template arguments in \c Arguments.
3758  unsigned NumArguments;
3759
3760  /// \brief The location of the non-type template parameter pack reference.
3761  SourceLocation NameLoc;
3762
3763  friend class ASTReader;
3764  friend class ASTStmtReader;
3765  explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
3766    : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) { }
3767
3768public:
3769  SubstNonTypeTemplateParmPackExpr(QualType T,
3770                                   NonTypeTemplateParmDecl *Param,
3771                                   SourceLocation NameLoc,
3772                                   const TemplateArgument &ArgPack);
3773
3774  /// \brief Retrieve the non-type template parameter pack being substituted.
3775  NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
3776
3777  /// \brief Retrieve the location of the parameter pack name.
3778  SourceLocation getParameterPackLocation() const { return NameLoc; }
3779
3780  /// \brief Retrieve the template argument pack containing the substituted
3781  /// template arguments.
3782  TemplateArgument getArgumentPack() const;
3783
3784  SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3785  SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3786
3787  static bool classof(const Stmt *T) {
3788    return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
3789  }
3790
3791  // Iterators
3792  child_range children() { return child_range(); }
3793};
3794
3795/// \brief Represents a reference to a function parameter pack that has been
3796/// substituted but not yet expanded.
3797///
3798/// When a pack expansion contains multiple parameter packs at different levels,
3799/// this node is used to represent a function parameter pack at an outer level
3800/// which we have already substituted to refer to expanded parameters, but where
3801/// the containing pack expansion cannot yet be expanded.
3802///
3803/// \code
3804/// template<typename...Ts> struct S {
3805///   template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
3806/// };
3807/// template struct S<int, int>;
3808/// \endcode
3809class FunctionParmPackExpr : public Expr {
3810  /// \brief The function parameter pack which was referenced.
3811  ParmVarDecl *ParamPack;
3812
3813  /// \brief The location of the function parameter pack reference.
3814  SourceLocation NameLoc;
3815
3816  /// \brief The number of expansions of this pack.
3817  unsigned NumParameters;
3818
3819  FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
3820                       SourceLocation NameLoc, unsigned NumParams,
3821                       Decl * const *Params);
3822
3823  friend class ASTReader;
3824  friend class ASTStmtReader;
3825
3826public:
3827  static FunctionParmPackExpr *Create(ASTContext &Context, QualType T,
3828                                      ParmVarDecl *ParamPack,
3829                                      SourceLocation NameLoc,
3830                                      ArrayRef<Decl *> Params);
3831  static FunctionParmPackExpr *CreateEmpty(ASTContext &Context,
3832                                           unsigned NumParams);
3833
3834  /// \brief Get the parameter pack which this expression refers to.
3835  ParmVarDecl *getParameterPack() const { return ParamPack; }
3836
3837  /// \brief Get the location of the parameter pack.
3838  SourceLocation getParameterPackLocation() const { return NameLoc; }
3839
3840  /// \brief Iterators over the parameters which the parameter pack expanded
3841  /// into.
3842  typedef ParmVarDecl * const *iterator;
3843  iterator begin() const { return reinterpret_cast<iterator>(this+1); }
3844  iterator end() const { return begin() + NumParameters; }
3845
3846  /// \brief Get the number of parameters in this parameter pack.
3847  unsigned getNumExpansions() const { return NumParameters; }
3848
3849  /// \brief Get an expansion of the parameter pack by index.
3850  ParmVarDecl *getExpansion(unsigned I) const { return begin()[I]; }
3851
3852  SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3853  SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3854
3855  static bool classof(const Stmt *T) {
3856    return T->getStmtClass() == FunctionParmPackExprClass;
3857  }
3858
3859  child_range children() { return child_range(); }
3860};
3861
3862/// \brief Represents a prvalue temporary that written into memory so that
3863/// a reference can bind to it.
3864///
3865/// Prvalue expressions are materialized when they need to have an address
3866/// in memory for a reference to bind to. This happens when binding a
3867/// reference to the result of a conversion, e.g.,
3868///
3869/// \code
3870/// const int &r = 1.0;
3871/// \endcode
3872///
3873/// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
3874/// then materialized via a \c MaterializeTemporaryExpr, and the reference
3875/// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
3876/// (either an lvalue or an xvalue, depending on the kind of reference binding
3877/// to it), maintaining the invariant that references always bind to glvalues.
3878///
3879/// Reference binding and copy-elision can both extend the lifetime of a
3880/// temporary. When either happens, the expression will also track the
3881/// declaration which is responsible for the lifetime extension.
3882class MaterializeTemporaryExpr : public Expr {
3883public:
3884  /// \brief The temporary-generating expression whose value will be
3885  /// materialized.
3886  Stmt *Temporary;
3887
3888  /// \brief The declaration which lifetime-extended this reference, if any.
3889  /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3890  const ValueDecl *ExtendingDecl;
3891
3892  friend class ASTStmtReader;
3893  friend class ASTStmtWriter;
3894
3895public:
3896  MaterializeTemporaryExpr(QualType T, Expr *Temporary,
3897                           bool BoundToLvalueReference,
3898                           const ValueDecl *ExtendedBy)
3899    : Expr(MaterializeTemporaryExprClass, T,
3900           BoundToLvalueReference? VK_LValue : VK_XValue, OK_Ordinary,
3901           Temporary->isTypeDependent(), Temporary->isValueDependent(),
3902           Temporary->isInstantiationDependent(),
3903           Temporary->containsUnexpandedParameterPack()),
3904      Temporary(Temporary), ExtendingDecl(ExtendedBy) {
3905  }
3906
3907  MaterializeTemporaryExpr(EmptyShell Empty)
3908    : Expr(MaterializeTemporaryExprClass, Empty) { }
3909
3910  /// \brief Retrieve the temporary-generating subexpression whose value will
3911  /// be materialized into a glvalue.
3912  Expr *GetTemporaryExpr() const { return static_cast<Expr *>(Temporary); }
3913
3914  /// \brief Retrieve the storage duration for the materialized temporary.
3915  StorageDuration getStorageDuration() const {
3916    if (!ExtendingDecl)
3917      return SD_FullExpression;
3918    // FIXME: This is not necessarily correct for a temporary materialized
3919    // within a default initializer.
3920    if (isa<FieldDecl>(ExtendingDecl))
3921      return SD_Automatic;
3922    return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
3923  }
3924
3925  /// \brief Get the declaration which triggered the lifetime-extension of this
3926  /// temporary, if any.
3927  const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
3928
3929  void setExtendingDecl(const ValueDecl *ExtendedBy) {
3930    ExtendingDecl = ExtendedBy;
3931  }
3932
3933  /// \brief Determine whether this materialized temporary is bound to an
3934  /// lvalue reference; otherwise, it's bound to an rvalue reference.
3935  bool isBoundToLvalueReference() const {
3936    return getValueKind() == VK_LValue;
3937  }
3938
3939  SourceLocation getLocStart() const LLVM_READONLY {
3940    return Temporary->getLocStart();
3941  }
3942  SourceLocation getLocEnd() const LLVM_READONLY {
3943    return Temporary->getLocEnd();
3944  }
3945
3946  static bool classof(const Stmt *T) {
3947    return T->getStmtClass() == MaterializeTemporaryExprClass;
3948  }
3949
3950  // Iterators
3951  child_range children() { return child_range(&Temporary, &Temporary + 1); }
3952};
3953
3954}  // end namespace clang
3955
3956#endif
3957