Expr.h revision 51f4708c00110940ca3f337961915f2ca1668375
1//===--- Expr.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.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPR_H
15#define LLVM_CLANG_AST_EXPR_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/Stmt.h"
19#include "clang/AST/Type.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/OperationKinds.h"
22#include "clang/AST/ASTVector.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/UsuallyTinyPtrVector.h"
25#include "clang/Basic/TypeTraits.h"
26#include "llvm/ADT/APSInt.h"
27#include "llvm/ADT/APFloat.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/StringRef.h"
30#include <cctype>
31
32namespace clang {
33  class ASTContext;
34  class APValue;
35  class Decl;
36  class IdentifierInfo;
37  class ParmVarDecl;
38  class NamedDecl;
39  class ValueDecl;
40  class BlockDecl;
41  class CXXBaseSpecifier;
42  class CXXOperatorCallExpr;
43  class CXXMemberCallExpr;
44  class ObjCPropertyRefExpr;
45  class OpaqueValueExpr;
46
47/// \brief A simple array of base specifiers.
48typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
49
50/// Expr - This represents one expression.  Note that Expr's are subclasses of
51/// Stmt.  This allows an expression to be transparently used any place a Stmt
52/// is required.
53///
54class Expr : public Stmt {
55  QualType TR;
56
57protected:
58  Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
59       bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
60    : Stmt(SC)
61  {
62    ExprBits.TypeDependent = TD;
63    ExprBits.ValueDependent = VD;
64    ExprBits.InstantiationDependent = ID;
65    ExprBits.ValueKind = VK;
66    ExprBits.ObjectKind = OK;
67    ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
68    setType(T);
69  }
70
71  /// \brief Construct an empty expression.
72  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
73
74public:
75  QualType getType() const { return TR; }
76  void setType(QualType t) {
77    // In C++, the type of an expression is always adjusted so that it
78    // will not have reference type an expression will never have
79    // reference type (C++ [expr]p6). Use
80    // QualType::getNonReferenceType() to retrieve the non-reference
81    // type. Additionally, inspect Expr::isLvalue to determine whether
82    // an expression that is adjusted in this manner should be
83    // considered an lvalue.
84    assert((t.isNull() || !t->isReferenceType()) &&
85           "Expressions can't have reference type");
86
87    TR = t;
88  }
89
90  /// isValueDependent - Determines whether this expression is
91  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
92  /// array bound of "Chars" in the following example is
93  /// value-dependent.
94  /// @code
95  /// template<int Size, char (&Chars)[Size]> struct meta_string;
96  /// @endcode
97  bool isValueDependent() const { return ExprBits.ValueDependent; }
98
99  /// \brief Set whether this expression is value-dependent or not.
100  void setValueDependent(bool VD) {
101    ExprBits.ValueDependent = VD;
102    if (VD)
103      ExprBits.InstantiationDependent = true;
104  }
105
106  /// isTypeDependent - Determines whether this expression is
107  /// type-dependent (C++ [temp.dep.expr]), which means that its type
108  /// could change from one template instantiation to the next. For
109  /// example, the expressions "x" and "x + y" are type-dependent in
110  /// the following code, but "y" is not type-dependent:
111  /// @code
112  /// template<typename T>
113  /// void add(T x, int y) {
114  ///   x + y;
115  /// }
116  /// @endcode
117  bool isTypeDependent() const { return ExprBits.TypeDependent; }
118
119  /// \brief Set whether this expression is type-dependent or not.
120  void setTypeDependent(bool TD) {
121    ExprBits.TypeDependent = TD;
122    if (TD)
123      ExprBits.InstantiationDependent = true;
124  }
125
126  /// \brief Whether this expression is instantiation-dependent, meaning that
127  /// it depends in some way on a template parameter, even if neither its type
128  /// nor (constant) value can change due to the template instantiation.
129  ///
130  /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
131  /// instantiation-dependent (since it involves a template parameter \c T), but
132  /// is neither type- nor value-dependent, since the type of the inner
133  /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
134  /// \c sizeof is known.
135  ///
136  /// \code
137  /// template<typename T>
138  /// void f(T x, T y) {
139  ///   sizeof(sizeof(T() + T());
140  /// }
141  /// \endcode
142  ///
143  bool isInstantiationDependent() const {
144    return ExprBits.InstantiationDependent;
145  }
146
147  /// \brief Set whether this expression is instantiation-dependent or not.
148  void setInstantiationDependent(bool ID) {
149    ExprBits.InstantiationDependent = ID;
150  }
151
152  /// \brief Whether this expression contains an unexpanded parameter
153  /// pack (for C++0x variadic templates).
154  ///
155  /// Given the following function template:
156  ///
157  /// \code
158  /// template<typename F, typename ...Types>
159  /// void forward(const F &f, Types &&...args) {
160  ///   f(static_cast<Types&&>(args)...);
161  /// }
162  /// \endcode
163  ///
164  /// The expressions \c args and \c static_cast<Types&&>(args) both
165  /// contain parameter packs.
166  bool containsUnexpandedParameterPack() const {
167    return ExprBits.ContainsUnexpandedParameterPack;
168  }
169
170  /// \brief Set the bit that describes whether this expression
171  /// contains an unexpanded parameter pack.
172  void setContainsUnexpandedParameterPack(bool PP = true) {
173    ExprBits.ContainsUnexpandedParameterPack = PP;
174  }
175
176  /// getExprLoc - Return the preferred location for the arrow when diagnosing
177  /// a problem with a generic expression.
178  SourceLocation getExprLoc() const;
179
180  /// isUnusedResultAWarning - Return true if this immediate expression should
181  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
182  /// with location to warn on and the source range[s] to report with the
183  /// warning.
184  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
185                              SourceRange &R2, ASTContext &Ctx) const;
186
187  /// isLValue - True if this expression is an "l-value" according to
188  /// the rules of the current language.  C and C++ give somewhat
189  /// different rules for this concept, but in general, the result of
190  /// an l-value expression identifies a specific object whereas the
191  /// result of an r-value expression is a value detached from any
192  /// specific storage.
193  ///
194  /// C++0x divides the concept of "r-value" into pure r-values
195  /// ("pr-values") and so-called expiring values ("x-values"), which
196  /// identify specific objects that can be safely cannibalized for
197  /// their resources.  This is an unfortunate abuse of terminology on
198  /// the part of the C++ committee.  In Clang, when we say "r-value",
199  /// we generally mean a pr-value.
200  bool isLValue() const { return getValueKind() == VK_LValue; }
201  bool isRValue() const { return getValueKind() == VK_RValue; }
202  bool isXValue() const { return getValueKind() == VK_XValue; }
203  bool isGLValue() const { return getValueKind() != VK_RValue; }
204
205  enum LValueClassification {
206    LV_Valid,
207    LV_NotObjectType,
208    LV_IncompleteVoidType,
209    LV_DuplicateVectorComponents,
210    LV_InvalidExpression,
211    LV_InvalidMessageExpression,
212    LV_MemberFunction,
213    LV_SubObjCPropertySetting,
214    LV_ClassTemporary
215  };
216  /// Reasons why an expression might not be an l-value.
217  LValueClassification ClassifyLValue(ASTContext &Ctx) const;
218
219  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
220  /// does not have an incomplete type, does not have a const-qualified type,
221  /// and if it is a structure or union, does not have any member (including,
222  /// recursively, any member or element of all contained aggregates or unions)
223  /// with a const-qualified type.
224  ///
225  /// \param Loc [in] [out] - A source location which *may* be filled
226  /// in with the location of the expression making this a
227  /// non-modifiable lvalue, if specified.
228  enum isModifiableLvalueResult {
229    MLV_Valid,
230    MLV_NotObjectType,
231    MLV_IncompleteVoidType,
232    MLV_DuplicateVectorComponents,
233    MLV_InvalidExpression,
234    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
235    MLV_IncompleteType,
236    MLV_ConstQualified,
237    MLV_ArrayType,
238    MLV_NotBlockQualified,
239    MLV_ReadonlyProperty,
240    MLV_NoSetterProperty,
241    MLV_MemberFunction,
242    MLV_SubObjCPropertySetting,
243    MLV_InvalidMessageExpression,
244    MLV_ClassTemporary
245  };
246  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
247                                              SourceLocation *Loc = 0) const;
248
249  /// \brief The return type of classify(). Represents the C++0x expression
250  ///        taxonomy.
251  class Classification {
252  public:
253    /// \brief The various classification results. Most of these mean prvalue.
254    enum Kinds {
255      CL_LValue,
256      CL_XValue,
257      CL_Function, // Functions cannot be lvalues in C.
258      CL_Void, // Void cannot be an lvalue in C.
259      CL_AddressableVoid, // Void expression whose address can be taken in C.
260      CL_DuplicateVectorComponents, // A vector shuffle with dupes.
261      CL_MemberFunction, // An expression referring to a member function
262      CL_SubObjCPropertySetting,
263      CL_ClassTemporary, // A prvalue of class type
264      CL_ObjCMessageRValue, // ObjC message is an rvalue
265      CL_PRValue // A prvalue for any other reason, of any other type
266    };
267    /// \brief The results of modification testing.
268    enum ModifiableType {
269      CM_Untested, // testModifiable was false.
270      CM_Modifiable,
271      CM_RValue, // Not modifiable because it's an rvalue
272      CM_Function, // Not modifiable because it's a function; C++ only
273      CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
274      CM_NotBlockQualified, // Not captured in the closure
275      CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
276      CM_ConstQualified,
277      CM_ArrayType,
278      CM_IncompleteType
279    };
280
281  private:
282    friend class Expr;
283
284    unsigned short Kind;
285    unsigned short Modifiable;
286
287    explicit Classification(Kinds k, ModifiableType m)
288      : Kind(k), Modifiable(m)
289    {}
290
291  public:
292    Classification() {}
293
294    Kinds getKind() const { return static_cast<Kinds>(Kind); }
295    ModifiableType getModifiable() const {
296      assert(Modifiable != CM_Untested && "Did not test for modifiability.");
297      return static_cast<ModifiableType>(Modifiable);
298    }
299    bool isLValue() const { return Kind == CL_LValue; }
300    bool isXValue() const { return Kind == CL_XValue; }
301    bool isGLValue() const { return Kind <= CL_XValue; }
302    bool isPRValue() const { return Kind >= CL_Function; }
303    bool isRValue() const { return Kind >= CL_XValue; }
304    bool isModifiable() const { return getModifiable() == CM_Modifiable; }
305
306    /// \brief Create a simple, modifiably lvalue
307    static Classification makeSimpleLValue() {
308      return Classification(CL_LValue, CM_Modifiable);
309    }
310
311  };
312  /// \brief Classify - Classify this expression according to the C++0x
313  ///        expression taxonomy.
314  ///
315  /// C++0x defines ([basic.lval]) a new taxonomy of expressions to replace the
316  /// old lvalue vs rvalue. This function determines the type of expression this
317  /// is. There are three expression types:
318  /// - lvalues are classical lvalues as in C++03.
319  /// - prvalues are equivalent to rvalues in C++03.
320  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
321  ///   function returning an rvalue reference.
322  /// lvalues and xvalues are collectively referred to as glvalues, while
323  /// prvalues and xvalues together form rvalues.
324  Classification Classify(ASTContext &Ctx) const {
325    return ClassifyImpl(Ctx, 0);
326  }
327
328  /// \brief ClassifyModifiable - Classify this expression according to the
329  ///        C++0x expression taxonomy, and see if it is valid on the left side
330  ///        of an assignment.
331  ///
332  /// This function extends classify in that it also tests whether the
333  /// expression is modifiable (C99 6.3.2.1p1).
334  /// \param Loc A source location that might be filled with a relevant location
335  ///            if the expression is not modifiable.
336  Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
337    return ClassifyImpl(Ctx, &Loc);
338  }
339
340  /// getValueKindForType - Given a formal return or parameter type,
341  /// give its value kind.
342  static ExprValueKind getValueKindForType(QualType T) {
343    if (const ReferenceType *RT = T->getAs<ReferenceType>())
344      return (isa<LValueReferenceType>(RT)
345                ? VK_LValue
346                : (RT->getPointeeType()->isFunctionType()
347                     ? VK_LValue : VK_XValue));
348    return VK_RValue;
349  }
350
351  /// getValueKind - The value kind that this expression produces.
352  ExprValueKind getValueKind() const {
353    return static_cast<ExprValueKind>(ExprBits.ValueKind);
354  }
355
356  /// getObjectKind - The object kind that this expression produces.
357  /// Object kinds are meaningful only for expressions that yield an
358  /// l-value or x-value.
359  ExprObjectKind getObjectKind() const {
360    return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
361  }
362
363  bool isOrdinaryOrBitFieldObject() const {
364    ExprObjectKind OK = getObjectKind();
365    return (OK == OK_Ordinary || OK == OK_BitField);
366  }
367
368  /// setValueKind - Set the value kind produced by this expression.
369  void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
370
371  /// setObjectKind - Set the object kind produced by this expression.
372  void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
373
374private:
375  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
376
377public:
378
379  /// \brief If this expression refers to a bit-field, retrieve the
380  /// declaration of that bit-field.
381  FieldDecl *getBitField();
382
383  const FieldDecl *getBitField() const {
384    return const_cast<Expr*>(this)->getBitField();
385  }
386
387  /// \brief If this expression is an l-value for an Objective C
388  /// property, find the underlying property reference expression.
389  const ObjCPropertyRefExpr *getObjCProperty() const;
390
391  /// \brief Returns whether this expression refers to a vector element.
392  bool refersToVectorElement() const;
393
394  /// \brief Returns whether this expression has a placeholder type.
395  bool hasPlaceholderType() const {
396    return getType()->isPlaceholderType();
397  }
398
399  /// \brief Returns whether this expression has a specific placeholder type.
400  bool hasPlaceholderType(BuiltinType::Kind K) const {
401    assert(BuiltinType::isPlaceholderTypeKind(K));
402    if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
403      return BT->getKind() == K;
404    return false;
405  }
406
407  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
408  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
409  /// but also int expressions which are produced by things like comparisons in
410  /// C.
411  bool isKnownToHaveBooleanValue() const;
412
413  /// isIntegerConstantExpr - Return true if this expression is a valid integer
414  /// constant expression, and, if so, return its value in Result.  If not a
415  /// valid i-c-e, return false and fill in Loc (if specified) with the location
416  /// of the invalid expression.
417  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
418                             SourceLocation *Loc = 0,
419                             bool isEvaluated = true) const;
420  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
421    llvm::APSInt X;
422    return isIntegerConstantExpr(X, Ctx, Loc);
423  }
424  /// isConstantInitializer - Returns true if this expression is a constant
425  /// initializer, which can be emitted at compile-time.
426  bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
427
428  /// EvalStatus is a struct with detailed info about an evaluation in progress.
429  struct EvalStatus {
430    /// HasSideEffects - Whether the evaluated expression has side effects.
431    /// For example, (f() && 0) can be folded, but it still has side effects.
432    bool HasSideEffects;
433
434    /// Diag - If the expression is unfoldable, then Diag contains a note
435    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
436    /// position for the error, and DiagExpr is the expression that caused
437    /// the error.
438    /// If the expression is foldable, but not an integer constant expression,
439    /// Diag contains a note diagnostic that describes why it isn't an integer
440    /// constant expression. If the expression *is* an integer constant
441    /// expression, then Diag will be zero.
442    unsigned Diag;
443    const Expr *DiagExpr;
444    SourceLocation DiagLoc;
445
446    EvalStatus() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
447
448    // hasSideEffects - Return true if the evaluated expression has
449    // side effects.
450    bool hasSideEffects() const {
451      return HasSideEffects;
452    }
453  };
454
455  /// EvalResult is a struct with detailed info about an evaluated expression.
456  struct EvalResult : EvalStatus {
457    /// Val - This is the value the expression can be folded to.
458    APValue Val;
459
460    // isGlobalLValue - Return true if the evaluated lvalue expression
461    // is global.
462    bool isGlobalLValue() const;
463  };
464
465  /// EvaluateAsRValue - Return true if this is a constant which we can fold to
466  /// an rvalue using any crazy technique (that has nothing to do with language
467  /// standards) that we want to, even if the expression has side-effects. If
468  /// this function returns true, it returns the folded constant in Result. If
469  /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
470  /// applied.
471  bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
472
473  /// EvaluateAsBooleanCondition - Return true if this is a constant
474  /// which we we can fold and convert to a boolean condition using
475  /// any crazy technique that we want to, even if the expression has
476  /// side-effects.
477  bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
478
479  /// EvaluateAsInt - Return true if this is a constant which we can fold and
480  /// convert to an integer without side-effects, using any crazy technique that
481  /// we want to.
482  bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx) const;
483
484  /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
485  /// constant folded without side-effects, but discard the result.
486  bool isEvaluatable(const ASTContext &Ctx) const;
487
488  /// HasSideEffects - This routine returns true for all those expressions
489  /// which must be evaluated each time and must not be optimized away
490  /// or evaluated at compile time. Example is a function call, volatile
491  /// variable read.
492  bool HasSideEffects(const ASTContext &Ctx) const;
493
494  /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
495  /// integer. This must be called on an expression that constant folds to an
496  /// integer.
497  llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const;
498
499  /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
500  /// lvalue with link time known address, with no side-effects.
501  bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
502
503  /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
504  /// lvalue, even if the expression has side-effects.
505  bool EvaluateAsAnyLValue(EvalResult &Result, const ASTContext &Ctx) const;
506
507  /// \brief Enumeration used to describe the kind of Null pointer constant
508  /// returned from \c isNullPointerConstant().
509  enum NullPointerConstantKind {
510    /// \brief Expression is not a Null pointer constant.
511    NPCK_NotNull = 0,
512
513    /// \brief Expression is a Null pointer constant built from a zero integer.
514    NPCK_ZeroInteger,
515
516    /// \brief Expression is a C++0X nullptr.
517    NPCK_CXX0X_nullptr,
518
519    /// \brief Expression is a GNU-style __null constant.
520    NPCK_GNUNull
521  };
522
523  /// \brief Enumeration used to describe how \c isNullPointerConstant()
524  /// should cope with value-dependent expressions.
525  enum NullPointerConstantValueDependence {
526    /// \brief Specifies that the expression should never be value-dependent.
527    NPC_NeverValueDependent = 0,
528
529    /// \brief Specifies that a value-dependent expression of integral or
530    /// dependent type should be considered a null pointer constant.
531    NPC_ValueDependentIsNull,
532
533    /// \brief Specifies that a value-dependent expression should be considered
534    /// to never be a null pointer constant.
535    NPC_ValueDependentIsNotNull
536  };
537
538  /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
539  /// a Null pointer constant. The return value can further distinguish the
540  /// kind of NULL pointer constant that was detected.
541  NullPointerConstantKind isNullPointerConstant(
542      ASTContext &Ctx,
543      NullPointerConstantValueDependence NPC) const;
544
545  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
546  /// write barrier.
547  bool isOBJCGCCandidate(ASTContext &Ctx) const;
548
549  /// \brief Returns true if this expression is a bound member function.
550  bool isBoundMemberFunction(ASTContext &Ctx) const;
551
552  /// \brief Given an expression of bound-member type, find the type
553  /// of the member.  Returns null if this is an *overloaded* bound
554  /// member expression.
555  static QualType findBoundMemberType(const Expr *expr);
556
557  /// \brief Result type of CanThrow().
558  enum CanThrowResult {
559    CT_Cannot,
560    CT_Dependent,
561    CT_Can
562  };
563  /// \brief Test if this expression, if evaluated, might throw, according to
564  ///        the rules of C++ [expr.unary.noexcept].
565  CanThrowResult CanThrow(ASTContext &C) const;
566
567  /// IgnoreImpCasts - Skip past any implicit casts which might
568  /// surround this expression.  Only skips ImplicitCastExprs.
569  Expr *IgnoreImpCasts();
570
571  /// IgnoreImplicit - Skip past any implicit AST nodes which might
572  /// surround this expression.
573  Expr *IgnoreImplicit() { return cast<Expr>(Stmt::IgnoreImplicit()); }
574
575  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
576  ///  its subexpression.  If that subexpression is also a ParenExpr,
577  ///  then this method recursively returns its subexpression, and so forth.
578  ///  Otherwise, the method returns the current Expr.
579  Expr *IgnoreParens();
580
581  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
582  /// or CastExprs, returning their operand.
583  Expr *IgnoreParenCasts();
584
585  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip off any
586  /// ParenExpr or ImplicitCastExprs, returning their operand.
587  Expr *IgnoreParenImpCasts();
588
589  /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
590  /// call to a conversion operator, return the argument.
591  Expr *IgnoreConversionOperator();
592
593  const Expr *IgnoreConversionOperator() const {
594    return const_cast<Expr*>(this)->IgnoreConversionOperator();
595  }
596
597  const Expr *IgnoreParenImpCasts() const {
598    return const_cast<Expr*>(this)->IgnoreParenImpCasts();
599  }
600
601  /// Ignore parentheses and lvalue casts.  Strip off any ParenExpr and
602  /// CastExprs that represent lvalue casts, returning their operand.
603  Expr *IgnoreParenLValueCasts();
604
605  const Expr *IgnoreParenLValueCasts() const {
606    return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
607  }
608
609  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
610  /// value (including ptr->int casts of the same size).  Strip off any
611  /// ParenExpr or CastExprs, returning their operand.
612  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
613
614  /// \brief Determine whether this expression is a default function argument.
615  ///
616  /// Default arguments are implicitly generated in the abstract syntax tree
617  /// by semantic analysis for function calls, object constructions, etc. in
618  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
619  /// this routine also looks through any implicit casts to determine whether
620  /// the expression is a default argument.
621  bool isDefaultArgument() const;
622
623  /// \brief Determine whether the result of this expression is a
624  /// temporary object of the given class type.
625  bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
626
627  /// \brief Whether this expression is an implicit reference to 'this' in C++.
628  bool isImplicitCXXThis() const;
629
630  const Expr *IgnoreImpCasts() const {
631    return const_cast<Expr*>(this)->IgnoreImpCasts();
632  }
633  const Expr *IgnoreParens() const {
634    return const_cast<Expr*>(this)->IgnoreParens();
635  }
636  const Expr *IgnoreParenCasts() const {
637    return const_cast<Expr*>(this)->IgnoreParenCasts();
638  }
639  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
640    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
641  }
642
643  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
644  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
645
646  static bool classof(const Stmt *T) {
647    return T->getStmtClass() >= firstExprConstant &&
648           T->getStmtClass() <= lastExprConstant;
649  }
650  static bool classof(const Expr *) { return true; }
651};
652
653
654//===----------------------------------------------------------------------===//
655// Primary Expressions.
656//===----------------------------------------------------------------------===//
657
658/// OpaqueValueExpr - An expression referring to an opaque object of a
659/// fixed type and value class.  These don't correspond to concrete
660/// syntax; instead they're used to express operations (usually copy
661/// operations) on values whose source is generally obvious from
662/// context.
663class OpaqueValueExpr : public Expr {
664  friend class ASTStmtReader;
665  Expr *SourceExpr;
666  SourceLocation Loc;
667
668public:
669  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
670                  ExprObjectKind OK = OK_Ordinary)
671    : Expr(OpaqueValueExprClass, T, VK, OK,
672           T->isDependentType(), T->isDependentType(),
673           T->isInstantiationDependentType(),
674           false),
675      SourceExpr(0), Loc(Loc) {
676  }
677
678  /// Given an expression which invokes a copy constructor --- i.e.  a
679  /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
680  /// find the OpaqueValueExpr that's the source of the construction.
681  static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
682
683  explicit OpaqueValueExpr(EmptyShell Empty)
684    : Expr(OpaqueValueExprClass, Empty) { }
685
686  /// \brief Retrieve the location of this expression.
687  SourceLocation getLocation() const { return Loc; }
688
689  SourceRange getSourceRange() const {
690    if (SourceExpr) return SourceExpr->getSourceRange();
691    return Loc;
692  }
693  SourceLocation getExprLoc() const {
694    if (SourceExpr) return SourceExpr->getExprLoc();
695    return Loc;
696  }
697
698  child_range children() { return child_range(); }
699
700  /// The source expression of an opaque value expression is the
701  /// expression which originally generated the value.  This is
702  /// provided as a convenience for analyses that don't wish to
703  /// precisely model the execution behavior of the program.
704  ///
705  /// The source expression is typically set when building the
706  /// expression which binds the opaque value expression in the first
707  /// place.
708  Expr *getSourceExpr() const { return SourceExpr; }
709  void setSourceExpr(Expr *e) { SourceExpr = e; }
710
711  static bool classof(const Stmt *T) {
712    return T->getStmtClass() == OpaqueValueExprClass;
713  }
714  static bool classof(const OpaqueValueExpr *) { return true; }
715};
716
717/// \brief A reference to a declared variable, function, enum, etc.
718/// [C99 6.5.1p2]
719///
720/// This encodes all the information about how a declaration is referenced
721/// within an expression.
722///
723/// There are several optional constructs attached to DeclRefExprs only when
724/// they apply in order to conserve memory. These are laid out past the end of
725/// the object, and flags in the DeclRefExprBitfield track whether they exist:
726///
727///   DeclRefExprBits.HasQualifier:
728///       Specifies when this declaration reference expression has a C++
729///       nested-name-specifier.
730///   DeclRefExprBits.HasFoundDecl:
731///       Specifies when this declaration reference expression has a record of
732///       a NamedDecl (different from the referenced ValueDecl) which was found
733///       during name lookup and/or overload resolution.
734///   DeclRefExprBits.HasExplicitTemplateArgs:
735///       Specifies when this declaration reference expression has an explicit
736///       C++ template argument list.
737class DeclRefExpr : public Expr {
738  /// \brief The declaration that we are referencing.
739  ValueDecl *D;
740
741  /// \brief The location of the declaration name itself.
742  SourceLocation Loc;
743
744  /// \brief Provides source/type location info for the declaration name
745  /// embedded in D.
746  DeclarationNameLoc DNLoc;
747
748  /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
749  NestedNameSpecifierLoc &getInternalQualifierLoc() {
750    assert(hasQualifier());
751    return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
752  }
753
754  /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
755  const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
756    return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
757  }
758
759  /// \brief Test whether there is a distinct FoundDecl attached to the end of
760  /// this DRE.
761  bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
762
763  /// \brief Helper to retrieve the optional NamedDecl through which this
764  /// reference occured.
765  NamedDecl *&getInternalFoundDecl() {
766    assert(hasFoundDecl());
767    if (hasQualifier())
768      return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
769    return *reinterpret_cast<NamedDecl **>(this + 1);
770  }
771
772  /// \brief Helper to retrieve the optional NamedDecl through which this
773  /// reference occured.
774  NamedDecl *getInternalFoundDecl() const {
775    return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
776  }
777
778  DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
779              ValueDecl *D, const DeclarationNameInfo &NameInfo,
780              NamedDecl *FoundD,
781              const TemplateArgumentListInfo *TemplateArgs,
782              QualType T, ExprValueKind VK);
783
784  /// \brief Construct an empty declaration reference expression.
785  explicit DeclRefExpr(EmptyShell Empty)
786    : Expr(DeclRefExprClass, Empty) { }
787
788  /// \brief Computes the type- and value-dependence flags for this
789  /// declaration reference expression.
790  void computeDependence();
791
792public:
793  DeclRefExpr(ValueDecl *D, QualType T, ExprValueKind VK, SourceLocation L,
794              const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
795    : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
796      D(D), Loc(L), DNLoc(LocInfo) {
797    DeclRefExprBits.HasQualifier = 0;
798    DeclRefExprBits.HasExplicitTemplateArgs = 0;
799    DeclRefExprBits.HasFoundDecl = 0;
800    DeclRefExprBits.HadMultipleCandidates = 0;
801    computeDependence();
802  }
803
804  static DeclRefExpr *Create(ASTContext &Context,
805                             NestedNameSpecifierLoc QualifierLoc,
806                             ValueDecl *D,
807                             SourceLocation NameLoc,
808                             QualType T, ExprValueKind VK,
809                             NamedDecl *FoundD = 0,
810                             const TemplateArgumentListInfo *TemplateArgs = 0);
811
812  static DeclRefExpr *Create(ASTContext &Context,
813                             NestedNameSpecifierLoc QualifierLoc,
814                             ValueDecl *D,
815                             const DeclarationNameInfo &NameInfo,
816                             QualType T, ExprValueKind VK,
817                             NamedDecl *FoundD = 0,
818                             const TemplateArgumentListInfo *TemplateArgs = 0);
819
820  /// \brief Construct an empty declaration reference expression.
821  static DeclRefExpr *CreateEmpty(ASTContext &Context,
822                                  bool HasQualifier,
823                                  bool HasFoundDecl,
824                                  bool HasExplicitTemplateArgs,
825                                  unsigned NumTemplateArgs);
826
827  ValueDecl *getDecl() { return D; }
828  const ValueDecl *getDecl() const { return D; }
829  void setDecl(ValueDecl *NewD) { D = NewD; }
830
831  DeclarationNameInfo getNameInfo() const {
832    return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
833  }
834
835  SourceLocation getLocation() const { return Loc; }
836  void setLocation(SourceLocation L) { Loc = L; }
837  SourceRange getSourceRange() const;
838
839  /// \brief Determine whether this declaration reference was preceded by a
840  /// C++ nested-name-specifier, e.g., \c N::foo.
841  bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
842
843  /// \brief If the name was qualified, retrieves the nested-name-specifier
844  /// that precedes the name. Otherwise, returns NULL.
845  NestedNameSpecifier *getQualifier() const {
846    if (!hasQualifier())
847      return 0;
848
849    return getInternalQualifierLoc().getNestedNameSpecifier();
850  }
851
852  /// \brief If the name was qualified, retrieves the nested-name-specifier
853  /// that precedes the name, with source-location information.
854  NestedNameSpecifierLoc getQualifierLoc() const {
855    if (!hasQualifier())
856      return NestedNameSpecifierLoc();
857
858    return getInternalQualifierLoc();
859  }
860
861  /// \brief Get the NamedDecl through which this reference occured.
862  ///
863  /// This Decl may be different from the ValueDecl actually referred to in the
864  /// presence of using declarations, etc. It always returns non-NULL, and may
865  /// simple return the ValueDecl when appropriate.
866  NamedDecl *getFoundDecl() {
867    return hasFoundDecl() ? getInternalFoundDecl() : D;
868  }
869
870  /// \brief Get the NamedDecl through which this reference occurred.
871  /// See non-const variant.
872  const NamedDecl *getFoundDecl() const {
873    return hasFoundDecl() ? getInternalFoundDecl() : D;
874  }
875
876  /// \brief Determines whether this declaration reference was followed by an
877  /// explict template argument list.
878  bool hasExplicitTemplateArgs() const {
879    return DeclRefExprBits.HasExplicitTemplateArgs;
880  }
881
882  /// \brief Retrieve the explicit template argument list that followed the
883  /// member template name.
884  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
885    assert(hasExplicitTemplateArgs());
886    if (hasFoundDecl())
887      return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
888        &getInternalFoundDecl() + 1);
889
890    if (hasQualifier())
891      return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
892        &getInternalQualifierLoc() + 1);
893
894    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
895  }
896
897  /// \brief Retrieve the explicit template argument list that followed the
898  /// member template name.
899  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
900    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
901  }
902
903  /// \brief Retrieves the optional explicit template arguments.
904  /// This points to the same data as getExplicitTemplateArgs(), but
905  /// returns null if there are no explicit template arguments.
906  const ASTTemplateArgumentListInfo *getExplicitTemplateArgsOpt() const {
907    if (!hasExplicitTemplateArgs()) return 0;
908    return &getExplicitTemplateArgs();
909  }
910
911  /// \brief Copies the template arguments (if present) into the given
912  /// structure.
913  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
914    if (hasExplicitTemplateArgs())
915      getExplicitTemplateArgs().copyInto(List);
916  }
917
918  /// \brief Retrieve the location of the left angle bracket following the
919  /// member name ('<'), if any.
920  SourceLocation getLAngleLoc() const {
921    if (!hasExplicitTemplateArgs())
922      return SourceLocation();
923
924    return getExplicitTemplateArgs().LAngleLoc;
925  }
926
927  /// \brief Retrieve the template arguments provided as part of this
928  /// template-id.
929  const TemplateArgumentLoc *getTemplateArgs() const {
930    if (!hasExplicitTemplateArgs())
931      return 0;
932
933    return getExplicitTemplateArgs().getTemplateArgs();
934  }
935
936  /// \brief Retrieve the number of template arguments provided as part of this
937  /// template-id.
938  unsigned getNumTemplateArgs() const {
939    if (!hasExplicitTemplateArgs())
940      return 0;
941
942    return getExplicitTemplateArgs().NumTemplateArgs;
943  }
944
945  /// \brief Retrieve the location of the right angle bracket following the
946  /// template arguments ('>').
947  SourceLocation getRAngleLoc() const {
948    if (!hasExplicitTemplateArgs())
949      return SourceLocation();
950
951    return getExplicitTemplateArgs().RAngleLoc;
952  }
953
954  /// \brief Returns true if this expression refers to a function that
955  /// was resolved from an overloaded set having size greater than 1.
956  bool hadMultipleCandidates() const {
957    return DeclRefExprBits.HadMultipleCandidates;
958  }
959  /// \brief Sets the flag telling whether this expression refers to
960  /// a function that was resolved from an overloaded set having size
961  /// greater than 1.
962  void setHadMultipleCandidates(bool V = true) {
963    DeclRefExprBits.HadMultipleCandidates = V;
964  }
965
966  static bool classof(const Stmt *T) {
967    return T->getStmtClass() == DeclRefExprClass;
968  }
969  static bool classof(const DeclRefExpr *) { return true; }
970
971  // Iterators
972  child_range children() { return child_range(); }
973
974  friend class ASTStmtReader;
975  friend class ASTStmtWriter;
976};
977
978/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
979class PredefinedExpr : public Expr {
980public:
981  enum IdentType {
982    Func,
983    Function,
984    PrettyFunction,
985    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
986    /// 'virtual' keyword is omitted for virtual member functions.
987    PrettyFunctionNoVirtual
988  };
989
990private:
991  SourceLocation Loc;
992  IdentType Type;
993public:
994  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
995    : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
996           type->isDependentType(), type->isDependentType(),
997           type->isInstantiationDependentType(),
998           /*ContainsUnexpandedParameterPack=*/false),
999      Loc(l), Type(IT) {}
1000
1001  /// \brief Construct an empty predefined expression.
1002  explicit PredefinedExpr(EmptyShell Empty)
1003    : Expr(PredefinedExprClass, Empty) { }
1004
1005  IdentType getIdentType() const { return Type; }
1006  void setIdentType(IdentType IT) { Type = IT; }
1007
1008  SourceLocation getLocation() const { return Loc; }
1009  void setLocation(SourceLocation L) { Loc = L; }
1010
1011  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1012
1013  SourceRange getSourceRange() const { return SourceRange(Loc); }
1014
1015  static bool classof(const Stmt *T) {
1016    return T->getStmtClass() == PredefinedExprClass;
1017  }
1018  static bool classof(const PredefinedExpr *) { return true; }
1019
1020  // Iterators
1021  child_range children() { return child_range(); }
1022};
1023
1024/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1025/// leaking memory.
1026///
1027/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1028/// to represent these numbers.  Unfortunately, when we use a BumpPtrAllocator
1029/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1030/// the APFloat/APInt values will never get freed. APNumericStorage uses
1031/// ASTContext's allocator for memory allocation.
1032class APNumericStorage {
1033  unsigned BitWidth;
1034  union {
1035    uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
1036    uint64_t *pVal;  ///< Used to store the >64 bits integer value.
1037  };
1038
1039  bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1040
1041  APNumericStorage(const APNumericStorage&); // do not implement
1042  APNumericStorage& operator=(const APNumericStorage&); // do not implement
1043
1044protected:
1045  APNumericStorage() : BitWidth(0), VAL(0) { }
1046
1047  llvm::APInt getIntValue() const {
1048    unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1049    if (NumWords > 1)
1050      return llvm::APInt(BitWidth, NumWords, pVal);
1051    else
1052      return llvm::APInt(BitWidth, VAL);
1053  }
1054  void setIntValue(ASTContext &C, const llvm::APInt &Val);
1055};
1056
1057class APIntStorage : public APNumericStorage {
1058public:
1059  llvm::APInt getValue() const { return getIntValue(); }
1060  void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); }
1061};
1062
1063class APFloatStorage : public APNumericStorage {
1064public:
1065  llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); }
1066  void setValue(ASTContext &C, const llvm::APFloat &Val) {
1067    setIntValue(C, Val.bitcastToAPInt());
1068  }
1069};
1070
1071class IntegerLiteral : public Expr {
1072  APIntStorage Num;
1073  SourceLocation Loc;
1074
1075  /// \brief Construct an empty integer literal.
1076  explicit IntegerLiteral(EmptyShell Empty)
1077    : Expr(IntegerLiteralClass, Empty) { }
1078
1079public:
1080  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1081  // or UnsignedLongLongTy
1082  IntegerLiteral(ASTContext &C, const llvm::APInt &V,
1083                 QualType type, SourceLocation l)
1084    : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1085           false, false),
1086      Loc(l) {
1087    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
1088    assert(V.getBitWidth() == C.getIntWidth(type) &&
1089           "Integer type is not the correct size for constant.");
1090    setValue(C, V);
1091  }
1092
1093  /// \brief Returns a new integer literal with value 'V' and type 'type'.
1094  /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1095  /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1096  /// \param V - the value that the returned integer literal contains.
1097  static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V,
1098                                QualType type, SourceLocation l);
1099  /// \brief Returns a new empty integer literal.
1100  static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty);
1101
1102  llvm::APInt getValue() const { return Num.getValue(); }
1103  SourceRange getSourceRange() const { return SourceRange(Loc); }
1104
1105  /// \brief Retrieve the location of the literal.
1106  SourceLocation getLocation() const { return Loc; }
1107
1108  void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, Val); }
1109  void setLocation(SourceLocation Location) { Loc = Location; }
1110
1111  static bool classof(const Stmt *T) {
1112    return T->getStmtClass() == IntegerLiteralClass;
1113  }
1114  static bool classof(const IntegerLiteral *) { return true; }
1115
1116  // Iterators
1117  child_range children() { return child_range(); }
1118};
1119
1120class CharacterLiteral : public Expr {
1121public:
1122  enum CharacterKind {
1123    Ascii,
1124    Wide,
1125    UTF16,
1126    UTF32
1127  };
1128
1129private:
1130  unsigned Value;
1131  SourceLocation Loc;
1132  unsigned Kind : 2;
1133public:
1134  // type should be IntTy
1135  CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1136                   SourceLocation l)
1137    : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1138           false, false),
1139      Value(value), Loc(l), Kind(kind) {
1140  }
1141
1142  /// \brief Construct an empty character literal.
1143  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1144
1145  SourceLocation getLocation() const { return Loc; }
1146  CharacterKind getKind() const { return static_cast<CharacterKind>(Kind); }
1147
1148  SourceRange getSourceRange() const { return SourceRange(Loc); }
1149
1150  unsigned getValue() const { return Value; }
1151
1152  void setLocation(SourceLocation Location) { Loc = Location; }
1153  void setKind(CharacterKind kind) { Kind = kind; }
1154  void setValue(unsigned Val) { Value = Val; }
1155
1156  static bool classof(const Stmt *T) {
1157    return T->getStmtClass() == CharacterLiteralClass;
1158  }
1159  static bool classof(const CharacterLiteral *) { return true; }
1160
1161  // Iterators
1162  child_range children() { return child_range(); }
1163};
1164
1165class FloatingLiteral : public Expr {
1166  APFloatStorage Num;
1167  bool IsExact : 1;
1168  SourceLocation Loc;
1169
1170  FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact,
1171                  QualType Type, SourceLocation L)
1172    : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
1173           false, false),
1174      IsExact(isexact), Loc(L) {
1175    setValue(C, V);
1176  }
1177
1178  /// \brief Construct an empty floating-point literal.
1179  explicit FloatingLiteral(EmptyShell Empty)
1180    : Expr(FloatingLiteralClass, Empty), IsExact(false) { }
1181
1182public:
1183  static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V,
1184                                 bool isexact, QualType Type, SourceLocation L);
1185  static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty);
1186
1187  llvm::APFloat getValue() const { return Num.getValue(); }
1188  void setValue(ASTContext &C, const llvm::APFloat &Val) {
1189    Num.setValue(C, Val);
1190  }
1191
1192  bool isExact() const { return IsExact; }
1193  void setExact(bool E) { IsExact = E; }
1194
1195  /// getValueAsApproximateDouble - This returns the value as an inaccurate
1196  /// double.  Note that this may cause loss of precision, but is useful for
1197  /// debugging dumps, etc.
1198  double getValueAsApproximateDouble() const;
1199
1200  SourceLocation getLocation() const { return Loc; }
1201  void setLocation(SourceLocation L) { Loc = L; }
1202
1203  SourceRange getSourceRange() const { return SourceRange(Loc); }
1204
1205  static bool classof(const Stmt *T) {
1206    return T->getStmtClass() == FloatingLiteralClass;
1207  }
1208  static bool classof(const FloatingLiteral *) { return true; }
1209
1210  // Iterators
1211  child_range children() { return child_range(); }
1212};
1213
1214/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1215/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
1216/// IntegerLiteral classes.  Instances of this class always have a Complex type
1217/// whose element type matches the subexpression.
1218///
1219class ImaginaryLiteral : public Expr {
1220  Stmt *Val;
1221public:
1222  ImaginaryLiteral(Expr *val, QualType Ty)
1223    : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1224           false, false),
1225      Val(val) {}
1226
1227  /// \brief Build an empty imaginary literal.
1228  explicit ImaginaryLiteral(EmptyShell Empty)
1229    : Expr(ImaginaryLiteralClass, Empty) { }
1230
1231  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1232  Expr *getSubExpr() { return cast<Expr>(Val); }
1233  void setSubExpr(Expr *E) { Val = E; }
1234
1235  SourceRange getSourceRange() const { return Val->getSourceRange(); }
1236  static bool classof(const Stmt *T) {
1237    return T->getStmtClass() == ImaginaryLiteralClass;
1238  }
1239  static bool classof(const ImaginaryLiteral *) { return true; }
1240
1241  // Iterators
1242  child_range children() { return child_range(&Val, &Val+1); }
1243};
1244
1245/// StringLiteral - This represents a string literal expression, e.g. "foo"
1246/// or L"bar" (wide strings).  The actual string is returned by getStrData()
1247/// is NOT null-terminated, and the length of the string is determined by
1248/// calling getByteLength().  The C type for a string is always a
1249/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
1250/// not.
1251///
1252/// Note that strings in C can be formed by concatenation of multiple string
1253/// literal pptokens in translation phase #6.  This keeps track of the locations
1254/// of each of these pieces.
1255///
1256/// Strings in C can also be truncated and extended by assigning into arrays,
1257/// e.g. with constructs like:
1258///   char X[2] = "foobar";
1259/// In this case, getByteLength() will return 6, but the string literal will
1260/// have type "char[2]".
1261class StringLiteral : public Expr {
1262public:
1263  enum StringKind {
1264    Ascii,
1265    Wide,
1266    UTF8,
1267    UTF16,
1268    UTF32
1269  };
1270
1271private:
1272  friend class ASTStmtReader;
1273
1274  const char *StrData;
1275  unsigned ByteLength;
1276  unsigned NumConcatenated;
1277  unsigned Kind : 3;
1278  bool IsPascal : 1;
1279  SourceLocation TokLocs[1];
1280
1281  StringLiteral(QualType Ty) :
1282    Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1283         false) {}
1284
1285public:
1286  /// This is the "fully general" constructor that allows representation of
1287  /// strings formed from multiple concatenated tokens.
1288  static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1289                               bool Pascal, QualType Ty,
1290                               const SourceLocation *Loc, unsigned NumStrs);
1291
1292  /// Simple constructor for string literals made from one token.
1293  static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1294                               bool Pascal, QualType Ty,
1295                               SourceLocation Loc) {
1296    return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1297  }
1298
1299  /// \brief Construct an empty string literal.
1300  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1301
1302  StringRef getString() const {
1303    return StringRef(StrData, ByteLength);
1304  }
1305
1306  unsigned getByteLength() const { return ByteLength; }
1307
1308  /// \brief Sets the string data to the given string data.
1309  void setString(ASTContext &C, StringRef Str);
1310
1311  StringKind getKind() const { return static_cast<StringKind>(Kind); }
1312  bool isAscii() const { return Kind == Ascii; }
1313  bool isWide() const { return Kind == Wide; }
1314  bool isUTF8() const { return Kind == UTF8; }
1315  bool isUTF16() const { return Kind == UTF16; }
1316  bool isUTF32() const { return Kind == UTF32; }
1317  bool isPascal() const { return IsPascal; }
1318
1319  bool containsNonAsciiOrNull() const {
1320    StringRef Str = getString();
1321    for (unsigned i = 0, e = Str.size(); i != e; ++i)
1322      if (!isascii(Str[i]) || !Str[i])
1323        return true;
1324    return false;
1325  }
1326  /// getNumConcatenated - Get the number of string literal tokens that were
1327  /// concatenated in translation phase #6 to form this string literal.
1328  unsigned getNumConcatenated() const { return NumConcatenated; }
1329
1330  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1331    assert(TokNum < NumConcatenated && "Invalid tok number");
1332    return TokLocs[TokNum];
1333  }
1334  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1335    assert(TokNum < NumConcatenated && "Invalid tok number");
1336    TokLocs[TokNum] = L;
1337  }
1338
1339  /// getLocationOfByte - Return a source location that points to the specified
1340  /// byte of this string literal.
1341  ///
1342  /// Strings are amazingly complex.  They can be formed from multiple tokens
1343  /// and can have escape sequences in them in addition to the usual trigraph
1344  /// and escaped newline business.  This routine handles this complexity.
1345  ///
1346  SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1347                                   const LangOptions &Features,
1348                                   const TargetInfo &Target) const;
1349
1350  typedef const SourceLocation *tokloc_iterator;
1351  tokloc_iterator tokloc_begin() const { return TokLocs; }
1352  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1353
1354  SourceRange getSourceRange() const {
1355    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
1356  }
1357  static bool classof(const Stmt *T) {
1358    return T->getStmtClass() == StringLiteralClass;
1359  }
1360  static bool classof(const StringLiteral *) { return true; }
1361
1362  // Iterators
1363  child_range children() { return child_range(); }
1364};
1365
1366/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
1367/// AST node is only formed if full location information is requested.
1368class ParenExpr : public Expr {
1369  SourceLocation L, R;
1370  Stmt *Val;
1371public:
1372  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1373    : Expr(ParenExprClass, val->getType(),
1374           val->getValueKind(), val->getObjectKind(),
1375           val->isTypeDependent(), val->isValueDependent(),
1376           val->isInstantiationDependent(),
1377           val->containsUnexpandedParameterPack()),
1378      L(l), R(r), Val(val) {}
1379
1380  /// \brief Construct an empty parenthesized expression.
1381  explicit ParenExpr(EmptyShell Empty)
1382    : Expr(ParenExprClass, Empty) { }
1383
1384  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1385  Expr *getSubExpr() { return cast<Expr>(Val); }
1386  void setSubExpr(Expr *E) { Val = E; }
1387
1388  SourceRange getSourceRange() const { return SourceRange(L, R); }
1389
1390  /// \brief Get the location of the left parentheses '('.
1391  SourceLocation getLParen() const { return L; }
1392  void setLParen(SourceLocation Loc) { L = Loc; }
1393
1394  /// \brief Get the location of the right parentheses ')'.
1395  SourceLocation getRParen() const { return R; }
1396  void setRParen(SourceLocation Loc) { R = Loc; }
1397
1398  static bool classof(const Stmt *T) {
1399    return T->getStmtClass() == ParenExprClass;
1400  }
1401  static bool classof(const ParenExpr *) { return true; }
1402
1403  // Iterators
1404  child_range children() { return child_range(&Val, &Val+1); }
1405};
1406
1407
1408/// UnaryOperator - This represents the unary-expression's (except sizeof and
1409/// alignof), the postinc/postdec operators from postfix-expression, and various
1410/// extensions.
1411///
1412/// Notes on various nodes:
1413///
1414/// Real/Imag - These return the real/imag part of a complex operand.  If
1415///   applied to a non-complex value, the former returns its operand and the
1416///   later returns zero in the type of the operand.
1417///
1418class UnaryOperator : public Expr {
1419public:
1420  typedef UnaryOperatorKind Opcode;
1421
1422private:
1423  unsigned Opc : 5;
1424  SourceLocation Loc;
1425  Stmt *Val;
1426public:
1427
1428  UnaryOperator(Expr *input, Opcode opc, QualType type,
1429                ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1430    : Expr(UnaryOperatorClass, type, VK, OK,
1431           input->isTypeDependent() || type->isDependentType(),
1432           input->isValueDependent(),
1433           (input->isInstantiationDependent() ||
1434            type->isInstantiationDependentType()),
1435           input->containsUnexpandedParameterPack()),
1436      Opc(opc), Loc(l), Val(input) {}
1437
1438  /// \brief Build an empty unary operator.
1439  explicit UnaryOperator(EmptyShell Empty)
1440    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1441
1442  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1443  void setOpcode(Opcode O) { Opc = O; }
1444
1445  Expr *getSubExpr() const { return cast<Expr>(Val); }
1446  void setSubExpr(Expr *E) { Val = E; }
1447
1448  /// getOperatorLoc - Return the location of the operator.
1449  SourceLocation getOperatorLoc() const { return Loc; }
1450  void setOperatorLoc(SourceLocation L) { Loc = L; }
1451
1452  /// isPostfix - Return true if this is a postfix operation, like x++.
1453  static bool isPostfix(Opcode Op) {
1454    return Op == UO_PostInc || Op == UO_PostDec;
1455  }
1456
1457  /// isPrefix - Return true if this is a prefix operation, like --x.
1458  static bool isPrefix(Opcode Op) {
1459    return Op == UO_PreInc || Op == UO_PreDec;
1460  }
1461
1462  bool isPrefix() const { return isPrefix(getOpcode()); }
1463  bool isPostfix() const { return isPostfix(getOpcode()); }
1464
1465  static bool isIncrementOp(Opcode Op) {
1466    return Op == UO_PreInc || Op == UO_PostInc;
1467  }
1468  bool isIncrementOp() const {
1469    return isIncrementOp(getOpcode());
1470  }
1471
1472  static bool isDecrementOp(Opcode Op) {
1473    return Op == UO_PreDec || Op == UO_PostDec;
1474  }
1475  bool isDecrementOp() const {
1476    return isDecrementOp(getOpcode());
1477  }
1478
1479  static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1480  bool isIncrementDecrementOp() const {
1481    return isIncrementDecrementOp(getOpcode());
1482  }
1483
1484  static bool isArithmeticOp(Opcode Op) {
1485    return Op >= UO_Plus && Op <= UO_LNot;
1486  }
1487  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1488
1489  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1490  /// corresponds to, e.g. "sizeof" or "[pre]++"
1491  static const char *getOpcodeStr(Opcode Op);
1492
1493  /// \brief Retrieve the unary opcode that corresponds to the given
1494  /// overloaded operator.
1495  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1496
1497  /// \brief Retrieve the overloaded operator kind that corresponds to
1498  /// the given unary opcode.
1499  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1500
1501  SourceRange getSourceRange() const {
1502    if (isPostfix())
1503      return SourceRange(Val->getLocStart(), Loc);
1504    else
1505      return SourceRange(Loc, Val->getLocEnd());
1506  }
1507  SourceLocation getExprLoc() const { return Loc; }
1508
1509  static bool classof(const Stmt *T) {
1510    return T->getStmtClass() == UnaryOperatorClass;
1511  }
1512  static bool classof(const UnaryOperator *) { return true; }
1513
1514  // Iterators
1515  child_range children() { return child_range(&Val, &Val+1); }
1516};
1517
1518/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1519/// offsetof(record-type, member-designator). For example, given:
1520/// @code
1521/// struct S {
1522///   float f;
1523///   double d;
1524/// };
1525/// struct T {
1526///   int i;
1527///   struct S s[10];
1528/// };
1529/// @endcode
1530/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1531
1532class OffsetOfExpr : public Expr {
1533public:
1534  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1535  class OffsetOfNode {
1536  public:
1537    /// \brief The kind of offsetof node we have.
1538    enum Kind {
1539      /// \brief An index into an array.
1540      Array = 0x00,
1541      /// \brief A field.
1542      Field = 0x01,
1543      /// \brief A field in a dependent type, known only by its name.
1544      Identifier = 0x02,
1545      /// \brief An implicit indirection through a C++ base class, when the
1546      /// field found is in a base class.
1547      Base = 0x03
1548    };
1549
1550  private:
1551    enum { MaskBits = 2, Mask = 0x03 };
1552
1553    /// \brief The source range that covers this part of the designator.
1554    SourceRange Range;
1555
1556    /// \brief The data describing the designator, which comes in three
1557    /// different forms, depending on the lower two bits.
1558    ///   - An unsigned index into the array of Expr*'s stored after this node
1559    ///     in memory, for [constant-expression] designators.
1560    ///   - A FieldDecl*, for references to a known field.
1561    ///   - An IdentifierInfo*, for references to a field with a given name
1562    ///     when the class type is dependent.
1563    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1564    ///     base class.
1565    uintptr_t Data;
1566
1567  public:
1568    /// \brief Create an offsetof node that refers to an array element.
1569    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1570                 SourceLocation RBracketLoc)
1571      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1572
1573    /// \brief Create an offsetof node that refers to a field.
1574    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1575                 SourceLocation NameLoc)
1576      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1577        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1578
1579    /// \brief Create an offsetof node that refers to an identifier.
1580    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1581                 SourceLocation NameLoc)
1582      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1583        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1584
1585    /// \brief Create an offsetof node that refers into a C++ base class.
1586    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1587      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1588
1589    /// \brief Determine what kind of offsetof node this is.
1590    Kind getKind() const {
1591      return static_cast<Kind>(Data & Mask);
1592    }
1593
1594    /// \brief For an array element node, returns the index into the array
1595    /// of expressions.
1596    unsigned getArrayExprIndex() const {
1597      assert(getKind() == Array);
1598      return Data >> 2;
1599    }
1600
1601    /// \brief For a field offsetof node, returns the field.
1602    FieldDecl *getField() const {
1603      assert(getKind() == Field);
1604      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1605    }
1606
1607    /// \brief For a field or identifier offsetof node, returns the name of
1608    /// the field.
1609    IdentifierInfo *getFieldName() const;
1610
1611    /// \brief For a base class node, returns the base specifier.
1612    CXXBaseSpecifier *getBase() const {
1613      assert(getKind() == Base);
1614      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1615    }
1616
1617    /// \brief Retrieve the source range that covers this offsetof node.
1618    ///
1619    /// For an array element node, the source range contains the locations of
1620    /// the square brackets. For a field or identifier node, the source range
1621    /// contains the location of the period (if there is one) and the
1622    /// identifier.
1623    SourceRange getSourceRange() const { return Range; }
1624  };
1625
1626private:
1627
1628  SourceLocation OperatorLoc, RParenLoc;
1629  // Base type;
1630  TypeSourceInfo *TSInfo;
1631  // Number of sub-components (i.e. instances of OffsetOfNode).
1632  unsigned NumComps;
1633  // Number of sub-expressions (i.e. array subscript expressions).
1634  unsigned NumExprs;
1635
1636  OffsetOfExpr(ASTContext &C, QualType type,
1637               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1638               OffsetOfNode* compsPtr, unsigned numComps,
1639               Expr** exprsPtr, unsigned numExprs,
1640               SourceLocation RParenLoc);
1641
1642  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1643    : Expr(OffsetOfExprClass, EmptyShell()),
1644      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1645
1646public:
1647
1648  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1649                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1650                              OffsetOfNode* compsPtr, unsigned numComps,
1651                              Expr** exprsPtr, unsigned numExprs,
1652                              SourceLocation RParenLoc);
1653
1654  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1655                                   unsigned NumComps, unsigned NumExprs);
1656
1657  /// getOperatorLoc - Return the location of the operator.
1658  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1659  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1660
1661  /// \brief Return the location of the right parentheses.
1662  SourceLocation getRParenLoc() const { return RParenLoc; }
1663  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1664
1665  TypeSourceInfo *getTypeSourceInfo() const {
1666    return TSInfo;
1667  }
1668  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1669    TSInfo = tsi;
1670  }
1671
1672  const OffsetOfNode &getComponent(unsigned Idx) const {
1673    assert(Idx < NumComps && "Subscript out of range");
1674    return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1675  }
1676
1677  void setComponent(unsigned Idx, OffsetOfNode ON) {
1678    assert(Idx < NumComps && "Subscript out of range");
1679    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1680  }
1681
1682  unsigned getNumComponents() const {
1683    return NumComps;
1684  }
1685
1686  Expr* getIndexExpr(unsigned Idx) {
1687    assert(Idx < NumExprs && "Subscript out of range");
1688    return reinterpret_cast<Expr **>(
1689                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1690  }
1691  const Expr *getIndexExpr(unsigned Idx) const {
1692    return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1693  }
1694
1695  void setIndexExpr(unsigned Idx, Expr* E) {
1696    assert(Idx < NumComps && "Subscript out of range");
1697    reinterpret_cast<Expr **>(
1698                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1699  }
1700
1701  unsigned getNumExpressions() const {
1702    return NumExprs;
1703  }
1704
1705  SourceRange getSourceRange() const {
1706    return SourceRange(OperatorLoc, RParenLoc);
1707  }
1708
1709  static bool classof(const Stmt *T) {
1710    return T->getStmtClass() == OffsetOfExprClass;
1711  }
1712
1713  static bool classof(const OffsetOfExpr *) { return true; }
1714
1715  // Iterators
1716  child_range children() {
1717    Stmt **begin =
1718      reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1719                               + NumComps);
1720    return child_range(begin, begin + NumExprs);
1721  }
1722};
1723
1724/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1725/// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
1726/// vec_step (OpenCL 1.1 6.11.12).
1727class UnaryExprOrTypeTraitExpr : public Expr {
1728  unsigned Kind : 2;
1729  bool isType : 1;    // true if operand is a type, false if an expression
1730  union {
1731    TypeSourceInfo *Ty;
1732    Stmt *Ex;
1733  } Argument;
1734  SourceLocation OpLoc, RParenLoc;
1735
1736public:
1737  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1738                           QualType resultType, SourceLocation op,
1739                           SourceLocation rp) :
1740      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1741           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1742           // Value-dependent if the argument is type-dependent.
1743           TInfo->getType()->isDependentType(),
1744           TInfo->getType()->isInstantiationDependentType(),
1745           TInfo->getType()->containsUnexpandedParameterPack()),
1746      Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) {
1747    Argument.Ty = TInfo;
1748  }
1749
1750  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1751                           QualType resultType, SourceLocation op,
1752                           SourceLocation rp) :
1753      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1754           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1755           // Value-dependent if the argument is type-dependent.
1756           E->isTypeDependent(),
1757           E->isInstantiationDependent(),
1758           E->containsUnexpandedParameterPack()),
1759      Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) {
1760    Argument.Ex = E;
1761  }
1762
1763  /// \brief Construct an empty sizeof/alignof expression.
1764  explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1765    : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1766
1767  UnaryExprOrTypeTrait getKind() const {
1768    return static_cast<UnaryExprOrTypeTrait>(Kind);
1769  }
1770  void setKind(UnaryExprOrTypeTrait K) { Kind = K; }
1771
1772  bool isArgumentType() const { return isType; }
1773  QualType getArgumentType() const {
1774    return getArgumentTypeInfo()->getType();
1775  }
1776  TypeSourceInfo *getArgumentTypeInfo() const {
1777    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1778    return Argument.Ty;
1779  }
1780  Expr *getArgumentExpr() {
1781    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1782    return static_cast<Expr*>(Argument.Ex);
1783  }
1784  const Expr *getArgumentExpr() const {
1785    return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
1786  }
1787
1788  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1789  void setArgument(TypeSourceInfo *TInfo) {
1790    Argument.Ty = TInfo;
1791    isType = true;
1792  }
1793
1794  /// Gets the argument type, or the type of the argument expression, whichever
1795  /// is appropriate.
1796  QualType getTypeOfArgument() const {
1797    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1798  }
1799
1800  SourceLocation getOperatorLoc() const { return OpLoc; }
1801  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1802
1803  SourceLocation getRParenLoc() const { return RParenLoc; }
1804  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1805
1806  SourceRange getSourceRange() const {
1807    return SourceRange(OpLoc, RParenLoc);
1808  }
1809
1810  static bool classof(const Stmt *T) {
1811    return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
1812  }
1813  static bool classof(const UnaryExprOrTypeTraitExpr *) { return true; }
1814
1815  // Iterators
1816  child_range children();
1817};
1818
1819//===----------------------------------------------------------------------===//
1820// Postfix Operators.
1821//===----------------------------------------------------------------------===//
1822
1823/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1824class ArraySubscriptExpr : public Expr {
1825  enum { LHS, RHS, END_EXPR=2 };
1826  Stmt* SubExprs[END_EXPR];
1827  SourceLocation RBracketLoc;
1828public:
1829  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1830                     ExprValueKind VK, ExprObjectKind OK,
1831                     SourceLocation rbracketloc)
1832  : Expr(ArraySubscriptExprClass, t, VK, OK,
1833         lhs->isTypeDependent() || rhs->isTypeDependent(),
1834         lhs->isValueDependent() || rhs->isValueDependent(),
1835         (lhs->isInstantiationDependent() ||
1836          rhs->isInstantiationDependent()),
1837         (lhs->containsUnexpandedParameterPack() ||
1838          rhs->containsUnexpandedParameterPack())),
1839    RBracketLoc(rbracketloc) {
1840    SubExprs[LHS] = lhs;
1841    SubExprs[RHS] = rhs;
1842  }
1843
1844  /// \brief Create an empty array subscript expression.
1845  explicit ArraySubscriptExpr(EmptyShell Shell)
1846    : Expr(ArraySubscriptExprClass, Shell) { }
1847
1848  /// An array access can be written A[4] or 4[A] (both are equivalent).
1849  /// - getBase() and getIdx() always present the normalized view: A[4].
1850  ///    In this case getBase() returns "A" and getIdx() returns "4".
1851  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1852  ///    4[A] getLHS() returns "4".
1853  /// Note: Because vector element access is also written A[4] we must
1854  /// predicate the format conversion in getBase and getIdx only on the
1855  /// the type of the RHS, as it is possible for the LHS to be a vector of
1856  /// integer type
1857  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1858  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1859  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1860
1861  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1862  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1863  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1864
1865  Expr *getBase() {
1866    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1867  }
1868
1869  const Expr *getBase() const {
1870    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1871  }
1872
1873  Expr *getIdx() {
1874    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1875  }
1876
1877  const Expr *getIdx() const {
1878    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1879  }
1880
1881  SourceRange getSourceRange() const {
1882    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1883  }
1884
1885  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1886  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1887
1888  SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1889
1890  static bool classof(const Stmt *T) {
1891    return T->getStmtClass() == ArraySubscriptExprClass;
1892  }
1893  static bool classof(const ArraySubscriptExpr *) { return true; }
1894
1895  // Iterators
1896  child_range children() {
1897    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
1898  }
1899};
1900
1901
1902/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1903/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1904/// while its subclasses may represent alternative syntax that (semantically)
1905/// results in a function call. For example, CXXOperatorCallExpr is
1906/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1907/// "str1 + str2" to resolve to a function call.
1908class CallExpr : public Expr {
1909  enum { FN=0, PREARGS_START=1 };
1910  Stmt **SubExprs;
1911  unsigned NumArgs;
1912  SourceLocation RParenLoc;
1913
1914protected:
1915  // These versions of the constructor are for derived classes.
1916  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
1917           Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
1918           SourceLocation rparenloc);
1919  CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty);
1920
1921  Stmt *getPreArg(unsigned i) {
1922    assert(i < getNumPreArgs() && "Prearg access out of range!");
1923    return SubExprs[PREARGS_START+i];
1924  }
1925  const Stmt *getPreArg(unsigned i) const {
1926    assert(i < getNumPreArgs() && "Prearg access out of range!");
1927    return SubExprs[PREARGS_START+i];
1928  }
1929  void setPreArg(unsigned i, Stmt *PreArg) {
1930    assert(i < getNumPreArgs() && "Prearg access out of range!");
1931    SubExprs[PREARGS_START+i] = PreArg;
1932  }
1933
1934  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
1935
1936public:
1937  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1938           ExprValueKind VK, SourceLocation rparenloc);
1939
1940  /// \brief Build an empty call expression.
1941  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1942
1943  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1944  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1945  void setCallee(Expr *F) { SubExprs[FN] = F; }
1946
1947  Decl *getCalleeDecl();
1948  const Decl *getCalleeDecl() const {
1949    return const_cast<CallExpr*>(this)->getCalleeDecl();
1950  }
1951
1952  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1953  FunctionDecl *getDirectCallee();
1954  const FunctionDecl *getDirectCallee() const {
1955    return const_cast<CallExpr*>(this)->getDirectCallee();
1956  }
1957
1958  /// getNumArgs - Return the number of actual arguments to this call.
1959  ///
1960  unsigned getNumArgs() const { return NumArgs; }
1961
1962  /// \brief Retrieve the call arguments.
1963  Expr **getArgs() {
1964    return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
1965  }
1966  const Expr *const *getArgs() const {
1967    return const_cast<CallExpr*>(this)->getArgs();
1968  }
1969
1970  /// getArg - Return the specified argument.
1971  Expr *getArg(unsigned Arg) {
1972    assert(Arg < NumArgs && "Arg access out of range!");
1973    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1974  }
1975  const Expr *getArg(unsigned Arg) const {
1976    assert(Arg < NumArgs && "Arg access out of range!");
1977    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1978  }
1979
1980  /// setArg - Set the specified argument.
1981  void setArg(unsigned Arg, Expr *ArgExpr) {
1982    assert(Arg < NumArgs && "Arg access out of range!");
1983    SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
1984  }
1985
1986  /// setNumArgs - This changes the number of arguments present in this call.
1987  /// Any orphaned expressions are deleted by this, and any new operands are set
1988  /// to null.
1989  void setNumArgs(ASTContext& C, unsigned NumArgs);
1990
1991  typedef ExprIterator arg_iterator;
1992  typedef ConstExprIterator const_arg_iterator;
1993
1994  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
1995  arg_iterator arg_end() {
1996    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1997  }
1998  const_arg_iterator arg_begin() const {
1999    return SubExprs+PREARGS_START+getNumPreArgs();
2000  }
2001  const_arg_iterator arg_end() const {
2002    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2003  }
2004
2005  /// getNumCommas - Return the number of commas that must have been present in
2006  /// this function call.
2007  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2008
2009  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
2010  /// not, return 0.
2011  unsigned isBuiltinCall(const ASTContext &Context) const;
2012
2013  /// getCallReturnType - Get the return type of the call expr. This is not
2014  /// always the type of the expr itself, if the return type is a reference
2015  /// type.
2016  QualType getCallReturnType() const;
2017
2018  SourceLocation getRParenLoc() const { return RParenLoc; }
2019  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2020
2021  SourceRange getSourceRange() const;
2022
2023  static bool classof(const Stmt *T) {
2024    return T->getStmtClass() >= firstCallExprConstant &&
2025           T->getStmtClass() <= lastCallExprConstant;
2026  }
2027  static bool classof(const CallExpr *) { return true; }
2028
2029  // Iterators
2030  child_range children() {
2031    return child_range(&SubExprs[0],
2032                       &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2033  }
2034};
2035
2036/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
2037///
2038class MemberExpr : public Expr {
2039  /// Extra data stored in some member expressions.
2040  struct MemberNameQualifier {
2041    /// \brief The nested-name-specifier that qualifies the name, including
2042    /// source-location information.
2043    NestedNameSpecifierLoc QualifierLoc;
2044
2045    /// \brief The DeclAccessPair through which the MemberDecl was found due to
2046    /// name qualifiers.
2047    DeclAccessPair FoundDecl;
2048  };
2049
2050  /// Base - the expression for the base pointer or structure references.  In
2051  /// X.F, this is "X".
2052  Stmt *Base;
2053
2054  /// MemberDecl - This is the decl being referenced by the field/member name.
2055  /// In X.F, this is the decl referenced by F.
2056  ValueDecl *MemberDecl;
2057
2058  /// MemberLoc - This is the location of the member name.
2059  SourceLocation MemberLoc;
2060
2061  /// MemberDNLoc - Provides source/type location info for the
2062  /// declaration name embedded in MemberDecl.
2063  DeclarationNameLoc MemberDNLoc;
2064
2065  /// IsArrow - True if this is "X->F", false if this is "X.F".
2066  bool IsArrow : 1;
2067
2068  /// \brief True if this member expression used a nested-name-specifier to
2069  /// refer to the member, e.g., "x->Base::f", or found its member via a using
2070  /// declaration.  When true, a MemberNameQualifier
2071  /// structure is allocated immediately after the MemberExpr.
2072  bool HasQualifierOrFoundDecl : 1;
2073
2074  /// \brief True if this member expression specified a template argument list
2075  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
2076  /// structure (and its TemplateArguments) are allocated immediately after
2077  /// the MemberExpr or, if the member expression also has a qualifier, after
2078  /// the MemberNameQualifier structure.
2079  bool HasExplicitTemplateArgumentList : 1;
2080
2081  /// \brief True if this member expression refers to a method that
2082  /// was resolved from an overloaded set having size greater than 1.
2083  bool HadMultipleCandidates : 1;
2084
2085  /// \brief Retrieve the qualifier that preceded the member name, if any.
2086  MemberNameQualifier *getMemberQualifier() {
2087    assert(HasQualifierOrFoundDecl);
2088    return reinterpret_cast<MemberNameQualifier *> (this + 1);
2089  }
2090
2091  /// \brief Retrieve the qualifier that preceded the member name, if any.
2092  const MemberNameQualifier *getMemberQualifier() const {
2093    return const_cast<MemberExpr *>(this)->getMemberQualifier();
2094  }
2095
2096public:
2097  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2098             const DeclarationNameInfo &NameInfo, QualType ty,
2099             ExprValueKind VK, ExprObjectKind OK)
2100    : Expr(MemberExprClass, ty, VK, OK,
2101           base->isTypeDependent(),
2102           base->isValueDependent(),
2103           base->isInstantiationDependent(),
2104           base->containsUnexpandedParameterPack()),
2105      Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
2106      MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
2107      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false),
2108      HadMultipleCandidates(false) {
2109    assert(memberdecl->getDeclName() == NameInfo.getName());
2110  }
2111
2112  // NOTE: this constructor should be used only when it is known that
2113  // the member name can not provide additional syntactic info
2114  // (i.e., source locations for C++ operator names or type source info
2115  // for constructors, destructors and conversion oeprators).
2116  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2117             SourceLocation l, QualType ty,
2118             ExprValueKind VK, ExprObjectKind OK)
2119    : Expr(MemberExprClass, ty, VK, OK,
2120           base->isTypeDependent(), base->isValueDependent(),
2121           base->isInstantiationDependent(),
2122           base->containsUnexpandedParameterPack()),
2123      Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
2124      IsArrow(isarrow),
2125      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false),
2126      HadMultipleCandidates(false) {}
2127
2128  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
2129                            NestedNameSpecifierLoc QualifierLoc,
2130                            ValueDecl *memberdecl, DeclAccessPair founddecl,
2131                            DeclarationNameInfo MemberNameInfo,
2132                            const TemplateArgumentListInfo *targs,
2133                            QualType ty, ExprValueKind VK, ExprObjectKind OK);
2134
2135  void setBase(Expr *E) { Base = E; }
2136  Expr *getBase() const { return cast<Expr>(Base); }
2137
2138  /// \brief Retrieve the member declaration to which this expression refers.
2139  ///
2140  /// The returned declaration will either be a FieldDecl or (in C++)
2141  /// a CXXMethodDecl.
2142  ValueDecl *getMemberDecl() const { return MemberDecl; }
2143  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2144
2145  /// \brief Retrieves the declaration found by lookup.
2146  DeclAccessPair getFoundDecl() const {
2147    if (!HasQualifierOrFoundDecl)
2148      return DeclAccessPair::make(getMemberDecl(),
2149                                  getMemberDecl()->getAccess());
2150    return getMemberQualifier()->FoundDecl;
2151  }
2152
2153  /// \brief Determines whether this member expression actually had
2154  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2155  /// x->Base::foo.
2156  bool hasQualifier() const { return getQualifier() != 0; }
2157
2158  /// \brief If the member name was qualified, retrieves the
2159  /// nested-name-specifier that precedes the member name. Otherwise, returns
2160  /// NULL.
2161  NestedNameSpecifier *getQualifier() const {
2162    if (!HasQualifierOrFoundDecl)
2163      return 0;
2164
2165    return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2166  }
2167
2168  /// \brief If the member name was qualified, retrieves the
2169  /// nested-name-specifier that precedes the member name, with source-location
2170  /// information.
2171  NestedNameSpecifierLoc getQualifierLoc() const {
2172    if (!hasQualifier())
2173      return NestedNameSpecifierLoc();
2174
2175    return getMemberQualifier()->QualifierLoc;
2176  }
2177
2178  /// \brief Determines whether this member expression actually had a C++
2179  /// template argument list explicitly specified, e.g., x.f<int>.
2180  bool hasExplicitTemplateArgs() const {
2181    return HasExplicitTemplateArgumentList;
2182  }
2183
2184  /// \brief Copies the template arguments (if present) into the given
2185  /// structure.
2186  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2187    if (hasExplicitTemplateArgs())
2188      getExplicitTemplateArgs().copyInto(List);
2189  }
2190
2191  /// \brief Retrieve the explicit template argument list that
2192  /// follow the member template name.  This must only be called on an
2193  /// expression with explicit template arguments.
2194  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2195    assert(HasExplicitTemplateArgumentList);
2196    if (!HasQualifierOrFoundDecl)
2197      return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
2198
2199    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
2200                                                      getMemberQualifier() + 1);
2201  }
2202
2203  /// \brief Retrieve the explicit template argument list that
2204  /// followed the member template name.  This must only be called on
2205  /// an expression with explicit template arguments.
2206  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2207    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2208  }
2209
2210  /// \brief Retrieves the optional explicit template arguments.
2211  /// This points to the same data as getExplicitTemplateArgs(), but
2212  /// returns null if there are no explicit template arguments.
2213  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2214    if (!hasExplicitTemplateArgs()) return 0;
2215    return &getExplicitTemplateArgs();
2216  }
2217
2218  /// \brief Retrieve the location of the left angle bracket following the
2219  /// member name ('<'), if any.
2220  SourceLocation getLAngleLoc() const {
2221    if (!HasExplicitTemplateArgumentList)
2222      return SourceLocation();
2223
2224    return getExplicitTemplateArgs().LAngleLoc;
2225  }
2226
2227  /// \brief Retrieve the template arguments provided as part of this
2228  /// template-id.
2229  const TemplateArgumentLoc *getTemplateArgs() const {
2230    if (!HasExplicitTemplateArgumentList)
2231      return 0;
2232
2233    return getExplicitTemplateArgs().getTemplateArgs();
2234  }
2235
2236  /// \brief Retrieve the number of template arguments provided as part of this
2237  /// template-id.
2238  unsigned getNumTemplateArgs() const {
2239    if (!HasExplicitTemplateArgumentList)
2240      return 0;
2241
2242    return getExplicitTemplateArgs().NumTemplateArgs;
2243  }
2244
2245  /// \brief Retrieve the location of the right angle bracket following the
2246  /// template arguments ('>').
2247  SourceLocation getRAngleLoc() const {
2248    if (!HasExplicitTemplateArgumentList)
2249      return SourceLocation();
2250
2251    return getExplicitTemplateArgs().RAngleLoc;
2252  }
2253
2254  /// \brief Retrieve the member declaration name info.
2255  DeclarationNameInfo getMemberNameInfo() const {
2256    return DeclarationNameInfo(MemberDecl->getDeclName(),
2257                               MemberLoc, MemberDNLoc);
2258  }
2259
2260  bool isArrow() const { return IsArrow; }
2261  void setArrow(bool A) { IsArrow = A; }
2262
2263  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2264  /// location of 'F'.
2265  SourceLocation getMemberLoc() const { return MemberLoc; }
2266  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2267
2268  SourceRange getSourceRange() const;
2269
2270  SourceLocation getExprLoc() const { return MemberLoc; }
2271
2272  /// \brief Determine whether the base of this explicit is implicit.
2273  bool isImplicitAccess() const {
2274    return getBase() && getBase()->isImplicitCXXThis();
2275  }
2276
2277  /// \brief Returns true if this member expression refers to a method that
2278  /// was resolved from an overloaded set having size greater than 1.
2279  bool hadMultipleCandidates() const {
2280    return HadMultipleCandidates;
2281  }
2282  /// \brief Sets the flag telling whether this expression refers to
2283  /// a method that was resolved from an overloaded set having size
2284  /// greater than 1.
2285  void setHadMultipleCandidates(bool V = true) {
2286    HadMultipleCandidates = V;
2287  }
2288
2289  static bool classof(const Stmt *T) {
2290    return T->getStmtClass() == MemberExprClass;
2291  }
2292  static bool classof(const MemberExpr *) { return true; }
2293
2294  // Iterators
2295  child_range children() { return child_range(&Base, &Base+1); }
2296
2297  friend class ASTReader;
2298  friend class ASTStmtWriter;
2299};
2300
2301/// CompoundLiteralExpr - [C99 6.5.2.5]
2302///
2303class CompoundLiteralExpr : public Expr {
2304  /// LParenLoc - If non-null, this is the location of the left paren in a
2305  /// compound literal like "(int){4}".  This can be null if this is a
2306  /// synthesized compound expression.
2307  SourceLocation LParenLoc;
2308
2309  /// The type as written.  This can be an incomplete array type, in
2310  /// which case the actual expression type will be different.
2311  TypeSourceInfo *TInfo;
2312  Stmt *Init;
2313  bool FileScope;
2314public:
2315  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2316                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2317    : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2318           tinfo->getType()->isDependentType(),
2319           init->isValueDependent(),
2320           (init->isInstantiationDependent() ||
2321            tinfo->getType()->isInstantiationDependentType()),
2322           init->containsUnexpandedParameterPack()),
2323      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
2324
2325  /// \brief Construct an empty compound literal.
2326  explicit CompoundLiteralExpr(EmptyShell Empty)
2327    : Expr(CompoundLiteralExprClass, Empty) { }
2328
2329  const Expr *getInitializer() const { return cast<Expr>(Init); }
2330  Expr *getInitializer() { return cast<Expr>(Init); }
2331  void setInitializer(Expr *E) { Init = E; }
2332
2333  bool isFileScope() const { return FileScope; }
2334  void setFileScope(bool FS) { FileScope = FS; }
2335
2336  SourceLocation getLParenLoc() const { return LParenLoc; }
2337  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2338
2339  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
2340  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
2341
2342  SourceRange getSourceRange() const {
2343    // FIXME: Init should never be null.
2344    if (!Init)
2345      return SourceRange();
2346    if (LParenLoc.isInvalid())
2347      return Init->getSourceRange();
2348    return SourceRange(LParenLoc, Init->getLocEnd());
2349  }
2350
2351  static bool classof(const Stmt *T) {
2352    return T->getStmtClass() == CompoundLiteralExprClass;
2353  }
2354  static bool classof(const CompoundLiteralExpr *) { return true; }
2355
2356  // Iterators
2357  child_range children() { return child_range(&Init, &Init+1); }
2358};
2359
2360/// CastExpr - Base class for type casts, including both implicit
2361/// casts (ImplicitCastExpr) and explicit casts that have some
2362/// representation in the source code (ExplicitCastExpr's derived
2363/// classes).
2364class CastExpr : public Expr {
2365public:
2366  typedef clang::CastKind CastKind;
2367
2368private:
2369  Stmt *Op;
2370
2371  void CheckCastConsistency() const;
2372
2373  const CXXBaseSpecifier * const *path_buffer() const {
2374    return const_cast<CastExpr*>(this)->path_buffer();
2375  }
2376  CXXBaseSpecifier **path_buffer();
2377
2378  void setBasePathSize(unsigned basePathSize) {
2379    CastExprBits.BasePathSize = basePathSize;
2380    assert(CastExprBits.BasePathSize == basePathSize &&
2381           "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2382  }
2383
2384protected:
2385  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2386           const CastKind kind, Expr *op, unsigned BasePathSize) :
2387    Expr(SC, ty, VK, OK_Ordinary,
2388         // Cast expressions are type-dependent if the type is
2389         // dependent (C++ [temp.dep.expr]p3).
2390         ty->isDependentType(),
2391         // Cast expressions are value-dependent if the type is
2392         // dependent or if the subexpression is value-dependent.
2393         ty->isDependentType() || (op && op->isValueDependent()),
2394         (ty->isInstantiationDependentType() ||
2395          (op && op->isInstantiationDependent())),
2396         (ty->containsUnexpandedParameterPack() ||
2397          op->containsUnexpandedParameterPack())),
2398    Op(op) {
2399    assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2400    CastExprBits.Kind = kind;
2401    setBasePathSize(BasePathSize);
2402#ifndef NDEBUG
2403    CheckCastConsistency();
2404#endif
2405  }
2406
2407  /// \brief Construct an empty cast.
2408  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2409    : Expr(SC, Empty) {
2410    setBasePathSize(BasePathSize);
2411  }
2412
2413public:
2414  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2415  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2416  const char *getCastKindName() const;
2417
2418  Expr *getSubExpr() { return cast<Expr>(Op); }
2419  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2420  void setSubExpr(Expr *E) { Op = E; }
2421
2422  /// \brief Retrieve the cast subexpression as it was written in the source
2423  /// code, looking through any implicit casts or other intermediate nodes
2424  /// introduced by semantic analysis.
2425  Expr *getSubExprAsWritten();
2426  const Expr *getSubExprAsWritten() const {
2427    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2428  }
2429
2430  typedef CXXBaseSpecifier **path_iterator;
2431  typedef const CXXBaseSpecifier * const *path_const_iterator;
2432  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2433  unsigned path_size() const { return CastExprBits.BasePathSize; }
2434  path_iterator path_begin() { return path_buffer(); }
2435  path_iterator path_end() { return path_buffer() + path_size(); }
2436  path_const_iterator path_begin() const { return path_buffer(); }
2437  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2438
2439  void setCastPath(const CXXCastPath &Path);
2440
2441  static bool classof(const Stmt *T) {
2442    return T->getStmtClass() >= firstCastExprConstant &&
2443           T->getStmtClass() <= lastCastExprConstant;
2444  }
2445  static bool classof(const CastExpr *) { return true; }
2446
2447  // Iterators
2448  child_range children() { return child_range(&Op, &Op+1); }
2449};
2450
2451/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2452/// conversions, which have no direct representation in the original
2453/// source code. For example: converting T[]->T*, void f()->void
2454/// (*f)(), float->double, short->int, etc.
2455///
2456/// In C, implicit casts always produce rvalues. However, in C++, an
2457/// implicit cast whose result is being bound to a reference will be
2458/// an lvalue or xvalue. For example:
2459///
2460/// @code
2461/// class Base { };
2462/// class Derived : public Base { };
2463/// Derived &&ref();
2464/// void f(Derived d) {
2465///   Base& b = d; // initializer is an ImplicitCastExpr
2466///                // to an lvalue of type Base
2467///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2468///                     // to an xvalue of type Base
2469/// }
2470/// @endcode
2471class ImplicitCastExpr : public CastExpr {
2472private:
2473  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2474                   unsigned BasePathLength, ExprValueKind VK)
2475    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2476  }
2477
2478  /// \brief Construct an empty implicit cast.
2479  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2480    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2481
2482public:
2483  enum OnStack_t { OnStack };
2484  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2485                   ExprValueKind VK)
2486    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2487  }
2488
2489  static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2490                                  CastKind Kind, Expr *Operand,
2491                                  const CXXCastPath *BasePath,
2492                                  ExprValueKind Cat);
2493
2494  static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2495
2496  SourceRange getSourceRange() const {
2497    return getSubExpr()->getSourceRange();
2498  }
2499
2500  static bool classof(const Stmt *T) {
2501    return T->getStmtClass() == ImplicitCastExprClass;
2502  }
2503  static bool classof(const ImplicitCastExpr *) { return true; }
2504};
2505
2506inline Expr *Expr::IgnoreImpCasts() {
2507  Expr *e = this;
2508  while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2509    e = ice->getSubExpr();
2510  return e;
2511}
2512
2513/// ExplicitCastExpr - An explicit cast written in the source
2514/// code.
2515///
2516/// This class is effectively an abstract class, because it provides
2517/// the basic representation of an explicitly-written cast without
2518/// specifying which kind of cast (C cast, functional cast, static
2519/// cast, etc.) was written; specific derived classes represent the
2520/// particular style of cast and its location information.
2521///
2522/// Unlike implicit casts, explicit cast nodes have two different
2523/// types: the type that was written into the source code, and the
2524/// actual type of the expression as determined by semantic
2525/// analysis. These types may differ slightly. For example, in C++ one
2526/// can cast to a reference type, which indicates that the resulting
2527/// expression will be an lvalue or xvalue. The reference type, however,
2528/// will not be used as the type of the expression.
2529class ExplicitCastExpr : public CastExpr {
2530  /// TInfo - Source type info for the (written) type
2531  /// this expression is casting to.
2532  TypeSourceInfo *TInfo;
2533
2534protected:
2535  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2536                   CastKind kind, Expr *op, unsigned PathSize,
2537                   TypeSourceInfo *writtenTy)
2538    : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2539
2540  /// \brief Construct an empty explicit cast.
2541  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2542    : CastExpr(SC, Shell, PathSize) { }
2543
2544public:
2545  /// getTypeInfoAsWritten - Returns the type source info for the type
2546  /// that this expression is casting to.
2547  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2548  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2549
2550  /// getTypeAsWritten - Returns the type that this expression is
2551  /// casting to, as written in the source code.
2552  QualType getTypeAsWritten() const { return TInfo->getType(); }
2553
2554  static bool classof(const Stmt *T) {
2555     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2556            T->getStmtClass() <= lastExplicitCastExprConstant;
2557  }
2558  static bool classof(const ExplicitCastExpr *) { return true; }
2559};
2560
2561/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2562/// cast in C++ (C++ [expr.cast]), which uses the syntax
2563/// (Type)expr. For example: @c (int)f.
2564class CStyleCastExpr : public ExplicitCastExpr {
2565  SourceLocation LPLoc; // the location of the left paren
2566  SourceLocation RPLoc; // the location of the right paren
2567
2568  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2569                 unsigned PathSize, TypeSourceInfo *writtenTy,
2570                 SourceLocation l, SourceLocation r)
2571    : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2572                       writtenTy), LPLoc(l), RPLoc(r) {}
2573
2574  /// \brief Construct an empty C-style explicit cast.
2575  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2576    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2577
2578public:
2579  static CStyleCastExpr *Create(ASTContext &Context, QualType T,
2580                                ExprValueKind VK, CastKind K,
2581                                Expr *Op, const CXXCastPath *BasePath,
2582                                TypeSourceInfo *WrittenTy, SourceLocation L,
2583                                SourceLocation R);
2584
2585  static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2586
2587  SourceLocation getLParenLoc() const { return LPLoc; }
2588  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2589
2590  SourceLocation getRParenLoc() const { return RPLoc; }
2591  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2592
2593  SourceRange getSourceRange() const {
2594    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2595  }
2596  static bool classof(const Stmt *T) {
2597    return T->getStmtClass() == CStyleCastExprClass;
2598  }
2599  static bool classof(const CStyleCastExpr *) { return true; }
2600};
2601
2602/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2603///
2604/// This expression node kind describes a builtin binary operation,
2605/// such as "x + y" for integer values "x" and "y". The operands will
2606/// already have been converted to appropriate types (e.g., by
2607/// performing promotions or conversions).
2608///
2609/// In C++, where operators may be overloaded, a different kind of
2610/// expression node (CXXOperatorCallExpr) is used to express the
2611/// invocation of an overloaded operator with operator syntax. Within
2612/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2613/// used to store an expression "x + y" depends on the subexpressions
2614/// for x and y. If neither x or y is type-dependent, and the "+"
2615/// operator resolves to a built-in operation, BinaryOperator will be
2616/// used to express the computation (x and y may still be
2617/// value-dependent). If either x or y is type-dependent, or if the
2618/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2619/// be used to express the computation.
2620class BinaryOperator : public Expr {
2621public:
2622  typedef BinaryOperatorKind Opcode;
2623
2624private:
2625  unsigned Opc : 6;
2626  SourceLocation OpLoc;
2627
2628  enum { LHS, RHS, END_EXPR };
2629  Stmt* SubExprs[END_EXPR];
2630public:
2631
2632  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2633                 ExprValueKind VK, ExprObjectKind OK,
2634                 SourceLocation opLoc)
2635    : Expr(BinaryOperatorClass, ResTy, VK, OK,
2636           lhs->isTypeDependent() || rhs->isTypeDependent(),
2637           lhs->isValueDependent() || rhs->isValueDependent(),
2638           (lhs->isInstantiationDependent() ||
2639            rhs->isInstantiationDependent()),
2640           (lhs->containsUnexpandedParameterPack() ||
2641            rhs->containsUnexpandedParameterPack())),
2642      Opc(opc), OpLoc(opLoc) {
2643    SubExprs[LHS] = lhs;
2644    SubExprs[RHS] = rhs;
2645    assert(!isCompoundAssignmentOp() &&
2646           "Use ArithAssignBinaryOperator for compound assignments");
2647  }
2648
2649  /// \brief Construct an empty binary operator.
2650  explicit BinaryOperator(EmptyShell Empty)
2651    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2652
2653  SourceLocation getOperatorLoc() const { return OpLoc; }
2654  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2655
2656  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2657  void setOpcode(Opcode O) { Opc = O; }
2658
2659  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2660  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2661  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2662  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2663
2664  SourceRange getSourceRange() const {
2665    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2666  }
2667
2668  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2669  /// corresponds to, e.g. "<<=".
2670  static const char *getOpcodeStr(Opcode Op);
2671
2672  const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2673
2674  /// \brief Retrieve the binary opcode that corresponds to the given
2675  /// overloaded operator.
2676  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2677
2678  /// \brief Retrieve the overloaded operator kind that corresponds to
2679  /// the given binary opcode.
2680  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2681
2682  /// predicates to categorize the respective opcodes.
2683  bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2684  bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2685  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2686  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2687  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2688  bool isShiftOp() const { return isShiftOp(getOpcode()); }
2689
2690  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2691  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2692
2693  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2694  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2695
2696  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2697  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2698
2699  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2700  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2701
2702  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2703  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2704
2705  static bool isAssignmentOp(Opcode Opc) {
2706    return Opc >= BO_Assign && Opc <= BO_OrAssign;
2707  }
2708  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
2709
2710  static bool isCompoundAssignmentOp(Opcode Opc) {
2711    return Opc > BO_Assign && Opc <= BO_OrAssign;
2712  }
2713  bool isCompoundAssignmentOp() const {
2714    return isCompoundAssignmentOp(getOpcode());
2715  }
2716
2717  static bool isShiftAssignOp(Opcode Opc) {
2718    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2719  }
2720  bool isShiftAssignOp() const {
2721    return isShiftAssignOp(getOpcode());
2722  }
2723
2724  static bool classof(const Stmt *S) {
2725    return S->getStmtClass() >= firstBinaryOperatorConstant &&
2726           S->getStmtClass() <= lastBinaryOperatorConstant;
2727  }
2728  static bool classof(const BinaryOperator *) { return true; }
2729
2730  // Iterators
2731  child_range children() {
2732    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2733  }
2734
2735protected:
2736  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2737                 ExprValueKind VK, ExprObjectKind OK,
2738                 SourceLocation opLoc, bool dead)
2739    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
2740           lhs->isTypeDependent() || rhs->isTypeDependent(),
2741           lhs->isValueDependent() || rhs->isValueDependent(),
2742           (lhs->isInstantiationDependent() ||
2743            rhs->isInstantiationDependent()),
2744           (lhs->containsUnexpandedParameterPack() ||
2745            rhs->containsUnexpandedParameterPack())),
2746      Opc(opc), OpLoc(opLoc) {
2747    SubExprs[LHS] = lhs;
2748    SubExprs[RHS] = rhs;
2749  }
2750
2751  BinaryOperator(StmtClass SC, EmptyShell Empty)
2752    : Expr(SC, Empty), Opc(BO_MulAssign) { }
2753};
2754
2755/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2756/// track of the type the operation is performed in.  Due to the semantics of
2757/// these operators, the operands are promoted, the arithmetic performed, an
2758/// implicit conversion back to the result type done, then the assignment takes
2759/// place.  This captures the intermediate type which the computation is done
2760/// in.
2761class CompoundAssignOperator : public BinaryOperator {
2762  QualType ComputationLHSType;
2763  QualType ComputationResultType;
2764public:
2765  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
2766                         ExprValueKind VK, ExprObjectKind OK,
2767                         QualType CompLHSType, QualType CompResultType,
2768                         SourceLocation OpLoc)
2769    : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true),
2770      ComputationLHSType(CompLHSType),
2771      ComputationResultType(CompResultType) {
2772    assert(isCompoundAssignmentOp() &&
2773           "Only should be used for compound assignments");
2774  }
2775
2776  /// \brief Build an empty compound assignment operator expression.
2777  explicit CompoundAssignOperator(EmptyShell Empty)
2778    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2779
2780  // The two computation types are the type the LHS is converted
2781  // to for the computation and the type of the result; the two are
2782  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2783  QualType getComputationLHSType() const { return ComputationLHSType; }
2784  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2785
2786  QualType getComputationResultType() const { return ComputationResultType; }
2787  void setComputationResultType(QualType T) { ComputationResultType = T; }
2788
2789  static bool classof(const CompoundAssignOperator *) { return true; }
2790  static bool classof(const Stmt *S) {
2791    return S->getStmtClass() == CompoundAssignOperatorClass;
2792  }
2793};
2794
2795/// AbstractConditionalOperator - An abstract base class for
2796/// ConditionalOperator and BinaryConditionalOperator.
2797class AbstractConditionalOperator : public Expr {
2798  SourceLocation QuestionLoc, ColonLoc;
2799  friend class ASTStmtReader;
2800
2801protected:
2802  AbstractConditionalOperator(StmtClass SC, QualType T,
2803                              ExprValueKind VK, ExprObjectKind OK,
2804                              bool TD, bool VD, bool ID,
2805                              bool ContainsUnexpandedParameterPack,
2806                              SourceLocation qloc,
2807                              SourceLocation cloc)
2808    : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
2809      QuestionLoc(qloc), ColonLoc(cloc) {}
2810
2811  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
2812    : Expr(SC, Empty) { }
2813
2814public:
2815  // getCond - Return the expression representing the condition for
2816  //   the ?: operator.
2817  Expr *getCond() const;
2818
2819  // getTrueExpr - Return the subexpression representing the value of
2820  //   the expression if the condition evaluates to true.
2821  Expr *getTrueExpr() const;
2822
2823  // getFalseExpr - Return the subexpression representing the value of
2824  //   the expression if the condition evaluates to false.  This is
2825  //   the same as getRHS.
2826  Expr *getFalseExpr() const;
2827
2828  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2829  SourceLocation getColonLoc() const { return ColonLoc; }
2830
2831  static bool classof(const Stmt *T) {
2832    return T->getStmtClass() == ConditionalOperatorClass ||
2833           T->getStmtClass() == BinaryConditionalOperatorClass;
2834  }
2835  static bool classof(const AbstractConditionalOperator *) { return true; }
2836};
2837
2838/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
2839/// middle" extension is a BinaryConditionalOperator.
2840class ConditionalOperator : public AbstractConditionalOperator {
2841  enum { COND, LHS, RHS, END_EXPR };
2842  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2843
2844  friend class ASTStmtReader;
2845public:
2846  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2847                      SourceLocation CLoc, Expr *rhs,
2848                      QualType t, ExprValueKind VK, ExprObjectKind OK)
2849    : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
2850           // FIXME: the type of the conditional operator doesn't
2851           // depend on the type of the conditional, but the standard
2852           // seems to imply that it could. File a bug!
2853           (lhs->isTypeDependent() || rhs->isTypeDependent()),
2854           (cond->isValueDependent() || lhs->isValueDependent() ||
2855            rhs->isValueDependent()),
2856           (cond->isInstantiationDependent() ||
2857            lhs->isInstantiationDependent() ||
2858            rhs->isInstantiationDependent()),
2859           (cond->containsUnexpandedParameterPack() ||
2860            lhs->containsUnexpandedParameterPack() ||
2861            rhs->containsUnexpandedParameterPack()),
2862                                  QLoc, CLoc) {
2863    SubExprs[COND] = cond;
2864    SubExprs[LHS] = lhs;
2865    SubExprs[RHS] = rhs;
2866  }
2867
2868  /// \brief Build an empty conditional operator.
2869  explicit ConditionalOperator(EmptyShell Empty)
2870    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
2871
2872  // getCond - Return the expression representing the condition for
2873  //   the ?: operator.
2874  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2875
2876  // getTrueExpr - Return the subexpression representing the value of
2877  //   the expression if the condition evaluates to true.
2878  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
2879
2880  // getFalseExpr - Return the subexpression representing the value of
2881  //   the expression if the condition evaluates to false.  This is
2882  //   the same as getRHS.
2883  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2884
2885  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2886  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2887
2888  SourceRange getSourceRange() const {
2889    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2890  }
2891  static bool classof(const Stmt *T) {
2892    return T->getStmtClass() == ConditionalOperatorClass;
2893  }
2894  static bool classof(const ConditionalOperator *) { return true; }
2895
2896  // Iterators
2897  child_range children() {
2898    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2899  }
2900};
2901
2902/// BinaryConditionalOperator - The GNU extension to the conditional
2903/// operator which allows the middle operand to be omitted.
2904///
2905/// This is a different expression kind on the assumption that almost
2906/// every client ends up needing to know that these are different.
2907class BinaryConditionalOperator : public AbstractConditionalOperator {
2908  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
2909
2910  /// - the common condition/left-hand-side expression, which will be
2911  ///   evaluated as the opaque value
2912  /// - the condition, expressed in terms of the opaque value
2913  /// - the left-hand-side, expressed in terms of the opaque value
2914  /// - the right-hand-side
2915  Stmt *SubExprs[NUM_SUBEXPRS];
2916  OpaqueValueExpr *OpaqueValue;
2917
2918  friend class ASTStmtReader;
2919public:
2920  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
2921                            Expr *cond, Expr *lhs, Expr *rhs,
2922                            SourceLocation qloc, SourceLocation cloc,
2923                            QualType t, ExprValueKind VK, ExprObjectKind OK)
2924    : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
2925           (common->isTypeDependent() || rhs->isTypeDependent()),
2926           (common->isValueDependent() || rhs->isValueDependent()),
2927           (common->isInstantiationDependent() ||
2928            rhs->isInstantiationDependent()),
2929           (common->containsUnexpandedParameterPack() ||
2930            rhs->containsUnexpandedParameterPack()),
2931                                  qloc, cloc),
2932      OpaqueValue(opaqueValue) {
2933    SubExprs[COMMON] = common;
2934    SubExprs[COND] = cond;
2935    SubExprs[LHS] = lhs;
2936    SubExprs[RHS] = rhs;
2937
2938    OpaqueValue->setSourceExpr(common);
2939  }
2940
2941  /// \brief Build an empty conditional operator.
2942  explicit BinaryConditionalOperator(EmptyShell Empty)
2943    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
2944
2945  /// \brief getCommon - Return the common expression, written to the
2946  ///   left of the condition.  The opaque value will be bound to the
2947  ///   result of this expression.
2948  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
2949
2950  /// \brief getOpaqueValue - Return the opaque value placeholder.
2951  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
2952
2953  /// \brief getCond - Return the condition expression; this is defined
2954  ///   in terms of the opaque value.
2955  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2956
2957  /// \brief getTrueExpr - Return the subexpression which will be
2958  ///   evaluated if the condition evaluates to true;  this is defined
2959  ///   in terms of the opaque value.
2960  Expr *getTrueExpr() const {
2961    return cast<Expr>(SubExprs[LHS]);
2962  }
2963
2964  /// \brief getFalseExpr - Return the subexpression which will be
2965  ///   evaluated if the condnition evaluates to false; this is
2966  ///   defined in terms of the opaque value.
2967  Expr *getFalseExpr() const {
2968    return cast<Expr>(SubExprs[RHS]);
2969  }
2970
2971  SourceRange getSourceRange() const {
2972    return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd());
2973  }
2974  static bool classof(const Stmt *T) {
2975    return T->getStmtClass() == BinaryConditionalOperatorClass;
2976  }
2977  static bool classof(const BinaryConditionalOperator *) { return true; }
2978
2979  // Iterators
2980  child_range children() {
2981    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
2982  }
2983};
2984
2985inline Expr *AbstractConditionalOperator::getCond() const {
2986  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2987    return co->getCond();
2988  return cast<BinaryConditionalOperator>(this)->getCond();
2989}
2990
2991inline Expr *AbstractConditionalOperator::getTrueExpr() const {
2992  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2993    return co->getTrueExpr();
2994  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
2995}
2996
2997inline Expr *AbstractConditionalOperator::getFalseExpr() const {
2998  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2999    return co->getFalseExpr();
3000  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3001}
3002
3003/// AddrLabelExpr - The GNU address of label extension, representing &&label.
3004class AddrLabelExpr : public Expr {
3005  SourceLocation AmpAmpLoc, LabelLoc;
3006  LabelDecl *Label;
3007public:
3008  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3009                QualType t)
3010    : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3011           false),
3012      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3013
3014  /// \brief Build an empty address of a label expression.
3015  explicit AddrLabelExpr(EmptyShell Empty)
3016    : Expr(AddrLabelExprClass, Empty) { }
3017
3018  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3019  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3020  SourceLocation getLabelLoc() const { return LabelLoc; }
3021  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3022
3023  SourceRange getSourceRange() const {
3024    return SourceRange(AmpAmpLoc, LabelLoc);
3025  }
3026
3027  LabelDecl *getLabel() const { return Label; }
3028  void setLabel(LabelDecl *L) { Label = L; }
3029
3030  static bool classof(const Stmt *T) {
3031    return T->getStmtClass() == AddrLabelExprClass;
3032  }
3033  static bool classof(const AddrLabelExpr *) { return true; }
3034
3035  // Iterators
3036  child_range children() { return child_range(); }
3037};
3038
3039/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3040/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3041/// takes the value of the last subexpression.
3042///
3043/// A StmtExpr is always an r-value; values "returned" out of a
3044/// StmtExpr will be copied.
3045class StmtExpr : public Expr {
3046  Stmt *SubStmt;
3047  SourceLocation LParenLoc, RParenLoc;
3048public:
3049  // FIXME: Does type-dependence need to be computed differently?
3050  // FIXME: Do we need to compute instantiation instantiation-dependence for
3051  // statements? (ugh!)
3052  StmtExpr(CompoundStmt *substmt, QualType T,
3053           SourceLocation lp, SourceLocation rp) :
3054    Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3055         T->isDependentType(), false, false, false),
3056    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3057
3058  /// \brief Build an empty statement expression.
3059  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3060
3061  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3062  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3063  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3064
3065  SourceRange getSourceRange() const {
3066    return SourceRange(LParenLoc, RParenLoc);
3067  }
3068
3069  SourceLocation getLParenLoc() const { return LParenLoc; }
3070  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3071  SourceLocation getRParenLoc() const { return RParenLoc; }
3072  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3073
3074  static bool classof(const Stmt *T) {
3075    return T->getStmtClass() == StmtExprClass;
3076  }
3077  static bool classof(const StmtExpr *) { return true; }
3078
3079  // Iterators
3080  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3081};
3082
3083
3084/// ShuffleVectorExpr - clang-specific builtin-in function
3085/// __builtin_shufflevector.
3086/// This AST node represents a operator that does a constant
3087/// shuffle, similar to LLVM's shufflevector instruction. It takes
3088/// two vectors and a variable number of constant indices,
3089/// and returns the appropriately shuffled vector.
3090class ShuffleVectorExpr : public Expr {
3091  SourceLocation BuiltinLoc, RParenLoc;
3092
3093  // SubExprs - the list of values passed to the __builtin_shufflevector
3094  // function. The first two are vectors, and the rest are constant
3095  // indices.  The number of values in this list is always
3096  // 2+the number of indices in the vector type.
3097  Stmt **SubExprs;
3098  unsigned NumExprs;
3099
3100public:
3101  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3102                    QualType Type, SourceLocation BLoc,
3103                    SourceLocation RP);
3104
3105  /// \brief Build an empty vector-shuffle expression.
3106  explicit ShuffleVectorExpr(EmptyShell Empty)
3107    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
3108
3109  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3110  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3111
3112  SourceLocation getRParenLoc() const { return RParenLoc; }
3113  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3114
3115  SourceRange getSourceRange() const {
3116    return SourceRange(BuiltinLoc, RParenLoc);
3117  }
3118  static bool classof(const Stmt *T) {
3119    return T->getStmtClass() == ShuffleVectorExprClass;
3120  }
3121  static bool classof(const ShuffleVectorExpr *) { return true; }
3122
3123  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
3124  /// constant expression, the actual arguments passed in, and the function
3125  /// pointers.
3126  unsigned getNumSubExprs() const { return NumExprs; }
3127
3128  /// \brief Retrieve the array of expressions.
3129  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3130
3131  /// getExpr - Return the Expr at the specified index.
3132  Expr *getExpr(unsigned Index) {
3133    assert((Index < NumExprs) && "Arg access out of range!");
3134    return cast<Expr>(SubExprs[Index]);
3135  }
3136  const Expr *getExpr(unsigned Index) const {
3137    assert((Index < NumExprs) && "Arg access out of range!");
3138    return cast<Expr>(SubExprs[Index]);
3139  }
3140
3141  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
3142
3143  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
3144    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3145    return getExpr(N+2)->EvaluateKnownConstInt(Ctx).getZExtValue();
3146  }
3147
3148  // Iterators
3149  child_range children() {
3150    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3151  }
3152};
3153
3154/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3155/// This AST node is similar to the conditional operator (?:) in C, with
3156/// the following exceptions:
3157/// - the test expression must be a integer constant expression.
3158/// - the expression returned acts like the chosen subexpression in every
3159///   visible way: the type is the same as that of the chosen subexpression,
3160///   and all predicates (whether it's an l-value, whether it's an integer
3161///   constant expression, etc.) return the same result as for the chosen
3162///   sub-expression.
3163class ChooseExpr : public Expr {
3164  enum { COND, LHS, RHS, END_EXPR };
3165  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3166  SourceLocation BuiltinLoc, RParenLoc;
3167public:
3168  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3169             QualType t, ExprValueKind VK, ExprObjectKind OK,
3170             SourceLocation RP, bool TypeDependent, bool ValueDependent)
3171    : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3172           (cond->isInstantiationDependent() ||
3173            lhs->isInstantiationDependent() ||
3174            rhs->isInstantiationDependent()),
3175           (cond->containsUnexpandedParameterPack() ||
3176            lhs->containsUnexpandedParameterPack() ||
3177            rhs->containsUnexpandedParameterPack())),
3178      BuiltinLoc(BLoc), RParenLoc(RP) {
3179      SubExprs[COND] = cond;
3180      SubExprs[LHS] = lhs;
3181      SubExprs[RHS] = rhs;
3182    }
3183
3184  /// \brief Build an empty __builtin_choose_expr.
3185  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3186
3187  /// isConditionTrue - Return whether the condition is true (i.e. not
3188  /// equal to zero).
3189  bool isConditionTrue(const ASTContext &C) const;
3190
3191  /// getChosenSubExpr - Return the subexpression chosen according to the
3192  /// condition.
3193  Expr *getChosenSubExpr(const ASTContext &C) const {
3194    return isConditionTrue(C) ? getLHS() : getRHS();
3195  }
3196
3197  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3198  void setCond(Expr *E) { SubExprs[COND] = E; }
3199  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3200  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3201  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3202  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3203
3204  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3205  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3206
3207  SourceLocation getRParenLoc() const { return RParenLoc; }
3208  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3209
3210  SourceRange getSourceRange() const {
3211    return SourceRange(BuiltinLoc, RParenLoc);
3212  }
3213  static bool classof(const Stmt *T) {
3214    return T->getStmtClass() == ChooseExprClass;
3215  }
3216  static bool classof(const ChooseExpr *) { return true; }
3217
3218  // Iterators
3219  child_range children() {
3220    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3221  }
3222};
3223
3224/// GNUNullExpr - Implements the GNU __null extension, which is a name
3225/// for a null pointer constant that has integral type (e.g., int or
3226/// long) and is the same size and alignment as a pointer. The __null
3227/// extension is typically only used by system headers, which define
3228/// NULL as __null in C++ rather than using 0 (which is an integer
3229/// that may not match the size of a pointer).
3230class GNUNullExpr : public Expr {
3231  /// TokenLoc - The location of the __null keyword.
3232  SourceLocation TokenLoc;
3233
3234public:
3235  GNUNullExpr(QualType Ty, SourceLocation Loc)
3236    : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3237           false),
3238      TokenLoc(Loc) { }
3239
3240  /// \brief Build an empty GNU __null expression.
3241  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3242
3243  /// getTokenLocation - The location of the __null token.
3244  SourceLocation getTokenLocation() const { return TokenLoc; }
3245  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3246
3247  SourceRange getSourceRange() const {
3248    return SourceRange(TokenLoc);
3249  }
3250  static bool classof(const Stmt *T) {
3251    return T->getStmtClass() == GNUNullExprClass;
3252  }
3253  static bool classof(const GNUNullExpr *) { return true; }
3254
3255  // Iterators
3256  child_range children() { return child_range(); }
3257};
3258
3259/// VAArgExpr, used for the builtin function __builtin_va_arg.
3260class VAArgExpr : public Expr {
3261  Stmt *Val;
3262  TypeSourceInfo *TInfo;
3263  SourceLocation BuiltinLoc, RParenLoc;
3264public:
3265  VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3266            SourceLocation RPLoc, QualType t)
3267    : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3268           t->isDependentType(), false,
3269           (TInfo->getType()->isInstantiationDependentType() ||
3270            e->isInstantiationDependent()),
3271           (TInfo->getType()->containsUnexpandedParameterPack() ||
3272            e->containsUnexpandedParameterPack())),
3273      Val(e), TInfo(TInfo),
3274      BuiltinLoc(BLoc),
3275      RParenLoc(RPLoc) { }
3276
3277  /// \brief Create an empty __builtin_va_arg expression.
3278  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3279
3280  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3281  Expr *getSubExpr() { return cast<Expr>(Val); }
3282  void setSubExpr(Expr *E) { Val = E; }
3283
3284  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3285  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3286
3287  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3288  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3289
3290  SourceLocation getRParenLoc() const { return RParenLoc; }
3291  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3292
3293  SourceRange getSourceRange() const {
3294    return SourceRange(BuiltinLoc, RParenLoc);
3295  }
3296  static bool classof(const Stmt *T) {
3297    return T->getStmtClass() == VAArgExprClass;
3298  }
3299  static bool classof(const VAArgExpr *) { return true; }
3300
3301  // Iterators
3302  child_range children() { return child_range(&Val, &Val+1); }
3303};
3304
3305/// @brief Describes an C or C++ initializer list.
3306///
3307/// InitListExpr describes an initializer list, which can be used to
3308/// initialize objects of different types, including
3309/// struct/class/union types, arrays, and vectors. For example:
3310///
3311/// @code
3312/// struct foo x = { 1, { 2, 3 } };
3313/// @endcode
3314///
3315/// Prior to semantic analysis, an initializer list will represent the
3316/// initializer list as written by the user, but will have the
3317/// placeholder type "void". This initializer list is called the
3318/// syntactic form of the initializer, and may contain C99 designated
3319/// initializers (represented as DesignatedInitExprs), initializations
3320/// of subobject members without explicit braces, and so on. Clients
3321/// interested in the original syntax of the initializer list should
3322/// use the syntactic form of the initializer list.
3323///
3324/// After semantic analysis, the initializer list will represent the
3325/// semantic form of the initializer, where the initializations of all
3326/// subobjects are made explicit with nested InitListExpr nodes and
3327/// C99 designators have been eliminated by placing the designated
3328/// initializations into the subobject they initialize. Additionally,
3329/// any "holes" in the initialization, where no initializer has been
3330/// specified for a particular subobject, will be replaced with
3331/// implicitly-generated ImplicitValueInitExpr expressions that
3332/// value-initialize the subobjects. Note, however, that the
3333/// initializer lists may still have fewer initializers than there are
3334/// elements to initialize within the object.
3335///
3336/// Given the semantic form of the initializer list, one can retrieve
3337/// the original syntactic form of that initializer list (if it
3338/// exists) using getSyntacticForm(). Since many initializer lists
3339/// have the same syntactic and semantic forms, getSyntacticForm() may
3340/// return NULL, indicating that the current initializer list also
3341/// serves as its syntactic form.
3342class InitListExpr : public Expr {
3343  // FIXME: Eliminate this vector in favor of ASTContext allocation
3344  typedef ASTVector<Stmt *> InitExprsTy;
3345  InitExprsTy InitExprs;
3346  SourceLocation LBraceLoc, RBraceLoc;
3347
3348  /// Contains the initializer list that describes the syntactic form
3349  /// written in the source code.
3350  InitListExpr *SyntacticForm;
3351
3352  /// \brief Either:
3353  ///  If this initializer list initializes an array with more elements than
3354  ///  there are initializers in the list, specifies an expression to be used
3355  ///  for value initialization of the rest of the elements.
3356  /// Or
3357  ///  If this initializer list initializes a union, specifies which
3358  ///  field within the union will be initialized.
3359  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3360
3361  /// Whether this initializer list originally had a GNU array-range
3362  /// designator in it. This is a temporary marker used by CodeGen.
3363  bool HadArrayRangeDesignator;
3364
3365public:
3366  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
3367               Expr **initexprs, unsigned numinits,
3368               SourceLocation rbraceloc);
3369
3370  /// \brief Build an empty initializer list.
3371  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
3372    : Expr(InitListExprClass, Empty), InitExprs(C) { }
3373
3374  unsigned getNumInits() const { return InitExprs.size(); }
3375
3376  /// \brief Retrieve the set of initializers.
3377  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3378
3379  const Expr *getInit(unsigned Init) const {
3380    assert(Init < getNumInits() && "Initializer access out of range!");
3381    return cast_or_null<Expr>(InitExprs[Init]);
3382  }
3383
3384  Expr *getInit(unsigned Init) {
3385    assert(Init < getNumInits() && "Initializer access out of range!");
3386    return cast_or_null<Expr>(InitExprs[Init]);
3387  }
3388
3389  void setInit(unsigned Init, Expr *expr) {
3390    assert(Init < getNumInits() && "Initializer access out of range!");
3391    InitExprs[Init] = expr;
3392  }
3393
3394  /// \brief Reserve space for some number of initializers.
3395  void reserveInits(ASTContext &C, unsigned NumInits);
3396
3397  /// @brief Specify the number of initializers
3398  ///
3399  /// If there are more than @p NumInits initializers, the remaining
3400  /// initializers will be destroyed. If there are fewer than @p
3401  /// NumInits initializers, NULL expressions will be added for the
3402  /// unknown initializers.
3403  void resizeInits(ASTContext &Context, unsigned NumInits);
3404
3405  /// @brief Updates the initializer at index @p Init with the new
3406  /// expression @p expr, and returns the old expression at that
3407  /// location.
3408  ///
3409  /// When @p Init is out of range for this initializer list, the
3410  /// initializer list will be extended with NULL expressions to
3411  /// accommodate the new entry.
3412  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
3413
3414  /// \brief If this initializer list initializes an array with more elements
3415  /// than there are initializers in the list, specifies an expression to be
3416  /// used for value initialization of the rest of the elements.
3417  Expr *getArrayFiller() {
3418    return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3419  }
3420  const Expr *getArrayFiller() const {
3421    return const_cast<InitListExpr *>(this)->getArrayFiller();
3422  }
3423  void setArrayFiller(Expr *filler);
3424
3425  /// \brief Return true if this is an array initializer and its array "filler"
3426  /// has been set.
3427  bool hasArrayFiller() const { return getArrayFiller(); }
3428
3429  /// \brief If this initializes a union, specifies which field in the
3430  /// union to initialize.
3431  ///
3432  /// Typically, this field is the first named field within the
3433  /// union. However, a designated initializer can specify the
3434  /// initialization of a different field within the union.
3435  FieldDecl *getInitializedFieldInUnion() {
3436    return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3437  }
3438  const FieldDecl *getInitializedFieldInUnion() const {
3439    return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3440  }
3441  void setInitializedFieldInUnion(FieldDecl *FD) {
3442    ArrayFillerOrUnionFieldInit = FD;
3443  }
3444
3445  // Explicit InitListExpr's originate from source code (and have valid source
3446  // locations). Implicit InitListExpr's are created by the semantic analyzer.
3447  bool isExplicit() {
3448    return LBraceLoc.isValid() && RBraceLoc.isValid();
3449  }
3450
3451  SourceLocation getLBraceLoc() const { return LBraceLoc; }
3452  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3453  SourceLocation getRBraceLoc() const { return RBraceLoc; }
3454  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3455
3456  /// @brief Retrieve the initializer list that describes the
3457  /// syntactic form of the initializer.
3458  ///
3459  ///
3460  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
3461  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
3462
3463  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
3464  void sawArrayRangeDesignator(bool ARD = true) {
3465    HadArrayRangeDesignator = ARD;
3466  }
3467
3468  SourceRange getSourceRange() const;
3469
3470  static bool classof(const Stmt *T) {
3471    return T->getStmtClass() == InitListExprClass;
3472  }
3473  static bool classof(const InitListExpr *) { return true; }
3474
3475  // Iterators
3476  child_range children() {
3477    if (InitExprs.empty()) return child_range();
3478    return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3479  }
3480
3481  typedef InitExprsTy::iterator iterator;
3482  typedef InitExprsTy::const_iterator const_iterator;
3483  typedef InitExprsTy::reverse_iterator reverse_iterator;
3484  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3485
3486  iterator begin() { return InitExprs.begin(); }
3487  const_iterator begin() const { return InitExprs.begin(); }
3488  iterator end() { return InitExprs.end(); }
3489  const_iterator end() const { return InitExprs.end(); }
3490  reverse_iterator rbegin() { return InitExprs.rbegin(); }
3491  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3492  reverse_iterator rend() { return InitExprs.rend(); }
3493  const_reverse_iterator rend() const { return InitExprs.rend(); }
3494
3495  friend class ASTStmtReader;
3496  friend class ASTStmtWriter;
3497};
3498
3499/// @brief Represents a C99 designated initializer expression.
3500///
3501/// A designated initializer expression (C99 6.7.8) contains one or
3502/// more designators (which can be field designators, array
3503/// designators, or GNU array-range designators) followed by an
3504/// expression that initializes the field or element(s) that the
3505/// designators refer to. For example, given:
3506///
3507/// @code
3508/// struct point {
3509///   double x;
3510///   double y;
3511/// };
3512/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3513/// @endcode
3514///
3515/// The InitListExpr contains three DesignatedInitExprs, the first of
3516/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3517/// designators, one array designator for @c [2] followed by one field
3518/// designator for @c .y. The initalization expression will be 1.0.
3519class DesignatedInitExpr : public Expr {
3520public:
3521  /// \brief Forward declaration of the Designator class.
3522  class Designator;
3523
3524private:
3525  /// The location of the '=' or ':' prior to the actual initializer
3526  /// expression.
3527  SourceLocation EqualOrColonLoc;
3528
3529  /// Whether this designated initializer used the GNU deprecated
3530  /// syntax rather than the C99 '=' syntax.
3531  bool GNUSyntax : 1;
3532
3533  /// The number of designators in this initializer expression.
3534  unsigned NumDesignators : 15;
3535
3536  /// \brief The designators in this designated initialization
3537  /// expression.
3538  Designator *Designators;
3539
3540  /// The number of subexpressions of this initializer expression,
3541  /// which contains both the initializer and any additional
3542  /// expressions used by array and array-range designators.
3543  unsigned NumSubExprs : 16;
3544
3545
3546  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3547                     const Designator *Designators,
3548                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
3549                     Expr **IndexExprs, unsigned NumIndexExprs,
3550                     Expr *Init);
3551
3552  explicit DesignatedInitExpr(unsigned NumSubExprs)
3553    : Expr(DesignatedInitExprClass, EmptyShell()),
3554      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
3555
3556public:
3557  /// A field designator, e.g., ".x".
3558  struct FieldDesignator {
3559    /// Refers to the field that is being initialized. The low bit
3560    /// of this field determines whether this is actually a pointer
3561    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3562    /// initially constructed, a field designator will store an
3563    /// IdentifierInfo*. After semantic analysis has resolved that
3564    /// name, the field designator will instead store a FieldDecl*.
3565    uintptr_t NameOrField;
3566
3567    /// The location of the '.' in the designated initializer.
3568    unsigned DotLoc;
3569
3570    /// The location of the field name in the designated initializer.
3571    unsigned FieldLoc;
3572  };
3573
3574  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3575  struct ArrayOrRangeDesignator {
3576    /// Location of the first index expression within the designated
3577    /// initializer expression's list of subexpressions.
3578    unsigned Index;
3579    /// The location of the '[' starting the array range designator.
3580    unsigned LBracketLoc;
3581    /// The location of the ellipsis separating the start and end
3582    /// indices. Only valid for GNU array-range designators.
3583    unsigned EllipsisLoc;
3584    /// The location of the ']' terminating the array range designator.
3585    unsigned RBracketLoc;
3586  };
3587
3588  /// @brief Represents a single C99 designator.
3589  ///
3590  /// @todo This class is infuriatingly similar to clang::Designator,
3591  /// but minor differences (storing indices vs. storing pointers)
3592  /// keep us from reusing it. Try harder, later, to rectify these
3593  /// differences.
3594  class Designator {
3595    /// @brief The kind of designator this describes.
3596    enum {
3597      FieldDesignator,
3598      ArrayDesignator,
3599      ArrayRangeDesignator
3600    } Kind;
3601
3602    union {
3603      /// A field designator, e.g., ".x".
3604      struct FieldDesignator Field;
3605      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3606      struct ArrayOrRangeDesignator ArrayOrRange;
3607    };
3608    friend class DesignatedInitExpr;
3609
3610  public:
3611    Designator() {}
3612
3613    /// @brief Initializes a field designator.
3614    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3615               SourceLocation FieldLoc)
3616      : Kind(FieldDesignator) {
3617      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3618      Field.DotLoc = DotLoc.getRawEncoding();
3619      Field.FieldLoc = FieldLoc.getRawEncoding();
3620    }
3621
3622    /// @brief Initializes an array designator.
3623    Designator(unsigned Index, SourceLocation LBracketLoc,
3624               SourceLocation RBracketLoc)
3625      : Kind(ArrayDesignator) {
3626      ArrayOrRange.Index = Index;
3627      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3628      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3629      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3630    }
3631
3632    /// @brief Initializes a GNU array-range designator.
3633    Designator(unsigned Index, SourceLocation LBracketLoc,
3634               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3635      : Kind(ArrayRangeDesignator) {
3636      ArrayOrRange.Index = Index;
3637      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3638      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3639      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3640    }
3641
3642    bool isFieldDesignator() const { return Kind == FieldDesignator; }
3643    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3644    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3645
3646    IdentifierInfo *getFieldName() const;
3647
3648    FieldDecl *getField() const {
3649      assert(Kind == FieldDesignator && "Only valid on a field designator");
3650      if (Field.NameOrField & 0x01)
3651        return 0;
3652      else
3653        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3654    }
3655
3656    void setField(FieldDecl *FD) {
3657      assert(Kind == FieldDesignator && "Only valid on a field designator");
3658      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3659    }
3660
3661    SourceLocation getDotLoc() const {
3662      assert(Kind == FieldDesignator && "Only valid on a field designator");
3663      return SourceLocation::getFromRawEncoding(Field.DotLoc);
3664    }
3665
3666    SourceLocation getFieldLoc() const {
3667      assert(Kind == FieldDesignator && "Only valid on a field designator");
3668      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3669    }
3670
3671    SourceLocation getLBracketLoc() const {
3672      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3673             "Only valid on an array or array-range designator");
3674      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3675    }
3676
3677    SourceLocation getRBracketLoc() const {
3678      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3679             "Only valid on an array or array-range designator");
3680      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3681    }
3682
3683    SourceLocation getEllipsisLoc() const {
3684      assert(Kind == ArrayRangeDesignator &&
3685             "Only valid on an array-range designator");
3686      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3687    }
3688
3689    unsigned getFirstExprIndex() const {
3690      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3691             "Only valid on an array or array-range designator");
3692      return ArrayOrRange.Index;
3693    }
3694
3695    SourceLocation getStartLocation() const {
3696      if (Kind == FieldDesignator)
3697        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3698      else
3699        return getLBracketLoc();
3700    }
3701    SourceLocation getEndLocation() const {
3702      return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
3703    }
3704    SourceRange getSourceRange() const {
3705      return SourceRange(getStartLocation(), getEndLocation());
3706    }
3707  };
3708
3709  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3710                                    unsigned NumDesignators,
3711                                    Expr **IndexExprs, unsigned NumIndexExprs,
3712                                    SourceLocation EqualOrColonLoc,
3713                                    bool GNUSyntax, Expr *Init);
3714
3715  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3716
3717  /// @brief Returns the number of designators in this initializer.
3718  unsigned size() const { return NumDesignators; }
3719
3720  // Iterator access to the designators.
3721  typedef Designator *designators_iterator;
3722  designators_iterator designators_begin() { return Designators; }
3723  designators_iterator designators_end() {
3724    return Designators + NumDesignators;
3725  }
3726
3727  typedef const Designator *const_designators_iterator;
3728  const_designators_iterator designators_begin() const { return Designators; }
3729  const_designators_iterator designators_end() const {
3730    return Designators + NumDesignators;
3731  }
3732
3733  typedef std::reverse_iterator<designators_iterator>
3734          reverse_designators_iterator;
3735  reverse_designators_iterator designators_rbegin() {
3736    return reverse_designators_iterator(designators_end());
3737  }
3738  reverse_designators_iterator designators_rend() {
3739    return reverse_designators_iterator(designators_begin());
3740  }
3741
3742  typedef std::reverse_iterator<const_designators_iterator>
3743          const_reverse_designators_iterator;
3744  const_reverse_designators_iterator designators_rbegin() const {
3745    return const_reverse_designators_iterator(designators_end());
3746  }
3747  const_reverse_designators_iterator designators_rend() const {
3748    return const_reverse_designators_iterator(designators_begin());
3749  }
3750
3751  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3752
3753  void setDesignators(ASTContext &C, const Designator *Desigs,
3754                      unsigned NumDesigs);
3755
3756  Expr *getArrayIndex(const Designator& D);
3757  Expr *getArrayRangeStart(const Designator& D);
3758  Expr *getArrayRangeEnd(const Designator& D);
3759
3760  /// @brief Retrieve the location of the '=' that precedes the
3761  /// initializer value itself, if present.
3762  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3763  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3764
3765  /// @brief Determines whether this designated initializer used the
3766  /// deprecated GNU syntax for designated initializers.
3767  bool usesGNUSyntax() const { return GNUSyntax; }
3768  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3769
3770  /// @brief Retrieve the initializer value.
3771  Expr *getInit() const {
3772    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3773  }
3774
3775  void setInit(Expr *init) {
3776    *child_begin() = init;
3777  }
3778
3779  /// \brief Retrieve the total number of subexpressions in this
3780  /// designated initializer expression, including the actual
3781  /// initialized value and any expressions that occur within array
3782  /// and array-range designators.
3783  unsigned getNumSubExprs() const { return NumSubExprs; }
3784
3785  Expr *getSubExpr(unsigned Idx) {
3786    assert(Idx < NumSubExprs && "Subscript out of range");
3787    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3788    Ptr += sizeof(DesignatedInitExpr);
3789    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3790  }
3791
3792  void setSubExpr(unsigned Idx, Expr *E) {
3793    assert(Idx < NumSubExprs && "Subscript out of range");
3794    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3795    Ptr += sizeof(DesignatedInitExpr);
3796    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3797  }
3798
3799  /// \brief Replaces the designator at index @p Idx with the series
3800  /// of designators in [First, Last).
3801  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3802                        const Designator *Last);
3803
3804  SourceRange getDesignatorsSourceRange() const;
3805
3806  SourceRange getSourceRange() const;
3807
3808  static bool classof(const Stmt *T) {
3809    return T->getStmtClass() == DesignatedInitExprClass;
3810  }
3811  static bool classof(const DesignatedInitExpr *) { return true; }
3812
3813  // Iterators
3814  child_range children() {
3815    Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
3816    return child_range(begin, begin + NumSubExprs);
3817  }
3818};
3819
3820/// \brief Represents an implicitly-generated value initialization of
3821/// an object of a given type.
3822///
3823/// Implicit value initializations occur within semantic initializer
3824/// list expressions (InitListExpr) as placeholders for subobject
3825/// initializations not explicitly specified by the user.
3826///
3827/// \see InitListExpr
3828class ImplicitValueInitExpr : public Expr {
3829public:
3830  explicit ImplicitValueInitExpr(QualType ty)
3831    : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
3832           false, false, ty->isInstantiationDependentType(), false) { }
3833
3834  /// \brief Construct an empty implicit value initialization.
3835  explicit ImplicitValueInitExpr(EmptyShell Empty)
3836    : Expr(ImplicitValueInitExprClass, Empty) { }
3837
3838  static bool classof(const Stmt *T) {
3839    return T->getStmtClass() == ImplicitValueInitExprClass;
3840  }
3841  static bool classof(const ImplicitValueInitExpr *) { return true; }
3842
3843  SourceRange getSourceRange() const {
3844    return SourceRange();
3845  }
3846
3847  // Iterators
3848  child_range children() { return child_range(); }
3849};
3850
3851
3852class ParenListExpr : public Expr {
3853  Stmt **Exprs;
3854  unsigned NumExprs;
3855  SourceLocation LParenLoc, RParenLoc;
3856
3857public:
3858  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3859                unsigned numexprs, SourceLocation rparenloc, QualType T);
3860
3861  /// \brief Build an empty paren list.
3862  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3863
3864  unsigned getNumExprs() const { return NumExprs; }
3865
3866  const Expr* getExpr(unsigned Init) const {
3867    assert(Init < getNumExprs() && "Initializer access out of range!");
3868    return cast_or_null<Expr>(Exprs[Init]);
3869  }
3870
3871  Expr* getExpr(unsigned Init) {
3872    assert(Init < getNumExprs() && "Initializer access out of range!");
3873    return cast_or_null<Expr>(Exprs[Init]);
3874  }
3875
3876  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3877
3878  SourceLocation getLParenLoc() const { return LParenLoc; }
3879  SourceLocation getRParenLoc() const { return RParenLoc; }
3880
3881  SourceRange getSourceRange() const {
3882    return SourceRange(LParenLoc, RParenLoc);
3883  }
3884  static bool classof(const Stmt *T) {
3885    return T->getStmtClass() == ParenListExprClass;
3886  }
3887  static bool classof(const ParenListExpr *) { return true; }
3888
3889  // Iterators
3890  child_range children() {
3891    return child_range(&Exprs[0], &Exprs[0]+NumExprs);
3892  }
3893
3894  friend class ASTStmtReader;
3895  friend class ASTStmtWriter;
3896};
3897
3898
3899/// \brief Represents a C1X generic selection.
3900///
3901/// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling
3902/// expression, followed by one or more generic associations.  Each generic
3903/// association specifies a type name and an expression, or "default" and an
3904/// expression (in which case it is known as a default generic association).
3905/// The type and value of the generic selection are identical to those of its
3906/// result expression, which is defined as the expression in the generic
3907/// association with a type name that is compatible with the type of the
3908/// controlling expression, or the expression in the default generic association
3909/// if no types are compatible.  For example:
3910///
3911/// @code
3912/// _Generic(X, double: 1, float: 2, default: 3)
3913/// @endcode
3914///
3915/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
3916/// or 3 if "hello".
3917///
3918/// As an extension, generic selections are allowed in C++, where the following
3919/// additional semantics apply:
3920///
3921/// Any generic selection whose controlling expression is type-dependent or
3922/// which names a dependent type in its association list is result-dependent,
3923/// which means that the choice of result expression is dependent.
3924/// Result-dependent generic associations are both type- and value-dependent.
3925class GenericSelectionExpr : public Expr {
3926  enum { CONTROLLING, END_EXPR };
3927  TypeSourceInfo **AssocTypes;
3928  Stmt **SubExprs;
3929  unsigned NumAssocs, ResultIndex;
3930  SourceLocation GenericLoc, DefaultLoc, RParenLoc;
3931
3932public:
3933  GenericSelectionExpr(ASTContext &Context,
3934                       SourceLocation GenericLoc, Expr *ControllingExpr,
3935                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3936                       unsigned NumAssocs, SourceLocation DefaultLoc,
3937                       SourceLocation RParenLoc,
3938                       bool ContainsUnexpandedParameterPack,
3939                       unsigned ResultIndex);
3940
3941  /// This constructor is used in the result-dependent case.
3942  GenericSelectionExpr(ASTContext &Context,
3943                       SourceLocation GenericLoc, Expr *ControllingExpr,
3944                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3945                       unsigned NumAssocs, SourceLocation DefaultLoc,
3946                       SourceLocation RParenLoc,
3947                       bool ContainsUnexpandedParameterPack);
3948
3949  explicit GenericSelectionExpr(EmptyShell Empty)
3950    : Expr(GenericSelectionExprClass, Empty) { }
3951
3952  unsigned getNumAssocs() const { return NumAssocs; }
3953
3954  SourceLocation getGenericLoc() const { return GenericLoc; }
3955  SourceLocation getDefaultLoc() const { return DefaultLoc; }
3956  SourceLocation getRParenLoc() const { return RParenLoc; }
3957
3958  const Expr *getAssocExpr(unsigned i) const {
3959    return cast<Expr>(SubExprs[END_EXPR+i]);
3960  }
3961  Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
3962
3963  const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
3964    return AssocTypes[i];
3965  }
3966  TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
3967
3968  QualType getAssocType(unsigned i) const {
3969    if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
3970      return TS->getType();
3971    else
3972      return QualType();
3973  }
3974
3975  const Expr *getControllingExpr() const {
3976    return cast<Expr>(SubExprs[CONTROLLING]);
3977  }
3978  Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
3979
3980  /// Whether this generic selection is result-dependent.
3981  bool isResultDependent() const { return ResultIndex == -1U; }
3982
3983  /// The zero-based index of the result expression's generic association in
3984  /// the generic selection's association list.  Defined only if the
3985  /// generic selection is not result-dependent.
3986  unsigned getResultIndex() const {
3987    assert(!isResultDependent() && "Generic selection is result-dependent");
3988    return ResultIndex;
3989  }
3990
3991  /// The generic selection's result expression.  Defined only if the
3992  /// generic selection is not result-dependent.
3993  const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
3994  Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
3995
3996  SourceRange getSourceRange() const {
3997    return SourceRange(GenericLoc, RParenLoc);
3998  }
3999  static bool classof(const Stmt *T) {
4000    return T->getStmtClass() == GenericSelectionExprClass;
4001  }
4002  static bool classof(const GenericSelectionExpr *) { return true; }
4003
4004  child_range children() {
4005    return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4006  }
4007
4008  friend class ASTStmtReader;
4009};
4010
4011//===----------------------------------------------------------------------===//
4012// Clang Extensions
4013//===----------------------------------------------------------------------===//
4014
4015
4016/// ExtVectorElementExpr - This represents access to specific elements of a
4017/// vector, and may occur on the left hand side or right hand side.  For example
4018/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
4019///
4020/// Note that the base may have either vector or pointer to vector type, just
4021/// like a struct field reference.
4022///
4023class ExtVectorElementExpr : public Expr {
4024  Stmt *Base;
4025  IdentifierInfo *Accessor;
4026  SourceLocation AccessorLoc;
4027public:
4028  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4029                       IdentifierInfo &accessor, SourceLocation loc)
4030    : Expr(ExtVectorElementExprClass, ty, VK,
4031           (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4032           base->isTypeDependent(), base->isValueDependent(),
4033           base->isInstantiationDependent(),
4034           base->containsUnexpandedParameterPack()),
4035      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4036
4037  /// \brief Build an empty vector element expression.
4038  explicit ExtVectorElementExpr(EmptyShell Empty)
4039    : Expr(ExtVectorElementExprClass, Empty) { }
4040
4041  const Expr *getBase() const { return cast<Expr>(Base); }
4042  Expr *getBase() { return cast<Expr>(Base); }
4043  void setBase(Expr *E) { Base = E; }
4044
4045  IdentifierInfo &getAccessor() const { return *Accessor; }
4046  void setAccessor(IdentifierInfo *II) { Accessor = II; }
4047
4048  SourceLocation getAccessorLoc() const { return AccessorLoc; }
4049  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4050
4051  /// getNumElements - Get the number of components being selected.
4052  unsigned getNumElements() const;
4053
4054  /// containsDuplicateElements - Return true if any element access is
4055  /// repeated.
4056  bool containsDuplicateElements() const;
4057
4058  /// getEncodedElementAccess - Encode the elements accessed into an llvm
4059  /// aggregate Constant of ConstantInt(s).
4060  void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4061
4062  SourceRange getSourceRange() const {
4063    return SourceRange(getBase()->getLocStart(), AccessorLoc);
4064  }
4065
4066  /// isArrow - Return true if the base expression is a pointer to vector,
4067  /// return false if the base expression is a vector.
4068  bool isArrow() const;
4069
4070  static bool classof(const Stmt *T) {
4071    return T->getStmtClass() == ExtVectorElementExprClass;
4072  }
4073  static bool classof(const ExtVectorElementExpr *) { return true; }
4074
4075  // Iterators
4076  child_range children() { return child_range(&Base, &Base+1); }
4077};
4078
4079
4080/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4081/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
4082class BlockExpr : public Expr {
4083protected:
4084  BlockDecl *TheBlock;
4085public:
4086  BlockExpr(BlockDecl *BD, QualType ty)
4087    : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4088           ty->isDependentType(), false,
4089           // FIXME: Check for instantiate-dependence in the statement?
4090           ty->isInstantiationDependentType(),
4091           false),
4092      TheBlock(BD) {}
4093
4094  /// \brief Build an empty block expression.
4095  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4096
4097  const BlockDecl *getBlockDecl() const { return TheBlock; }
4098  BlockDecl *getBlockDecl() { return TheBlock; }
4099  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4100
4101  // Convenience functions for probing the underlying BlockDecl.
4102  SourceLocation getCaretLocation() const;
4103  const Stmt *getBody() const;
4104  Stmt *getBody();
4105
4106  SourceRange getSourceRange() const {
4107    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
4108  }
4109
4110  /// getFunctionType - Return the underlying function type for this block.
4111  const FunctionType *getFunctionType() const;
4112
4113  static bool classof(const Stmt *T) {
4114    return T->getStmtClass() == BlockExprClass;
4115  }
4116  static bool classof(const BlockExpr *) { return true; }
4117
4118  // Iterators
4119  child_range children() { return child_range(); }
4120};
4121
4122/// BlockDeclRefExpr - A reference to a local variable declared in an
4123/// enclosing scope.
4124class BlockDeclRefExpr : public Expr {
4125  VarDecl *D;
4126  SourceLocation Loc;
4127  bool IsByRef : 1;
4128  bool ConstQualAdded : 1;
4129public:
4130  BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
4131                   SourceLocation l, bool ByRef, bool constAdded = false);
4132
4133  // \brief Build an empty reference to a declared variable in a
4134  // block.
4135  explicit BlockDeclRefExpr(EmptyShell Empty)
4136    : Expr(BlockDeclRefExprClass, Empty) { }
4137
4138  VarDecl *getDecl() { return D; }
4139  const VarDecl *getDecl() const { return D; }
4140  void setDecl(VarDecl *VD) { D = VD; }
4141
4142  SourceLocation getLocation() const { return Loc; }
4143  void setLocation(SourceLocation L) { Loc = L; }
4144
4145  SourceRange getSourceRange() const { return SourceRange(Loc); }
4146
4147  bool isByRef() const { return IsByRef; }
4148  void setByRef(bool BR) { IsByRef = BR; }
4149
4150  bool isConstQualAdded() const { return ConstQualAdded; }
4151  void setConstQualAdded(bool C) { ConstQualAdded = C; }
4152
4153  static bool classof(const Stmt *T) {
4154    return T->getStmtClass() == BlockDeclRefExprClass;
4155  }
4156  static bool classof(const BlockDeclRefExpr *) { return true; }
4157
4158  // Iterators
4159  child_range children() { return child_range(); }
4160};
4161
4162/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4163/// This AST node provides support for reinterpreting a type to another
4164/// type of the same size.
4165class AsTypeExpr : public Expr { // Should this be an ExplicitCastExpr?
4166private:
4167  Stmt *SrcExpr;
4168  SourceLocation BuiltinLoc, RParenLoc;
4169
4170  friend class ASTReader;
4171  friend class ASTStmtReader;
4172  explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4173
4174public:
4175  AsTypeExpr(Expr* SrcExpr, QualType DstType,
4176             ExprValueKind VK, ExprObjectKind OK,
4177             SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4178    : Expr(AsTypeExprClass, DstType, VK, OK,
4179           DstType->isDependentType(),
4180           DstType->isDependentType() || SrcExpr->isValueDependent(),
4181           (DstType->isInstantiationDependentType() ||
4182            SrcExpr->isInstantiationDependent()),
4183           (DstType->containsUnexpandedParameterPack() ||
4184            SrcExpr->containsUnexpandedParameterPack())),
4185  SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4186
4187  /// getSrcExpr - Return the Expr to be converted.
4188  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4189
4190  /// getBuiltinLoc - Return the location of the __builtin_astype token.
4191  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4192
4193  /// getRParenLoc - Return the location of final right parenthesis.
4194  SourceLocation getRParenLoc() const { return RParenLoc; }
4195
4196  SourceRange getSourceRange() const {
4197    return SourceRange(BuiltinLoc, RParenLoc);
4198  }
4199
4200  static bool classof(const Stmt *T) {
4201    return T->getStmtClass() == AsTypeExprClass;
4202  }
4203  static bool classof(const AsTypeExpr *) { return true; }
4204
4205  // Iterators
4206  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4207};
4208
4209/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4210/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4211/// similarly-named C++0x instructions.  All of these instructions take one
4212/// primary pointer and at least one memory order.
4213class AtomicExpr : public Expr {
4214public:
4215  enum AtomicOp { Load, Store, CmpXchgStrong, CmpXchgWeak, Xchg,
4216                  Add, Sub, And, Or, Xor };
4217private:
4218  enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, END_EXPR };
4219  Stmt* SubExprs[END_EXPR];
4220  unsigned NumSubExprs;
4221  SourceLocation BuiltinLoc, RParenLoc;
4222  AtomicOp Op;
4223
4224public:
4225  AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr, QualType t,
4226             AtomicOp op, SourceLocation RP);
4227
4228  /// \brief Build an empty AtomicExpr.
4229  explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4230
4231  Expr *getPtr() const {
4232    return cast<Expr>(SubExprs[PTR]);
4233  }
4234  void setPtr(Expr *E) {
4235    SubExprs[PTR] = E;
4236  }
4237  Expr *getOrder() const {
4238    return cast<Expr>(SubExprs[ORDER]);
4239  }
4240  void setOrder(Expr *E) {
4241    SubExprs[ORDER] = E;
4242  }
4243  Expr *getVal1() const {
4244    assert(NumSubExprs >= 3);
4245    return cast<Expr>(SubExprs[VAL1]);
4246  }
4247  void setVal1(Expr *E) {
4248    assert(NumSubExprs >= 3);
4249    SubExprs[VAL1] = E;
4250  }
4251  Expr *getOrderFail() const {
4252    assert(NumSubExprs == 5);
4253    return cast<Expr>(SubExprs[ORDER_FAIL]);
4254  }
4255  void setOrderFail(Expr *E) {
4256    assert(NumSubExprs == 5);
4257    SubExprs[ORDER_FAIL] = E;
4258  }
4259  Expr *getVal2() const {
4260    assert(NumSubExprs == 5);
4261    return cast<Expr>(SubExprs[VAL2]);
4262  }
4263  void setVal2(Expr *E) {
4264    assert(NumSubExprs == 5);
4265    SubExprs[VAL2] = E;
4266  }
4267
4268  AtomicOp getOp() const { return Op; }
4269  void setOp(AtomicOp op) { Op = op; }
4270  unsigned getNumSubExprs() { return NumSubExprs; }
4271  void setNumSubExprs(unsigned num) { NumSubExprs = num; }
4272
4273  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4274
4275  bool isVolatile() const {
4276    return getPtr()->getType()->getPointeeType().isVolatileQualified();
4277  }
4278
4279  bool isCmpXChg() const {
4280    return getOp() == AtomicExpr::CmpXchgStrong ||
4281           getOp() == AtomicExpr::CmpXchgWeak;
4282  }
4283
4284  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4285  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4286
4287  SourceLocation getRParenLoc() const { return RParenLoc; }
4288  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4289
4290  SourceRange getSourceRange() const {
4291    return SourceRange(BuiltinLoc, RParenLoc);
4292  }
4293  static bool classof(const Stmt *T) {
4294    return T->getStmtClass() == AtomicExprClass;
4295  }
4296  static bool classof(const AtomicExpr *) { return true; }
4297
4298  // Iterators
4299  child_range children() {
4300    return child_range(SubExprs, SubExprs+NumSubExprs);
4301  }
4302};
4303}  // end namespace clang
4304
4305#endif
4306