Expr.h revision 64f45a24b19eb89ff88f7c3ff0df9be8e861ac97
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  union {
1275    const char *asChar;
1276    const uint16_t *asUInt16;
1277    const uint32_t *asUInt32;
1278  } StrData;
1279  unsigned Length;
1280  unsigned CharByteWidth;
1281  unsigned NumConcatenated;
1282  unsigned Kind : 3;
1283  bool IsPascal : 1;
1284  SourceLocation TokLocs[1];
1285
1286  StringLiteral(QualType Ty) :
1287    Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1288         false) {}
1289
1290  static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1291
1292public:
1293  /// This is the "fully general" constructor that allows representation of
1294  /// strings formed from multiple concatenated tokens.
1295  static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1296                               bool Pascal, QualType Ty,
1297                               const SourceLocation *Loc, unsigned NumStrs);
1298
1299  /// Simple constructor for string literals made from one token.
1300  static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1301                               bool Pascal, QualType Ty,
1302                               SourceLocation Loc) {
1303    return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1304  }
1305
1306  /// \brief Construct an empty string literal.
1307  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1308
1309  StringRef getString() const {
1310    assert(CharByteWidth==1
1311           && "This function is used in places that assume strings use char");
1312    return StringRef(StrData.asChar, getByteLength());
1313  }
1314
1315  /// Allow clients that need the byte representation, such as ASTWriterStmt
1316  /// ::VisitStringLiteral(), access.
1317  StringRef getBytes() const {
1318    // FIXME: StringRef may not be the right type to use as a result for this...
1319    assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
1320           && "unsupported CharByteWidth");
1321    if (CharByteWidth==4) {
1322      return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1323                       getByteLength());
1324    } else if (CharByteWidth==2) {
1325      return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1326                       getByteLength());
1327    } else {
1328      return StringRef(StrData.asChar, getByteLength());
1329    }
1330  }
1331
1332  uint32_t getCodeUnit(size_t i) const {
1333    assert(i<Length && "out of bounds access");
1334    assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
1335           && "unsupported CharByteWidth");
1336    if (CharByteWidth==4) {
1337      return StrData.asUInt32[i];
1338    } else if (CharByteWidth==2) {
1339      return StrData.asUInt16[i];
1340    } else {
1341      return static_cast<unsigned char>(StrData.asChar[i]);
1342    }
1343  }
1344
1345  unsigned getByteLength() const { return CharByteWidth*Length; }
1346  unsigned getLength() const { return Length; }
1347  unsigned getCharByteWidth() const { return CharByteWidth; }
1348
1349  /// \brief Sets the string data to the given string data.
1350  void setString(ASTContext &C, StringRef Str,
1351                 StringKind Kind, bool IsPascal);
1352
1353  StringKind getKind() const { return static_cast<StringKind>(Kind); }
1354
1355
1356  bool isAscii() const { return Kind == Ascii; }
1357  bool isWide() const { return Kind == Wide; }
1358  bool isUTF8() const { return Kind == UTF8; }
1359  bool isUTF16() const { return Kind == UTF16; }
1360  bool isUTF32() const { return Kind == UTF32; }
1361  bool isPascal() const { return IsPascal; }
1362
1363  bool containsNonAsciiOrNull() const {
1364    StringRef Str = getString();
1365    for (unsigned i = 0, e = Str.size(); i != e; ++i)
1366      if (!isascii(Str[i]) || !Str[i])
1367        return true;
1368    return false;
1369  }
1370
1371  /// getNumConcatenated - Get the number of string literal tokens that were
1372  /// concatenated in translation phase #6 to form this string literal.
1373  unsigned getNumConcatenated() const { return NumConcatenated; }
1374
1375  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1376    assert(TokNum < NumConcatenated && "Invalid tok number");
1377    return TokLocs[TokNum];
1378  }
1379  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1380    assert(TokNum < NumConcatenated && "Invalid tok number");
1381    TokLocs[TokNum] = L;
1382  }
1383
1384  /// getLocationOfByte - Return a source location that points to the specified
1385  /// byte of this string literal.
1386  ///
1387  /// Strings are amazingly complex.  They can be formed from multiple tokens
1388  /// and can have escape sequences in them in addition to the usual trigraph
1389  /// and escaped newline business.  This routine handles this complexity.
1390  ///
1391  SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1392                                   const LangOptions &Features,
1393                                   const TargetInfo &Target) const;
1394
1395  typedef const SourceLocation *tokloc_iterator;
1396  tokloc_iterator tokloc_begin() const { return TokLocs; }
1397  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1398
1399  SourceRange getSourceRange() const {
1400    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
1401  }
1402  static bool classof(const Stmt *T) {
1403    return T->getStmtClass() == StringLiteralClass;
1404  }
1405  static bool classof(const StringLiteral *) { return true; }
1406
1407  // Iterators
1408  child_range children() { return child_range(); }
1409};
1410
1411/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
1412/// AST node is only formed if full location information is requested.
1413class ParenExpr : public Expr {
1414  SourceLocation L, R;
1415  Stmt *Val;
1416public:
1417  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1418    : Expr(ParenExprClass, val->getType(),
1419           val->getValueKind(), val->getObjectKind(),
1420           val->isTypeDependent(), val->isValueDependent(),
1421           val->isInstantiationDependent(),
1422           val->containsUnexpandedParameterPack()),
1423      L(l), R(r), Val(val) {}
1424
1425  /// \brief Construct an empty parenthesized expression.
1426  explicit ParenExpr(EmptyShell Empty)
1427    : Expr(ParenExprClass, Empty) { }
1428
1429  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1430  Expr *getSubExpr() { return cast<Expr>(Val); }
1431  void setSubExpr(Expr *E) { Val = E; }
1432
1433  SourceRange getSourceRange() const { return SourceRange(L, R); }
1434
1435  /// \brief Get the location of the left parentheses '('.
1436  SourceLocation getLParen() const { return L; }
1437  void setLParen(SourceLocation Loc) { L = Loc; }
1438
1439  /// \brief Get the location of the right parentheses ')'.
1440  SourceLocation getRParen() const { return R; }
1441  void setRParen(SourceLocation Loc) { R = Loc; }
1442
1443  static bool classof(const Stmt *T) {
1444    return T->getStmtClass() == ParenExprClass;
1445  }
1446  static bool classof(const ParenExpr *) { return true; }
1447
1448  // Iterators
1449  child_range children() { return child_range(&Val, &Val+1); }
1450};
1451
1452
1453/// UnaryOperator - This represents the unary-expression's (except sizeof and
1454/// alignof), the postinc/postdec operators from postfix-expression, and various
1455/// extensions.
1456///
1457/// Notes on various nodes:
1458///
1459/// Real/Imag - These return the real/imag part of a complex operand.  If
1460///   applied to a non-complex value, the former returns its operand and the
1461///   later returns zero in the type of the operand.
1462///
1463class UnaryOperator : public Expr {
1464public:
1465  typedef UnaryOperatorKind Opcode;
1466
1467private:
1468  unsigned Opc : 5;
1469  SourceLocation Loc;
1470  Stmt *Val;
1471public:
1472
1473  UnaryOperator(Expr *input, Opcode opc, QualType type,
1474                ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1475    : Expr(UnaryOperatorClass, type, VK, OK,
1476           input->isTypeDependent() || type->isDependentType(),
1477           input->isValueDependent(),
1478           (input->isInstantiationDependent() ||
1479            type->isInstantiationDependentType()),
1480           input->containsUnexpandedParameterPack()),
1481      Opc(opc), Loc(l), Val(input) {}
1482
1483  /// \brief Build an empty unary operator.
1484  explicit UnaryOperator(EmptyShell Empty)
1485    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1486
1487  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1488  void setOpcode(Opcode O) { Opc = O; }
1489
1490  Expr *getSubExpr() const { return cast<Expr>(Val); }
1491  void setSubExpr(Expr *E) { Val = E; }
1492
1493  /// getOperatorLoc - Return the location of the operator.
1494  SourceLocation getOperatorLoc() const { return Loc; }
1495  void setOperatorLoc(SourceLocation L) { Loc = L; }
1496
1497  /// isPostfix - Return true if this is a postfix operation, like x++.
1498  static bool isPostfix(Opcode Op) {
1499    return Op == UO_PostInc || Op == UO_PostDec;
1500  }
1501
1502  /// isPrefix - Return true if this is a prefix operation, like --x.
1503  static bool isPrefix(Opcode Op) {
1504    return Op == UO_PreInc || Op == UO_PreDec;
1505  }
1506
1507  bool isPrefix() const { return isPrefix(getOpcode()); }
1508  bool isPostfix() const { return isPostfix(getOpcode()); }
1509
1510  static bool isIncrementOp(Opcode Op) {
1511    return Op == UO_PreInc || Op == UO_PostInc;
1512  }
1513  bool isIncrementOp() const {
1514    return isIncrementOp(getOpcode());
1515  }
1516
1517  static bool isDecrementOp(Opcode Op) {
1518    return Op == UO_PreDec || Op == UO_PostDec;
1519  }
1520  bool isDecrementOp() const {
1521    return isDecrementOp(getOpcode());
1522  }
1523
1524  static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1525  bool isIncrementDecrementOp() const {
1526    return isIncrementDecrementOp(getOpcode());
1527  }
1528
1529  static bool isArithmeticOp(Opcode Op) {
1530    return Op >= UO_Plus && Op <= UO_LNot;
1531  }
1532  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1533
1534  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1535  /// corresponds to, e.g. "sizeof" or "[pre]++"
1536  static const char *getOpcodeStr(Opcode Op);
1537
1538  /// \brief Retrieve the unary opcode that corresponds to the given
1539  /// overloaded operator.
1540  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1541
1542  /// \brief Retrieve the overloaded operator kind that corresponds to
1543  /// the given unary opcode.
1544  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1545
1546  SourceRange getSourceRange() const {
1547    if (isPostfix())
1548      return SourceRange(Val->getLocStart(), Loc);
1549    else
1550      return SourceRange(Loc, Val->getLocEnd());
1551  }
1552  SourceLocation getExprLoc() const { return Loc; }
1553
1554  static bool classof(const Stmt *T) {
1555    return T->getStmtClass() == UnaryOperatorClass;
1556  }
1557  static bool classof(const UnaryOperator *) { return true; }
1558
1559  // Iterators
1560  child_range children() { return child_range(&Val, &Val+1); }
1561};
1562
1563/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1564/// offsetof(record-type, member-designator). For example, given:
1565/// @code
1566/// struct S {
1567///   float f;
1568///   double d;
1569/// };
1570/// struct T {
1571///   int i;
1572///   struct S s[10];
1573/// };
1574/// @endcode
1575/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1576
1577class OffsetOfExpr : public Expr {
1578public:
1579  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1580  class OffsetOfNode {
1581  public:
1582    /// \brief The kind of offsetof node we have.
1583    enum Kind {
1584      /// \brief An index into an array.
1585      Array = 0x00,
1586      /// \brief A field.
1587      Field = 0x01,
1588      /// \brief A field in a dependent type, known only by its name.
1589      Identifier = 0x02,
1590      /// \brief An implicit indirection through a C++ base class, when the
1591      /// field found is in a base class.
1592      Base = 0x03
1593    };
1594
1595  private:
1596    enum { MaskBits = 2, Mask = 0x03 };
1597
1598    /// \brief The source range that covers this part of the designator.
1599    SourceRange Range;
1600
1601    /// \brief The data describing the designator, which comes in three
1602    /// different forms, depending on the lower two bits.
1603    ///   - An unsigned index into the array of Expr*'s stored after this node
1604    ///     in memory, for [constant-expression] designators.
1605    ///   - A FieldDecl*, for references to a known field.
1606    ///   - An IdentifierInfo*, for references to a field with a given name
1607    ///     when the class type is dependent.
1608    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1609    ///     base class.
1610    uintptr_t Data;
1611
1612  public:
1613    /// \brief Create an offsetof node that refers to an array element.
1614    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1615                 SourceLocation RBracketLoc)
1616      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1617
1618    /// \brief Create an offsetof node that refers to a field.
1619    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1620                 SourceLocation NameLoc)
1621      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1622        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1623
1624    /// \brief Create an offsetof node that refers to an identifier.
1625    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1626                 SourceLocation NameLoc)
1627      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1628        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1629
1630    /// \brief Create an offsetof node that refers into a C++ base class.
1631    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1632      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1633
1634    /// \brief Determine what kind of offsetof node this is.
1635    Kind getKind() const {
1636      return static_cast<Kind>(Data & Mask);
1637    }
1638
1639    /// \brief For an array element node, returns the index into the array
1640    /// of expressions.
1641    unsigned getArrayExprIndex() const {
1642      assert(getKind() == Array);
1643      return Data >> 2;
1644    }
1645
1646    /// \brief For a field offsetof node, returns the field.
1647    FieldDecl *getField() const {
1648      assert(getKind() == Field);
1649      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1650    }
1651
1652    /// \brief For a field or identifier offsetof node, returns the name of
1653    /// the field.
1654    IdentifierInfo *getFieldName() const;
1655
1656    /// \brief For a base class node, returns the base specifier.
1657    CXXBaseSpecifier *getBase() const {
1658      assert(getKind() == Base);
1659      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1660    }
1661
1662    /// \brief Retrieve the source range that covers this offsetof node.
1663    ///
1664    /// For an array element node, the source range contains the locations of
1665    /// the square brackets. For a field or identifier node, the source range
1666    /// contains the location of the period (if there is one) and the
1667    /// identifier.
1668    SourceRange getSourceRange() const { return Range; }
1669  };
1670
1671private:
1672
1673  SourceLocation OperatorLoc, RParenLoc;
1674  // Base type;
1675  TypeSourceInfo *TSInfo;
1676  // Number of sub-components (i.e. instances of OffsetOfNode).
1677  unsigned NumComps;
1678  // Number of sub-expressions (i.e. array subscript expressions).
1679  unsigned NumExprs;
1680
1681  OffsetOfExpr(ASTContext &C, QualType type,
1682               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1683               OffsetOfNode* compsPtr, unsigned numComps,
1684               Expr** exprsPtr, unsigned numExprs,
1685               SourceLocation RParenLoc);
1686
1687  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1688    : Expr(OffsetOfExprClass, EmptyShell()),
1689      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1690
1691public:
1692
1693  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1694                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1695                              OffsetOfNode* compsPtr, unsigned numComps,
1696                              Expr** exprsPtr, unsigned numExprs,
1697                              SourceLocation RParenLoc);
1698
1699  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1700                                   unsigned NumComps, unsigned NumExprs);
1701
1702  /// getOperatorLoc - Return the location of the operator.
1703  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1704  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1705
1706  /// \brief Return the location of the right parentheses.
1707  SourceLocation getRParenLoc() const { return RParenLoc; }
1708  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1709
1710  TypeSourceInfo *getTypeSourceInfo() const {
1711    return TSInfo;
1712  }
1713  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1714    TSInfo = tsi;
1715  }
1716
1717  const OffsetOfNode &getComponent(unsigned Idx) const {
1718    assert(Idx < NumComps && "Subscript out of range");
1719    return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1720  }
1721
1722  void setComponent(unsigned Idx, OffsetOfNode ON) {
1723    assert(Idx < NumComps && "Subscript out of range");
1724    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1725  }
1726
1727  unsigned getNumComponents() const {
1728    return NumComps;
1729  }
1730
1731  Expr* getIndexExpr(unsigned Idx) {
1732    assert(Idx < NumExprs && "Subscript out of range");
1733    return reinterpret_cast<Expr **>(
1734                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1735  }
1736  const Expr *getIndexExpr(unsigned Idx) const {
1737    return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1738  }
1739
1740  void setIndexExpr(unsigned Idx, Expr* E) {
1741    assert(Idx < NumComps && "Subscript out of range");
1742    reinterpret_cast<Expr **>(
1743                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1744  }
1745
1746  unsigned getNumExpressions() const {
1747    return NumExprs;
1748  }
1749
1750  SourceRange getSourceRange() const {
1751    return SourceRange(OperatorLoc, RParenLoc);
1752  }
1753
1754  static bool classof(const Stmt *T) {
1755    return T->getStmtClass() == OffsetOfExprClass;
1756  }
1757
1758  static bool classof(const OffsetOfExpr *) { return true; }
1759
1760  // Iterators
1761  child_range children() {
1762    Stmt **begin =
1763      reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1764                               + NumComps);
1765    return child_range(begin, begin + NumExprs);
1766  }
1767};
1768
1769/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1770/// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
1771/// vec_step (OpenCL 1.1 6.11.12).
1772class UnaryExprOrTypeTraitExpr : public Expr {
1773  unsigned Kind : 2;
1774  bool isType : 1;    // true if operand is a type, false if an expression
1775  union {
1776    TypeSourceInfo *Ty;
1777    Stmt *Ex;
1778  } Argument;
1779  SourceLocation OpLoc, RParenLoc;
1780
1781public:
1782  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1783                           QualType resultType, SourceLocation op,
1784                           SourceLocation rp) :
1785      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1786           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1787           // Value-dependent if the argument is type-dependent.
1788           TInfo->getType()->isDependentType(),
1789           TInfo->getType()->isInstantiationDependentType(),
1790           TInfo->getType()->containsUnexpandedParameterPack()),
1791      Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) {
1792    Argument.Ty = TInfo;
1793  }
1794
1795  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1796                           QualType resultType, SourceLocation op,
1797                           SourceLocation rp) :
1798      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1799           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1800           // Value-dependent if the argument is type-dependent.
1801           E->isTypeDependent(),
1802           E->isInstantiationDependent(),
1803           E->containsUnexpandedParameterPack()),
1804      Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) {
1805    Argument.Ex = E;
1806  }
1807
1808  /// \brief Construct an empty sizeof/alignof expression.
1809  explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1810    : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1811
1812  UnaryExprOrTypeTrait getKind() const {
1813    return static_cast<UnaryExprOrTypeTrait>(Kind);
1814  }
1815  void setKind(UnaryExprOrTypeTrait K) { Kind = K; }
1816
1817  bool isArgumentType() const { return isType; }
1818  QualType getArgumentType() const {
1819    return getArgumentTypeInfo()->getType();
1820  }
1821  TypeSourceInfo *getArgumentTypeInfo() const {
1822    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1823    return Argument.Ty;
1824  }
1825  Expr *getArgumentExpr() {
1826    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1827    return static_cast<Expr*>(Argument.Ex);
1828  }
1829  const Expr *getArgumentExpr() const {
1830    return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
1831  }
1832
1833  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1834  void setArgument(TypeSourceInfo *TInfo) {
1835    Argument.Ty = TInfo;
1836    isType = true;
1837  }
1838
1839  /// Gets the argument type, or the type of the argument expression, whichever
1840  /// is appropriate.
1841  QualType getTypeOfArgument() const {
1842    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1843  }
1844
1845  SourceLocation getOperatorLoc() const { return OpLoc; }
1846  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1847
1848  SourceLocation getRParenLoc() const { return RParenLoc; }
1849  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1850
1851  SourceRange getSourceRange() const {
1852    return SourceRange(OpLoc, RParenLoc);
1853  }
1854
1855  static bool classof(const Stmt *T) {
1856    return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
1857  }
1858  static bool classof(const UnaryExprOrTypeTraitExpr *) { return true; }
1859
1860  // Iterators
1861  child_range children();
1862};
1863
1864//===----------------------------------------------------------------------===//
1865// Postfix Operators.
1866//===----------------------------------------------------------------------===//
1867
1868/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1869class ArraySubscriptExpr : public Expr {
1870  enum { LHS, RHS, END_EXPR=2 };
1871  Stmt* SubExprs[END_EXPR];
1872  SourceLocation RBracketLoc;
1873public:
1874  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1875                     ExprValueKind VK, ExprObjectKind OK,
1876                     SourceLocation rbracketloc)
1877  : Expr(ArraySubscriptExprClass, t, VK, OK,
1878         lhs->isTypeDependent() || rhs->isTypeDependent(),
1879         lhs->isValueDependent() || rhs->isValueDependent(),
1880         (lhs->isInstantiationDependent() ||
1881          rhs->isInstantiationDependent()),
1882         (lhs->containsUnexpandedParameterPack() ||
1883          rhs->containsUnexpandedParameterPack())),
1884    RBracketLoc(rbracketloc) {
1885    SubExprs[LHS] = lhs;
1886    SubExprs[RHS] = rhs;
1887  }
1888
1889  /// \brief Create an empty array subscript expression.
1890  explicit ArraySubscriptExpr(EmptyShell Shell)
1891    : Expr(ArraySubscriptExprClass, Shell) { }
1892
1893  /// An array access can be written A[4] or 4[A] (both are equivalent).
1894  /// - getBase() and getIdx() always present the normalized view: A[4].
1895  ///    In this case getBase() returns "A" and getIdx() returns "4".
1896  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1897  ///    4[A] getLHS() returns "4".
1898  /// Note: Because vector element access is also written A[4] we must
1899  /// predicate the format conversion in getBase and getIdx only on the
1900  /// the type of the RHS, as it is possible for the LHS to be a vector of
1901  /// integer type
1902  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1903  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1904  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1905
1906  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1907  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1908  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1909
1910  Expr *getBase() {
1911    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1912  }
1913
1914  const Expr *getBase() const {
1915    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1916  }
1917
1918  Expr *getIdx() {
1919    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1920  }
1921
1922  const Expr *getIdx() const {
1923    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1924  }
1925
1926  SourceRange getSourceRange() const {
1927    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1928  }
1929
1930  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1931  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1932
1933  SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1934
1935  static bool classof(const Stmt *T) {
1936    return T->getStmtClass() == ArraySubscriptExprClass;
1937  }
1938  static bool classof(const ArraySubscriptExpr *) { return true; }
1939
1940  // Iterators
1941  child_range children() {
1942    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
1943  }
1944};
1945
1946
1947/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1948/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1949/// while its subclasses may represent alternative syntax that (semantically)
1950/// results in a function call. For example, CXXOperatorCallExpr is
1951/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1952/// "str1 + str2" to resolve to a function call.
1953class CallExpr : public Expr {
1954  enum { FN=0, PREARGS_START=1 };
1955  Stmt **SubExprs;
1956  unsigned NumArgs;
1957  SourceLocation RParenLoc;
1958
1959protected:
1960  // These versions of the constructor are for derived classes.
1961  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
1962           Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
1963           SourceLocation rparenloc);
1964  CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty);
1965
1966  Stmt *getPreArg(unsigned i) {
1967    assert(i < getNumPreArgs() && "Prearg access out of range!");
1968    return SubExprs[PREARGS_START+i];
1969  }
1970  const Stmt *getPreArg(unsigned i) const {
1971    assert(i < getNumPreArgs() && "Prearg access out of range!");
1972    return SubExprs[PREARGS_START+i];
1973  }
1974  void setPreArg(unsigned i, Stmt *PreArg) {
1975    assert(i < getNumPreArgs() && "Prearg access out of range!");
1976    SubExprs[PREARGS_START+i] = PreArg;
1977  }
1978
1979  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
1980
1981public:
1982  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1983           ExprValueKind VK, SourceLocation rparenloc);
1984
1985  /// \brief Build an empty call expression.
1986  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1987
1988  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1989  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1990  void setCallee(Expr *F) { SubExprs[FN] = F; }
1991
1992  Decl *getCalleeDecl();
1993  const Decl *getCalleeDecl() const {
1994    return const_cast<CallExpr*>(this)->getCalleeDecl();
1995  }
1996
1997  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1998  FunctionDecl *getDirectCallee();
1999  const FunctionDecl *getDirectCallee() const {
2000    return const_cast<CallExpr*>(this)->getDirectCallee();
2001  }
2002
2003  /// getNumArgs - Return the number of actual arguments to this call.
2004  ///
2005  unsigned getNumArgs() const { return NumArgs; }
2006
2007  /// \brief Retrieve the call arguments.
2008  Expr **getArgs() {
2009    return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2010  }
2011  const Expr *const *getArgs() const {
2012    return const_cast<CallExpr*>(this)->getArgs();
2013  }
2014
2015  /// getArg - Return the specified argument.
2016  Expr *getArg(unsigned Arg) {
2017    assert(Arg < NumArgs && "Arg access out of range!");
2018    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2019  }
2020  const Expr *getArg(unsigned Arg) const {
2021    assert(Arg < NumArgs && "Arg access out of range!");
2022    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2023  }
2024
2025  /// setArg - Set the specified argument.
2026  void setArg(unsigned Arg, Expr *ArgExpr) {
2027    assert(Arg < NumArgs && "Arg access out of range!");
2028    SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2029  }
2030
2031  /// setNumArgs - This changes the number of arguments present in this call.
2032  /// Any orphaned expressions are deleted by this, and any new operands are set
2033  /// to null.
2034  void setNumArgs(ASTContext& C, unsigned NumArgs);
2035
2036  typedef ExprIterator arg_iterator;
2037  typedef ConstExprIterator const_arg_iterator;
2038
2039  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2040  arg_iterator arg_end() {
2041    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2042  }
2043  const_arg_iterator arg_begin() const {
2044    return SubExprs+PREARGS_START+getNumPreArgs();
2045  }
2046  const_arg_iterator arg_end() const {
2047    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2048  }
2049
2050  /// getNumCommas - Return the number of commas that must have been present in
2051  /// this function call.
2052  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2053
2054  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
2055  /// not, return 0.
2056  unsigned isBuiltinCall(const ASTContext &Context) const;
2057
2058  /// getCallReturnType - Get the return type of the call expr. This is not
2059  /// always the type of the expr itself, if the return type is a reference
2060  /// type.
2061  QualType getCallReturnType() const;
2062
2063  SourceLocation getRParenLoc() const { return RParenLoc; }
2064  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2065
2066  SourceRange getSourceRange() const;
2067
2068  static bool classof(const Stmt *T) {
2069    return T->getStmtClass() >= firstCallExprConstant &&
2070           T->getStmtClass() <= lastCallExprConstant;
2071  }
2072  static bool classof(const CallExpr *) { return true; }
2073
2074  // Iterators
2075  child_range children() {
2076    return child_range(&SubExprs[0],
2077                       &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2078  }
2079};
2080
2081/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
2082///
2083class MemberExpr : public Expr {
2084  /// Extra data stored in some member expressions.
2085  struct MemberNameQualifier {
2086    /// \brief The nested-name-specifier that qualifies the name, including
2087    /// source-location information.
2088    NestedNameSpecifierLoc QualifierLoc;
2089
2090    /// \brief The DeclAccessPair through which the MemberDecl was found due to
2091    /// name qualifiers.
2092    DeclAccessPair FoundDecl;
2093  };
2094
2095  /// Base - the expression for the base pointer or structure references.  In
2096  /// X.F, this is "X".
2097  Stmt *Base;
2098
2099  /// MemberDecl - This is the decl being referenced by the field/member name.
2100  /// In X.F, this is the decl referenced by F.
2101  ValueDecl *MemberDecl;
2102
2103  /// MemberLoc - This is the location of the member name.
2104  SourceLocation MemberLoc;
2105
2106  /// MemberDNLoc - Provides source/type location info for the
2107  /// declaration name embedded in MemberDecl.
2108  DeclarationNameLoc MemberDNLoc;
2109
2110  /// IsArrow - True if this is "X->F", false if this is "X.F".
2111  bool IsArrow : 1;
2112
2113  /// \brief True if this member expression used a nested-name-specifier to
2114  /// refer to the member, e.g., "x->Base::f", or found its member via a using
2115  /// declaration.  When true, a MemberNameQualifier
2116  /// structure is allocated immediately after the MemberExpr.
2117  bool HasQualifierOrFoundDecl : 1;
2118
2119  /// \brief True if this member expression specified a template argument list
2120  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
2121  /// structure (and its TemplateArguments) are allocated immediately after
2122  /// the MemberExpr or, if the member expression also has a qualifier, after
2123  /// the MemberNameQualifier structure.
2124  bool HasExplicitTemplateArgumentList : 1;
2125
2126  /// \brief True if this member expression refers to a method that
2127  /// was resolved from an overloaded set having size greater than 1.
2128  bool HadMultipleCandidates : 1;
2129
2130  /// \brief Retrieve the qualifier that preceded the member name, if any.
2131  MemberNameQualifier *getMemberQualifier() {
2132    assert(HasQualifierOrFoundDecl);
2133    return reinterpret_cast<MemberNameQualifier *> (this + 1);
2134  }
2135
2136  /// \brief Retrieve the qualifier that preceded the member name, if any.
2137  const MemberNameQualifier *getMemberQualifier() const {
2138    return const_cast<MemberExpr *>(this)->getMemberQualifier();
2139  }
2140
2141public:
2142  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2143             const DeclarationNameInfo &NameInfo, QualType ty,
2144             ExprValueKind VK, ExprObjectKind OK)
2145    : Expr(MemberExprClass, ty, VK, OK,
2146           base->isTypeDependent(),
2147           base->isValueDependent(),
2148           base->isInstantiationDependent(),
2149           base->containsUnexpandedParameterPack()),
2150      Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
2151      MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
2152      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false),
2153      HadMultipleCandidates(false) {
2154    assert(memberdecl->getDeclName() == NameInfo.getName());
2155  }
2156
2157  // NOTE: this constructor should be used only when it is known that
2158  // the member name can not provide additional syntactic info
2159  // (i.e., source locations for C++ operator names or type source info
2160  // for constructors, destructors and conversion oeprators).
2161  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2162             SourceLocation l, QualType ty,
2163             ExprValueKind VK, ExprObjectKind OK)
2164    : Expr(MemberExprClass, ty, VK, OK,
2165           base->isTypeDependent(), base->isValueDependent(),
2166           base->isInstantiationDependent(),
2167           base->containsUnexpandedParameterPack()),
2168      Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
2169      IsArrow(isarrow),
2170      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false),
2171      HadMultipleCandidates(false) {}
2172
2173  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
2174                            NestedNameSpecifierLoc QualifierLoc,
2175                            ValueDecl *memberdecl, DeclAccessPair founddecl,
2176                            DeclarationNameInfo MemberNameInfo,
2177                            const TemplateArgumentListInfo *targs,
2178                            QualType ty, ExprValueKind VK, ExprObjectKind OK);
2179
2180  void setBase(Expr *E) { Base = E; }
2181  Expr *getBase() const { return cast<Expr>(Base); }
2182
2183  /// \brief Retrieve the member declaration to which this expression refers.
2184  ///
2185  /// The returned declaration will either be a FieldDecl or (in C++)
2186  /// a CXXMethodDecl.
2187  ValueDecl *getMemberDecl() const { return MemberDecl; }
2188  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2189
2190  /// \brief Retrieves the declaration found by lookup.
2191  DeclAccessPair getFoundDecl() const {
2192    if (!HasQualifierOrFoundDecl)
2193      return DeclAccessPair::make(getMemberDecl(),
2194                                  getMemberDecl()->getAccess());
2195    return getMemberQualifier()->FoundDecl;
2196  }
2197
2198  /// \brief Determines whether this member expression actually had
2199  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2200  /// x->Base::foo.
2201  bool hasQualifier() const { return getQualifier() != 0; }
2202
2203  /// \brief If the member name was qualified, retrieves the
2204  /// nested-name-specifier that precedes the member name. Otherwise, returns
2205  /// NULL.
2206  NestedNameSpecifier *getQualifier() const {
2207    if (!HasQualifierOrFoundDecl)
2208      return 0;
2209
2210    return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2211  }
2212
2213  /// \brief If the member name was qualified, retrieves the
2214  /// nested-name-specifier that precedes the member name, with source-location
2215  /// information.
2216  NestedNameSpecifierLoc getQualifierLoc() const {
2217    if (!hasQualifier())
2218      return NestedNameSpecifierLoc();
2219
2220    return getMemberQualifier()->QualifierLoc;
2221  }
2222
2223  /// \brief Determines whether this member expression actually had a C++
2224  /// template argument list explicitly specified, e.g., x.f<int>.
2225  bool hasExplicitTemplateArgs() const {
2226    return HasExplicitTemplateArgumentList;
2227  }
2228
2229  /// \brief Copies the template arguments (if present) into the given
2230  /// structure.
2231  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2232    if (hasExplicitTemplateArgs())
2233      getExplicitTemplateArgs().copyInto(List);
2234  }
2235
2236  /// \brief Retrieve the explicit template argument list that
2237  /// follow the member template name.  This must only be called on an
2238  /// expression with explicit template arguments.
2239  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2240    assert(HasExplicitTemplateArgumentList);
2241    if (!HasQualifierOrFoundDecl)
2242      return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
2243
2244    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
2245                                                      getMemberQualifier() + 1);
2246  }
2247
2248  /// \brief Retrieve the explicit template argument list that
2249  /// followed the member template name.  This must only be called on
2250  /// an expression with explicit template arguments.
2251  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2252    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2253  }
2254
2255  /// \brief Retrieves the optional explicit template arguments.
2256  /// This points to the same data as getExplicitTemplateArgs(), but
2257  /// returns null if there are no explicit template arguments.
2258  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2259    if (!hasExplicitTemplateArgs()) return 0;
2260    return &getExplicitTemplateArgs();
2261  }
2262
2263  /// \brief Retrieve the location of the left angle bracket following the
2264  /// member name ('<'), if any.
2265  SourceLocation getLAngleLoc() const {
2266    if (!HasExplicitTemplateArgumentList)
2267      return SourceLocation();
2268
2269    return getExplicitTemplateArgs().LAngleLoc;
2270  }
2271
2272  /// \brief Retrieve the template arguments provided as part of this
2273  /// template-id.
2274  const TemplateArgumentLoc *getTemplateArgs() const {
2275    if (!HasExplicitTemplateArgumentList)
2276      return 0;
2277
2278    return getExplicitTemplateArgs().getTemplateArgs();
2279  }
2280
2281  /// \brief Retrieve the number of template arguments provided as part of this
2282  /// template-id.
2283  unsigned getNumTemplateArgs() const {
2284    if (!HasExplicitTemplateArgumentList)
2285      return 0;
2286
2287    return getExplicitTemplateArgs().NumTemplateArgs;
2288  }
2289
2290  /// \brief Retrieve the location of the right angle bracket following the
2291  /// template arguments ('>').
2292  SourceLocation getRAngleLoc() const {
2293    if (!HasExplicitTemplateArgumentList)
2294      return SourceLocation();
2295
2296    return getExplicitTemplateArgs().RAngleLoc;
2297  }
2298
2299  /// \brief Retrieve the member declaration name info.
2300  DeclarationNameInfo getMemberNameInfo() const {
2301    return DeclarationNameInfo(MemberDecl->getDeclName(),
2302                               MemberLoc, MemberDNLoc);
2303  }
2304
2305  bool isArrow() const { return IsArrow; }
2306  void setArrow(bool A) { IsArrow = A; }
2307
2308  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2309  /// location of 'F'.
2310  SourceLocation getMemberLoc() const { return MemberLoc; }
2311  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2312
2313  SourceRange getSourceRange() const;
2314
2315  SourceLocation getExprLoc() const { return MemberLoc; }
2316
2317  /// \brief Determine whether the base of this explicit is implicit.
2318  bool isImplicitAccess() const {
2319    return getBase() && getBase()->isImplicitCXXThis();
2320  }
2321
2322  /// \brief Returns true if this member expression refers to a method that
2323  /// was resolved from an overloaded set having size greater than 1.
2324  bool hadMultipleCandidates() const {
2325    return HadMultipleCandidates;
2326  }
2327  /// \brief Sets the flag telling whether this expression refers to
2328  /// a method that was resolved from an overloaded set having size
2329  /// greater than 1.
2330  void setHadMultipleCandidates(bool V = true) {
2331    HadMultipleCandidates = V;
2332  }
2333
2334  static bool classof(const Stmt *T) {
2335    return T->getStmtClass() == MemberExprClass;
2336  }
2337  static bool classof(const MemberExpr *) { return true; }
2338
2339  // Iterators
2340  child_range children() { return child_range(&Base, &Base+1); }
2341
2342  friend class ASTReader;
2343  friend class ASTStmtWriter;
2344};
2345
2346/// CompoundLiteralExpr - [C99 6.5.2.5]
2347///
2348class CompoundLiteralExpr : public Expr {
2349  /// LParenLoc - If non-null, this is the location of the left paren in a
2350  /// compound literal like "(int){4}".  This can be null if this is a
2351  /// synthesized compound expression.
2352  SourceLocation LParenLoc;
2353
2354  /// The type as written.  This can be an incomplete array type, in
2355  /// which case the actual expression type will be different.
2356  TypeSourceInfo *TInfo;
2357  Stmt *Init;
2358  bool FileScope;
2359public:
2360  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2361                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2362    : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2363           tinfo->getType()->isDependentType(),
2364           init->isValueDependent(),
2365           (init->isInstantiationDependent() ||
2366            tinfo->getType()->isInstantiationDependentType()),
2367           init->containsUnexpandedParameterPack()),
2368      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
2369
2370  /// \brief Construct an empty compound literal.
2371  explicit CompoundLiteralExpr(EmptyShell Empty)
2372    : Expr(CompoundLiteralExprClass, Empty) { }
2373
2374  const Expr *getInitializer() const { return cast<Expr>(Init); }
2375  Expr *getInitializer() { return cast<Expr>(Init); }
2376  void setInitializer(Expr *E) { Init = E; }
2377
2378  bool isFileScope() const { return FileScope; }
2379  void setFileScope(bool FS) { FileScope = FS; }
2380
2381  SourceLocation getLParenLoc() const { return LParenLoc; }
2382  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2383
2384  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
2385  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
2386
2387  SourceRange getSourceRange() const {
2388    // FIXME: Init should never be null.
2389    if (!Init)
2390      return SourceRange();
2391    if (LParenLoc.isInvalid())
2392      return Init->getSourceRange();
2393    return SourceRange(LParenLoc, Init->getLocEnd());
2394  }
2395
2396  static bool classof(const Stmt *T) {
2397    return T->getStmtClass() == CompoundLiteralExprClass;
2398  }
2399  static bool classof(const CompoundLiteralExpr *) { return true; }
2400
2401  // Iterators
2402  child_range children() { return child_range(&Init, &Init+1); }
2403};
2404
2405/// CastExpr - Base class for type casts, including both implicit
2406/// casts (ImplicitCastExpr) and explicit casts that have some
2407/// representation in the source code (ExplicitCastExpr's derived
2408/// classes).
2409class CastExpr : public Expr {
2410public:
2411  typedef clang::CastKind CastKind;
2412
2413private:
2414  Stmt *Op;
2415
2416  void CheckCastConsistency() const;
2417
2418  const CXXBaseSpecifier * const *path_buffer() const {
2419    return const_cast<CastExpr*>(this)->path_buffer();
2420  }
2421  CXXBaseSpecifier **path_buffer();
2422
2423  void setBasePathSize(unsigned basePathSize) {
2424    CastExprBits.BasePathSize = basePathSize;
2425    assert(CastExprBits.BasePathSize == basePathSize &&
2426           "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2427  }
2428
2429protected:
2430  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2431           const CastKind kind, Expr *op, unsigned BasePathSize) :
2432    Expr(SC, ty, VK, OK_Ordinary,
2433         // Cast expressions are type-dependent if the type is
2434         // dependent (C++ [temp.dep.expr]p3).
2435         ty->isDependentType(),
2436         // Cast expressions are value-dependent if the type is
2437         // dependent or if the subexpression is value-dependent.
2438         ty->isDependentType() || (op && op->isValueDependent()),
2439         (ty->isInstantiationDependentType() ||
2440          (op && op->isInstantiationDependent())),
2441         (ty->containsUnexpandedParameterPack() ||
2442          op->containsUnexpandedParameterPack())),
2443    Op(op) {
2444    assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2445    CastExprBits.Kind = kind;
2446    setBasePathSize(BasePathSize);
2447#ifndef NDEBUG
2448    CheckCastConsistency();
2449#endif
2450  }
2451
2452  /// \brief Construct an empty cast.
2453  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2454    : Expr(SC, Empty) {
2455    setBasePathSize(BasePathSize);
2456  }
2457
2458public:
2459  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2460  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2461  const char *getCastKindName() const;
2462
2463  Expr *getSubExpr() { return cast<Expr>(Op); }
2464  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2465  void setSubExpr(Expr *E) { Op = E; }
2466
2467  /// \brief Retrieve the cast subexpression as it was written in the source
2468  /// code, looking through any implicit casts or other intermediate nodes
2469  /// introduced by semantic analysis.
2470  Expr *getSubExprAsWritten();
2471  const Expr *getSubExprAsWritten() const {
2472    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2473  }
2474
2475  typedef CXXBaseSpecifier **path_iterator;
2476  typedef const CXXBaseSpecifier * const *path_const_iterator;
2477  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2478  unsigned path_size() const { return CastExprBits.BasePathSize; }
2479  path_iterator path_begin() { return path_buffer(); }
2480  path_iterator path_end() { return path_buffer() + path_size(); }
2481  path_const_iterator path_begin() const { return path_buffer(); }
2482  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2483
2484  void setCastPath(const CXXCastPath &Path);
2485
2486  static bool classof(const Stmt *T) {
2487    return T->getStmtClass() >= firstCastExprConstant &&
2488           T->getStmtClass() <= lastCastExprConstant;
2489  }
2490  static bool classof(const CastExpr *) { return true; }
2491
2492  // Iterators
2493  child_range children() { return child_range(&Op, &Op+1); }
2494};
2495
2496/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2497/// conversions, which have no direct representation in the original
2498/// source code. For example: converting T[]->T*, void f()->void
2499/// (*f)(), float->double, short->int, etc.
2500///
2501/// In C, implicit casts always produce rvalues. However, in C++, an
2502/// implicit cast whose result is being bound to a reference will be
2503/// an lvalue or xvalue. For example:
2504///
2505/// @code
2506/// class Base { };
2507/// class Derived : public Base { };
2508/// Derived &&ref();
2509/// void f(Derived d) {
2510///   Base& b = d; // initializer is an ImplicitCastExpr
2511///                // to an lvalue of type Base
2512///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2513///                     // to an xvalue of type Base
2514/// }
2515/// @endcode
2516class ImplicitCastExpr : public CastExpr {
2517private:
2518  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2519                   unsigned BasePathLength, ExprValueKind VK)
2520    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2521  }
2522
2523  /// \brief Construct an empty implicit cast.
2524  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2525    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2526
2527public:
2528  enum OnStack_t { OnStack };
2529  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2530                   ExprValueKind VK)
2531    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2532  }
2533
2534  static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2535                                  CastKind Kind, Expr *Operand,
2536                                  const CXXCastPath *BasePath,
2537                                  ExprValueKind Cat);
2538
2539  static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2540
2541  SourceRange getSourceRange() const {
2542    return getSubExpr()->getSourceRange();
2543  }
2544
2545  static bool classof(const Stmt *T) {
2546    return T->getStmtClass() == ImplicitCastExprClass;
2547  }
2548  static bool classof(const ImplicitCastExpr *) { return true; }
2549};
2550
2551inline Expr *Expr::IgnoreImpCasts() {
2552  Expr *e = this;
2553  while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2554    e = ice->getSubExpr();
2555  return e;
2556}
2557
2558/// ExplicitCastExpr - An explicit cast written in the source
2559/// code.
2560///
2561/// This class is effectively an abstract class, because it provides
2562/// the basic representation of an explicitly-written cast without
2563/// specifying which kind of cast (C cast, functional cast, static
2564/// cast, etc.) was written; specific derived classes represent the
2565/// particular style of cast and its location information.
2566///
2567/// Unlike implicit casts, explicit cast nodes have two different
2568/// types: the type that was written into the source code, and the
2569/// actual type of the expression as determined by semantic
2570/// analysis. These types may differ slightly. For example, in C++ one
2571/// can cast to a reference type, which indicates that the resulting
2572/// expression will be an lvalue or xvalue. The reference type, however,
2573/// will not be used as the type of the expression.
2574class ExplicitCastExpr : public CastExpr {
2575  /// TInfo - Source type info for the (written) type
2576  /// this expression is casting to.
2577  TypeSourceInfo *TInfo;
2578
2579protected:
2580  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2581                   CastKind kind, Expr *op, unsigned PathSize,
2582                   TypeSourceInfo *writtenTy)
2583    : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2584
2585  /// \brief Construct an empty explicit cast.
2586  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2587    : CastExpr(SC, Shell, PathSize) { }
2588
2589public:
2590  /// getTypeInfoAsWritten - Returns the type source info for the type
2591  /// that this expression is casting to.
2592  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2593  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2594
2595  /// getTypeAsWritten - Returns the type that this expression is
2596  /// casting to, as written in the source code.
2597  QualType getTypeAsWritten() const { return TInfo->getType(); }
2598
2599  static bool classof(const Stmt *T) {
2600     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2601            T->getStmtClass() <= lastExplicitCastExprConstant;
2602  }
2603  static bool classof(const ExplicitCastExpr *) { return true; }
2604};
2605
2606/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2607/// cast in C++ (C++ [expr.cast]), which uses the syntax
2608/// (Type)expr. For example: @c (int)f.
2609class CStyleCastExpr : public ExplicitCastExpr {
2610  SourceLocation LPLoc; // the location of the left paren
2611  SourceLocation RPLoc; // the location of the right paren
2612
2613  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2614                 unsigned PathSize, TypeSourceInfo *writtenTy,
2615                 SourceLocation l, SourceLocation r)
2616    : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2617                       writtenTy), LPLoc(l), RPLoc(r) {}
2618
2619  /// \brief Construct an empty C-style explicit cast.
2620  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2621    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2622
2623public:
2624  static CStyleCastExpr *Create(ASTContext &Context, QualType T,
2625                                ExprValueKind VK, CastKind K,
2626                                Expr *Op, const CXXCastPath *BasePath,
2627                                TypeSourceInfo *WrittenTy, SourceLocation L,
2628                                SourceLocation R);
2629
2630  static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2631
2632  SourceLocation getLParenLoc() const { return LPLoc; }
2633  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2634
2635  SourceLocation getRParenLoc() const { return RPLoc; }
2636  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2637
2638  SourceRange getSourceRange() const {
2639    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2640  }
2641  static bool classof(const Stmt *T) {
2642    return T->getStmtClass() == CStyleCastExprClass;
2643  }
2644  static bool classof(const CStyleCastExpr *) { return true; }
2645};
2646
2647/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2648///
2649/// This expression node kind describes a builtin binary operation,
2650/// such as "x + y" for integer values "x" and "y". The operands will
2651/// already have been converted to appropriate types (e.g., by
2652/// performing promotions or conversions).
2653///
2654/// In C++, where operators may be overloaded, a different kind of
2655/// expression node (CXXOperatorCallExpr) is used to express the
2656/// invocation of an overloaded operator with operator syntax. Within
2657/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2658/// used to store an expression "x + y" depends on the subexpressions
2659/// for x and y. If neither x or y is type-dependent, and the "+"
2660/// operator resolves to a built-in operation, BinaryOperator will be
2661/// used to express the computation (x and y may still be
2662/// value-dependent). If either x or y is type-dependent, or if the
2663/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2664/// be used to express the computation.
2665class BinaryOperator : public Expr {
2666public:
2667  typedef BinaryOperatorKind Opcode;
2668
2669private:
2670  unsigned Opc : 6;
2671  SourceLocation OpLoc;
2672
2673  enum { LHS, RHS, END_EXPR };
2674  Stmt* SubExprs[END_EXPR];
2675public:
2676
2677  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2678                 ExprValueKind VK, ExprObjectKind OK,
2679                 SourceLocation opLoc)
2680    : Expr(BinaryOperatorClass, ResTy, VK, OK,
2681           lhs->isTypeDependent() || rhs->isTypeDependent(),
2682           lhs->isValueDependent() || rhs->isValueDependent(),
2683           (lhs->isInstantiationDependent() ||
2684            rhs->isInstantiationDependent()),
2685           (lhs->containsUnexpandedParameterPack() ||
2686            rhs->containsUnexpandedParameterPack())),
2687      Opc(opc), OpLoc(opLoc) {
2688    SubExprs[LHS] = lhs;
2689    SubExprs[RHS] = rhs;
2690    assert(!isCompoundAssignmentOp() &&
2691           "Use ArithAssignBinaryOperator for compound assignments");
2692  }
2693
2694  /// \brief Construct an empty binary operator.
2695  explicit BinaryOperator(EmptyShell Empty)
2696    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2697
2698  SourceLocation getOperatorLoc() const { return OpLoc; }
2699  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2700
2701  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2702  void setOpcode(Opcode O) { Opc = O; }
2703
2704  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2705  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2706  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2707  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2708
2709  SourceRange getSourceRange() const {
2710    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2711  }
2712
2713  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2714  /// corresponds to, e.g. "<<=".
2715  static const char *getOpcodeStr(Opcode Op);
2716
2717  const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2718
2719  /// \brief Retrieve the binary opcode that corresponds to the given
2720  /// overloaded operator.
2721  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2722
2723  /// \brief Retrieve the overloaded operator kind that corresponds to
2724  /// the given binary opcode.
2725  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2726
2727  /// predicates to categorize the respective opcodes.
2728  bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2729  bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2730  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2731  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2732  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2733  bool isShiftOp() const { return isShiftOp(getOpcode()); }
2734
2735  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2736  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2737
2738  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2739  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2740
2741  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2742  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2743
2744  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2745  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2746
2747  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2748  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2749
2750  static bool isAssignmentOp(Opcode Opc) {
2751    return Opc >= BO_Assign && Opc <= BO_OrAssign;
2752  }
2753  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
2754
2755  static bool isCompoundAssignmentOp(Opcode Opc) {
2756    return Opc > BO_Assign && Opc <= BO_OrAssign;
2757  }
2758  bool isCompoundAssignmentOp() const {
2759    return isCompoundAssignmentOp(getOpcode());
2760  }
2761
2762  static bool isShiftAssignOp(Opcode Opc) {
2763    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2764  }
2765  bool isShiftAssignOp() const {
2766    return isShiftAssignOp(getOpcode());
2767  }
2768
2769  static bool classof(const Stmt *S) {
2770    return S->getStmtClass() >= firstBinaryOperatorConstant &&
2771           S->getStmtClass() <= lastBinaryOperatorConstant;
2772  }
2773  static bool classof(const BinaryOperator *) { return true; }
2774
2775  // Iterators
2776  child_range children() {
2777    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2778  }
2779
2780protected:
2781  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2782                 ExprValueKind VK, ExprObjectKind OK,
2783                 SourceLocation opLoc, bool dead)
2784    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
2785           lhs->isTypeDependent() || rhs->isTypeDependent(),
2786           lhs->isValueDependent() || rhs->isValueDependent(),
2787           (lhs->isInstantiationDependent() ||
2788            rhs->isInstantiationDependent()),
2789           (lhs->containsUnexpandedParameterPack() ||
2790            rhs->containsUnexpandedParameterPack())),
2791      Opc(opc), OpLoc(opLoc) {
2792    SubExprs[LHS] = lhs;
2793    SubExprs[RHS] = rhs;
2794  }
2795
2796  BinaryOperator(StmtClass SC, EmptyShell Empty)
2797    : Expr(SC, Empty), Opc(BO_MulAssign) { }
2798};
2799
2800/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2801/// track of the type the operation is performed in.  Due to the semantics of
2802/// these operators, the operands are promoted, the arithmetic performed, an
2803/// implicit conversion back to the result type done, then the assignment takes
2804/// place.  This captures the intermediate type which the computation is done
2805/// in.
2806class CompoundAssignOperator : public BinaryOperator {
2807  QualType ComputationLHSType;
2808  QualType ComputationResultType;
2809public:
2810  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
2811                         ExprValueKind VK, ExprObjectKind OK,
2812                         QualType CompLHSType, QualType CompResultType,
2813                         SourceLocation OpLoc)
2814    : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true),
2815      ComputationLHSType(CompLHSType),
2816      ComputationResultType(CompResultType) {
2817    assert(isCompoundAssignmentOp() &&
2818           "Only should be used for compound assignments");
2819  }
2820
2821  /// \brief Build an empty compound assignment operator expression.
2822  explicit CompoundAssignOperator(EmptyShell Empty)
2823    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2824
2825  // The two computation types are the type the LHS is converted
2826  // to for the computation and the type of the result; the two are
2827  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2828  QualType getComputationLHSType() const { return ComputationLHSType; }
2829  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2830
2831  QualType getComputationResultType() const { return ComputationResultType; }
2832  void setComputationResultType(QualType T) { ComputationResultType = T; }
2833
2834  static bool classof(const CompoundAssignOperator *) { return true; }
2835  static bool classof(const Stmt *S) {
2836    return S->getStmtClass() == CompoundAssignOperatorClass;
2837  }
2838};
2839
2840/// AbstractConditionalOperator - An abstract base class for
2841/// ConditionalOperator and BinaryConditionalOperator.
2842class AbstractConditionalOperator : public Expr {
2843  SourceLocation QuestionLoc, ColonLoc;
2844  friend class ASTStmtReader;
2845
2846protected:
2847  AbstractConditionalOperator(StmtClass SC, QualType T,
2848                              ExprValueKind VK, ExprObjectKind OK,
2849                              bool TD, bool VD, bool ID,
2850                              bool ContainsUnexpandedParameterPack,
2851                              SourceLocation qloc,
2852                              SourceLocation cloc)
2853    : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
2854      QuestionLoc(qloc), ColonLoc(cloc) {}
2855
2856  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
2857    : Expr(SC, Empty) { }
2858
2859public:
2860  // getCond - Return the expression representing the condition for
2861  //   the ?: operator.
2862  Expr *getCond() const;
2863
2864  // getTrueExpr - Return the subexpression representing the value of
2865  //   the expression if the condition evaluates to true.
2866  Expr *getTrueExpr() const;
2867
2868  // getFalseExpr - Return the subexpression representing the value of
2869  //   the expression if the condition evaluates to false.  This is
2870  //   the same as getRHS.
2871  Expr *getFalseExpr() const;
2872
2873  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2874  SourceLocation getColonLoc() const { return ColonLoc; }
2875
2876  static bool classof(const Stmt *T) {
2877    return T->getStmtClass() == ConditionalOperatorClass ||
2878           T->getStmtClass() == BinaryConditionalOperatorClass;
2879  }
2880  static bool classof(const AbstractConditionalOperator *) { return true; }
2881};
2882
2883/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
2884/// middle" extension is a BinaryConditionalOperator.
2885class ConditionalOperator : public AbstractConditionalOperator {
2886  enum { COND, LHS, RHS, END_EXPR };
2887  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2888
2889  friend class ASTStmtReader;
2890public:
2891  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2892                      SourceLocation CLoc, Expr *rhs,
2893                      QualType t, ExprValueKind VK, ExprObjectKind OK)
2894    : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
2895           // FIXME: the type of the conditional operator doesn't
2896           // depend on the type of the conditional, but the standard
2897           // seems to imply that it could. File a bug!
2898           (lhs->isTypeDependent() || rhs->isTypeDependent()),
2899           (cond->isValueDependent() || lhs->isValueDependent() ||
2900            rhs->isValueDependent()),
2901           (cond->isInstantiationDependent() ||
2902            lhs->isInstantiationDependent() ||
2903            rhs->isInstantiationDependent()),
2904           (cond->containsUnexpandedParameterPack() ||
2905            lhs->containsUnexpandedParameterPack() ||
2906            rhs->containsUnexpandedParameterPack()),
2907                                  QLoc, CLoc) {
2908    SubExprs[COND] = cond;
2909    SubExprs[LHS] = lhs;
2910    SubExprs[RHS] = rhs;
2911  }
2912
2913  /// \brief Build an empty conditional operator.
2914  explicit ConditionalOperator(EmptyShell Empty)
2915    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
2916
2917  // getCond - Return the expression representing the condition for
2918  //   the ?: operator.
2919  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2920
2921  // getTrueExpr - Return the subexpression representing the value of
2922  //   the expression if the condition evaluates to true.
2923  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
2924
2925  // getFalseExpr - Return the subexpression representing the value of
2926  //   the expression if the condition evaluates to false.  This is
2927  //   the same as getRHS.
2928  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2929
2930  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2931  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2932
2933  SourceRange getSourceRange() const {
2934    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2935  }
2936  static bool classof(const Stmt *T) {
2937    return T->getStmtClass() == ConditionalOperatorClass;
2938  }
2939  static bool classof(const ConditionalOperator *) { return true; }
2940
2941  // Iterators
2942  child_range children() {
2943    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2944  }
2945};
2946
2947/// BinaryConditionalOperator - The GNU extension to the conditional
2948/// operator which allows the middle operand to be omitted.
2949///
2950/// This is a different expression kind on the assumption that almost
2951/// every client ends up needing to know that these are different.
2952class BinaryConditionalOperator : public AbstractConditionalOperator {
2953  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
2954
2955  /// - the common condition/left-hand-side expression, which will be
2956  ///   evaluated as the opaque value
2957  /// - the condition, expressed in terms of the opaque value
2958  /// - the left-hand-side, expressed in terms of the opaque value
2959  /// - the right-hand-side
2960  Stmt *SubExprs[NUM_SUBEXPRS];
2961  OpaqueValueExpr *OpaqueValue;
2962
2963  friend class ASTStmtReader;
2964public:
2965  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
2966                            Expr *cond, Expr *lhs, Expr *rhs,
2967                            SourceLocation qloc, SourceLocation cloc,
2968                            QualType t, ExprValueKind VK, ExprObjectKind OK)
2969    : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
2970           (common->isTypeDependent() || rhs->isTypeDependent()),
2971           (common->isValueDependent() || rhs->isValueDependent()),
2972           (common->isInstantiationDependent() ||
2973            rhs->isInstantiationDependent()),
2974           (common->containsUnexpandedParameterPack() ||
2975            rhs->containsUnexpandedParameterPack()),
2976                                  qloc, cloc),
2977      OpaqueValue(opaqueValue) {
2978    SubExprs[COMMON] = common;
2979    SubExprs[COND] = cond;
2980    SubExprs[LHS] = lhs;
2981    SubExprs[RHS] = rhs;
2982
2983    OpaqueValue->setSourceExpr(common);
2984  }
2985
2986  /// \brief Build an empty conditional operator.
2987  explicit BinaryConditionalOperator(EmptyShell Empty)
2988    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
2989
2990  /// \brief getCommon - Return the common expression, written to the
2991  ///   left of the condition.  The opaque value will be bound to the
2992  ///   result of this expression.
2993  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
2994
2995  /// \brief getOpaqueValue - Return the opaque value placeholder.
2996  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
2997
2998  /// \brief getCond - Return the condition expression; this is defined
2999  ///   in terms of the opaque value.
3000  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3001
3002  /// \brief getTrueExpr - Return the subexpression which will be
3003  ///   evaluated if the condition evaluates to true;  this is defined
3004  ///   in terms of the opaque value.
3005  Expr *getTrueExpr() const {
3006    return cast<Expr>(SubExprs[LHS]);
3007  }
3008
3009  /// \brief getFalseExpr - Return the subexpression which will be
3010  ///   evaluated if the condnition evaluates to false; this is
3011  ///   defined in terms of the opaque value.
3012  Expr *getFalseExpr() const {
3013    return cast<Expr>(SubExprs[RHS]);
3014  }
3015
3016  SourceRange getSourceRange() const {
3017    return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd());
3018  }
3019  static bool classof(const Stmt *T) {
3020    return T->getStmtClass() == BinaryConditionalOperatorClass;
3021  }
3022  static bool classof(const BinaryConditionalOperator *) { return true; }
3023
3024  // Iterators
3025  child_range children() {
3026    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3027  }
3028};
3029
3030inline Expr *AbstractConditionalOperator::getCond() const {
3031  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3032    return co->getCond();
3033  return cast<BinaryConditionalOperator>(this)->getCond();
3034}
3035
3036inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3037  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3038    return co->getTrueExpr();
3039  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3040}
3041
3042inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3043  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3044    return co->getFalseExpr();
3045  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3046}
3047
3048/// AddrLabelExpr - The GNU address of label extension, representing &&label.
3049class AddrLabelExpr : public Expr {
3050  SourceLocation AmpAmpLoc, LabelLoc;
3051  LabelDecl *Label;
3052public:
3053  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3054                QualType t)
3055    : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3056           false),
3057      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3058
3059  /// \brief Build an empty address of a label expression.
3060  explicit AddrLabelExpr(EmptyShell Empty)
3061    : Expr(AddrLabelExprClass, Empty) { }
3062
3063  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3064  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3065  SourceLocation getLabelLoc() const { return LabelLoc; }
3066  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3067
3068  SourceRange getSourceRange() const {
3069    return SourceRange(AmpAmpLoc, LabelLoc);
3070  }
3071
3072  LabelDecl *getLabel() const { return Label; }
3073  void setLabel(LabelDecl *L) { Label = L; }
3074
3075  static bool classof(const Stmt *T) {
3076    return T->getStmtClass() == AddrLabelExprClass;
3077  }
3078  static bool classof(const AddrLabelExpr *) { return true; }
3079
3080  // Iterators
3081  child_range children() { return child_range(); }
3082};
3083
3084/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3085/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3086/// takes the value of the last subexpression.
3087///
3088/// A StmtExpr is always an r-value; values "returned" out of a
3089/// StmtExpr will be copied.
3090class StmtExpr : public Expr {
3091  Stmt *SubStmt;
3092  SourceLocation LParenLoc, RParenLoc;
3093public:
3094  // FIXME: Does type-dependence need to be computed differently?
3095  // FIXME: Do we need to compute instantiation instantiation-dependence for
3096  // statements? (ugh!)
3097  StmtExpr(CompoundStmt *substmt, QualType T,
3098           SourceLocation lp, SourceLocation rp) :
3099    Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3100         T->isDependentType(), false, false, false),
3101    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3102
3103  /// \brief Build an empty statement expression.
3104  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3105
3106  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3107  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3108  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3109
3110  SourceRange getSourceRange() const {
3111    return SourceRange(LParenLoc, RParenLoc);
3112  }
3113
3114  SourceLocation getLParenLoc() const { return LParenLoc; }
3115  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3116  SourceLocation getRParenLoc() const { return RParenLoc; }
3117  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3118
3119  static bool classof(const Stmt *T) {
3120    return T->getStmtClass() == StmtExprClass;
3121  }
3122  static bool classof(const StmtExpr *) { return true; }
3123
3124  // Iterators
3125  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3126};
3127
3128
3129/// ShuffleVectorExpr - clang-specific builtin-in function
3130/// __builtin_shufflevector.
3131/// This AST node represents a operator that does a constant
3132/// shuffle, similar to LLVM's shufflevector instruction. It takes
3133/// two vectors and a variable number of constant indices,
3134/// and returns the appropriately shuffled vector.
3135class ShuffleVectorExpr : public Expr {
3136  SourceLocation BuiltinLoc, RParenLoc;
3137
3138  // SubExprs - the list of values passed to the __builtin_shufflevector
3139  // function. The first two are vectors, and the rest are constant
3140  // indices.  The number of values in this list is always
3141  // 2+the number of indices in the vector type.
3142  Stmt **SubExprs;
3143  unsigned NumExprs;
3144
3145public:
3146  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3147                    QualType Type, SourceLocation BLoc,
3148                    SourceLocation RP);
3149
3150  /// \brief Build an empty vector-shuffle expression.
3151  explicit ShuffleVectorExpr(EmptyShell Empty)
3152    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
3153
3154  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3155  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3156
3157  SourceLocation getRParenLoc() const { return RParenLoc; }
3158  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3159
3160  SourceRange getSourceRange() const {
3161    return SourceRange(BuiltinLoc, RParenLoc);
3162  }
3163  static bool classof(const Stmt *T) {
3164    return T->getStmtClass() == ShuffleVectorExprClass;
3165  }
3166  static bool classof(const ShuffleVectorExpr *) { return true; }
3167
3168  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
3169  /// constant expression, the actual arguments passed in, and the function
3170  /// pointers.
3171  unsigned getNumSubExprs() const { return NumExprs; }
3172
3173  /// \brief Retrieve the array of expressions.
3174  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3175
3176  /// getExpr - Return the Expr at the specified index.
3177  Expr *getExpr(unsigned Index) {
3178    assert((Index < NumExprs) && "Arg access out of range!");
3179    return cast<Expr>(SubExprs[Index]);
3180  }
3181  const Expr *getExpr(unsigned Index) const {
3182    assert((Index < NumExprs) && "Arg access out of range!");
3183    return cast<Expr>(SubExprs[Index]);
3184  }
3185
3186  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
3187
3188  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
3189    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3190    return getExpr(N+2)->EvaluateKnownConstInt(Ctx).getZExtValue();
3191  }
3192
3193  // Iterators
3194  child_range children() {
3195    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3196  }
3197};
3198
3199/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3200/// This AST node is similar to the conditional operator (?:) in C, with
3201/// the following exceptions:
3202/// - the test expression must be a integer constant expression.
3203/// - the expression returned acts like the chosen subexpression in every
3204///   visible way: the type is the same as that of the chosen subexpression,
3205///   and all predicates (whether it's an l-value, whether it's an integer
3206///   constant expression, etc.) return the same result as for the chosen
3207///   sub-expression.
3208class ChooseExpr : public Expr {
3209  enum { COND, LHS, RHS, END_EXPR };
3210  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3211  SourceLocation BuiltinLoc, RParenLoc;
3212public:
3213  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3214             QualType t, ExprValueKind VK, ExprObjectKind OK,
3215             SourceLocation RP, bool TypeDependent, bool ValueDependent)
3216    : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3217           (cond->isInstantiationDependent() ||
3218            lhs->isInstantiationDependent() ||
3219            rhs->isInstantiationDependent()),
3220           (cond->containsUnexpandedParameterPack() ||
3221            lhs->containsUnexpandedParameterPack() ||
3222            rhs->containsUnexpandedParameterPack())),
3223      BuiltinLoc(BLoc), RParenLoc(RP) {
3224      SubExprs[COND] = cond;
3225      SubExprs[LHS] = lhs;
3226      SubExprs[RHS] = rhs;
3227    }
3228
3229  /// \brief Build an empty __builtin_choose_expr.
3230  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3231
3232  /// isConditionTrue - Return whether the condition is true (i.e. not
3233  /// equal to zero).
3234  bool isConditionTrue(const ASTContext &C) const;
3235
3236  /// getChosenSubExpr - Return the subexpression chosen according to the
3237  /// condition.
3238  Expr *getChosenSubExpr(const ASTContext &C) const {
3239    return isConditionTrue(C) ? getLHS() : getRHS();
3240  }
3241
3242  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3243  void setCond(Expr *E) { SubExprs[COND] = E; }
3244  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3245  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3246  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3247  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3248
3249  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3250  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3251
3252  SourceLocation getRParenLoc() const { return RParenLoc; }
3253  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3254
3255  SourceRange getSourceRange() const {
3256    return SourceRange(BuiltinLoc, RParenLoc);
3257  }
3258  static bool classof(const Stmt *T) {
3259    return T->getStmtClass() == ChooseExprClass;
3260  }
3261  static bool classof(const ChooseExpr *) { return true; }
3262
3263  // Iterators
3264  child_range children() {
3265    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3266  }
3267};
3268
3269/// GNUNullExpr - Implements the GNU __null extension, which is a name
3270/// for a null pointer constant that has integral type (e.g., int or
3271/// long) and is the same size and alignment as a pointer. The __null
3272/// extension is typically only used by system headers, which define
3273/// NULL as __null in C++ rather than using 0 (which is an integer
3274/// that may not match the size of a pointer).
3275class GNUNullExpr : public Expr {
3276  /// TokenLoc - The location of the __null keyword.
3277  SourceLocation TokenLoc;
3278
3279public:
3280  GNUNullExpr(QualType Ty, SourceLocation Loc)
3281    : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3282           false),
3283      TokenLoc(Loc) { }
3284
3285  /// \brief Build an empty GNU __null expression.
3286  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3287
3288  /// getTokenLocation - The location of the __null token.
3289  SourceLocation getTokenLocation() const { return TokenLoc; }
3290  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3291
3292  SourceRange getSourceRange() const {
3293    return SourceRange(TokenLoc);
3294  }
3295  static bool classof(const Stmt *T) {
3296    return T->getStmtClass() == GNUNullExprClass;
3297  }
3298  static bool classof(const GNUNullExpr *) { return true; }
3299
3300  // Iterators
3301  child_range children() { return child_range(); }
3302};
3303
3304/// VAArgExpr, used for the builtin function __builtin_va_arg.
3305class VAArgExpr : public Expr {
3306  Stmt *Val;
3307  TypeSourceInfo *TInfo;
3308  SourceLocation BuiltinLoc, RParenLoc;
3309public:
3310  VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3311            SourceLocation RPLoc, QualType t)
3312    : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3313           t->isDependentType(), false,
3314           (TInfo->getType()->isInstantiationDependentType() ||
3315            e->isInstantiationDependent()),
3316           (TInfo->getType()->containsUnexpandedParameterPack() ||
3317            e->containsUnexpandedParameterPack())),
3318      Val(e), TInfo(TInfo),
3319      BuiltinLoc(BLoc),
3320      RParenLoc(RPLoc) { }
3321
3322  /// \brief Create an empty __builtin_va_arg expression.
3323  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3324
3325  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3326  Expr *getSubExpr() { return cast<Expr>(Val); }
3327  void setSubExpr(Expr *E) { Val = E; }
3328
3329  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3330  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3331
3332  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3333  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3334
3335  SourceLocation getRParenLoc() const { return RParenLoc; }
3336  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3337
3338  SourceRange getSourceRange() const {
3339    return SourceRange(BuiltinLoc, RParenLoc);
3340  }
3341  static bool classof(const Stmt *T) {
3342    return T->getStmtClass() == VAArgExprClass;
3343  }
3344  static bool classof(const VAArgExpr *) { return true; }
3345
3346  // Iterators
3347  child_range children() { return child_range(&Val, &Val+1); }
3348};
3349
3350/// @brief Describes an C or C++ initializer list.
3351///
3352/// InitListExpr describes an initializer list, which can be used to
3353/// initialize objects of different types, including
3354/// struct/class/union types, arrays, and vectors. For example:
3355///
3356/// @code
3357/// struct foo x = { 1, { 2, 3 } };
3358/// @endcode
3359///
3360/// Prior to semantic analysis, an initializer list will represent the
3361/// initializer list as written by the user, but will have the
3362/// placeholder type "void". This initializer list is called the
3363/// syntactic form of the initializer, and may contain C99 designated
3364/// initializers (represented as DesignatedInitExprs), initializations
3365/// of subobject members without explicit braces, and so on. Clients
3366/// interested in the original syntax of the initializer list should
3367/// use the syntactic form of the initializer list.
3368///
3369/// After semantic analysis, the initializer list will represent the
3370/// semantic form of the initializer, where the initializations of all
3371/// subobjects are made explicit with nested InitListExpr nodes and
3372/// C99 designators have been eliminated by placing the designated
3373/// initializations into the subobject they initialize. Additionally,
3374/// any "holes" in the initialization, where no initializer has been
3375/// specified for a particular subobject, will be replaced with
3376/// implicitly-generated ImplicitValueInitExpr expressions that
3377/// value-initialize the subobjects. Note, however, that the
3378/// initializer lists may still have fewer initializers than there are
3379/// elements to initialize within the object.
3380///
3381/// Given the semantic form of the initializer list, one can retrieve
3382/// the original syntactic form of that initializer list (if it
3383/// exists) using getSyntacticForm(). Since many initializer lists
3384/// have the same syntactic and semantic forms, getSyntacticForm() may
3385/// return NULL, indicating that the current initializer list also
3386/// serves as its syntactic form.
3387class InitListExpr : public Expr {
3388  // FIXME: Eliminate this vector in favor of ASTContext allocation
3389  typedef ASTVector<Stmt *> InitExprsTy;
3390  InitExprsTy InitExprs;
3391  SourceLocation LBraceLoc, RBraceLoc;
3392
3393  /// Contains the initializer list that describes the syntactic form
3394  /// written in the source code.
3395  InitListExpr *SyntacticForm;
3396
3397  /// \brief Either:
3398  ///  If this initializer list initializes an array with more elements than
3399  ///  there are initializers in the list, specifies an expression to be used
3400  ///  for value initialization of the rest of the elements.
3401  /// Or
3402  ///  If this initializer list initializes a union, specifies which
3403  ///  field within the union will be initialized.
3404  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3405
3406  /// Whether this initializer list originally had a GNU array-range
3407  /// designator in it. This is a temporary marker used by CodeGen.
3408  bool HadArrayRangeDesignator;
3409
3410public:
3411  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
3412               Expr **initexprs, unsigned numinits,
3413               SourceLocation rbraceloc);
3414
3415  /// \brief Build an empty initializer list.
3416  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
3417    : Expr(InitListExprClass, Empty), InitExprs(C) { }
3418
3419  unsigned getNumInits() const { return InitExprs.size(); }
3420
3421  /// \brief Retrieve the set of initializers.
3422  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3423
3424  const Expr *getInit(unsigned Init) const {
3425    assert(Init < getNumInits() && "Initializer access out of range!");
3426    return cast_or_null<Expr>(InitExprs[Init]);
3427  }
3428
3429  Expr *getInit(unsigned Init) {
3430    assert(Init < getNumInits() && "Initializer access out of range!");
3431    return cast_or_null<Expr>(InitExprs[Init]);
3432  }
3433
3434  void setInit(unsigned Init, Expr *expr) {
3435    assert(Init < getNumInits() && "Initializer access out of range!");
3436    InitExprs[Init] = expr;
3437  }
3438
3439  /// \brief Reserve space for some number of initializers.
3440  void reserveInits(ASTContext &C, unsigned NumInits);
3441
3442  /// @brief Specify the number of initializers
3443  ///
3444  /// If there are more than @p NumInits initializers, the remaining
3445  /// initializers will be destroyed. If there are fewer than @p
3446  /// NumInits initializers, NULL expressions will be added for the
3447  /// unknown initializers.
3448  void resizeInits(ASTContext &Context, unsigned NumInits);
3449
3450  /// @brief Updates the initializer at index @p Init with the new
3451  /// expression @p expr, and returns the old expression at that
3452  /// location.
3453  ///
3454  /// When @p Init is out of range for this initializer list, the
3455  /// initializer list will be extended with NULL expressions to
3456  /// accommodate the new entry.
3457  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
3458
3459  /// \brief If this initializer list initializes an array with more elements
3460  /// than there are initializers in the list, specifies an expression to be
3461  /// used for value initialization of the rest of the elements.
3462  Expr *getArrayFiller() {
3463    return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3464  }
3465  const Expr *getArrayFiller() const {
3466    return const_cast<InitListExpr *>(this)->getArrayFiller();
3467  }
3468  void setArrayFiller(Expr *filler);
3469
3470  /// \brief Return true if this is an array initializer and its array "filler"
3471  /// has been set.
3472  bool hasArrayFiller() const { return getArrayFiller(); }
3473
3474  /// \brief If this initializes a union, specifies which field in the
3475  /// union to initialize.
3476  ///
3477  /// Typically, this field is the first named field within the
3478  /// union. However, a designated initializer can specify the
3479  /// initialization of a different field within the union.
3480  FieldDecl *getInitializedFieldInUnion() {
3481    return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3482  }
3483  const FieldDecl *getInitializedFieldInUnion() const {
3484    return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3485  }
3486  void setInitializedFieldInUnion(FieldDecl *FD) {
3487    ArrayFillerOrUnionFieldInit = FD;
3488  }
3489
3490  // Explicit InitListExpr's originate from source code (and have valid source
3491  // locations). Implicit InitListExpr's are created by the semantic analyzer.
3492  bool isExplicit() {
3493    return LBraceLoc.isValid() && RBraceLoc.isValid();
3494  }
3495
3496  SourceLocation getLBraceLoc() const { return LBraceLoc; }
3497  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3498  SourceLocation getRBraceLoc() const { return RBraceLoc; }
3499  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3500
3501  /// @brief Retrieve the initializer list that describes the
3502  /// syntactic form of the initializer.
3503  ///
3504  ///
3505  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
3506  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
3507
3508  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
3509  void sawArrayRangeDesignator(bool ARD = true) {
3510    HadArrayRangeDesignator = ARD;
3511  }
3512
3513  SourceRange getSourceRange() const;
3514
3515  static bool classof(const Stmt *T) {
3516    return T->getStmtClass() == InitListExprClass;
3517  }
3518  static bool classof(const InitListExpr *) { return true; }
3519
3520  // Iterators
3521  child_range children() {
3522    if (InitExprs.empty()) return child_range();
3523    return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3524  }
3525
3526  typedef InitExprsTy::iterator iterator;
3527  typedef InitExprsTy::const_iterator const_iterator;
3528  typedef InitExprsTy::reverse_iterator reverse_iterator;
3529  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3530
3531  iterator begin() { return InitExprs.begin(); }
3532  const_iterator begin() const { return InitExprs.begin(); }
3533  iterator end() { return InitExprs.end(); }
3534  const_iterator end() const { return InitExprs.end(); }
3535  reverse_iterator rbegin() { return InitExprs.rbegin(); }
3536  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3537  reverse_iterator rend() { return InitExprs.rend(); }
3538  const_reverse_iterator rend() const { return InitExprs.rend(); }
3539
3540  friend class ASTStmtReader;
3541  friend class ASTStmtWriter;
3542};
3543
3544/// @brief Represents a C99 designated initializer expression.
3545///
3546/// A designated initializer expression (C99 6.7.8) contains one or
3547/// more designators (which can be field designators, array
3548/// designators, or GNU array-range designators) followed by an
3549/// expression that initializes the field or element(s) that the
3550/// designators refer to. For example, given:
3551///
3552/// @code
3553/// struct point {
3554///   double x;
3555///   double y;
3556/// };
3557/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3558/// @endcode
3559///
3560/// The InitListExpr contains three DesignatedInitExprs, the first of
3561/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3562/// designators, one array designator for @c [2] followed by one field
3563/// designator for @c .y. The initalization expression will be 1.0.
3564class DesignatedInitExpr : public Expr {
3565public:
3566  /// \brief Forward declaration of the Designator class.
3567  class Designator;
3568
3569private:
3570  /// The location of the '=' or ':' prior to the actual initializer
3571  /// expression.
3572  SourceLocation EqualOrColonLoc;
3573
3574  /// Whether this designated initializer used the GNU deprecated
3575  /// syntax rather than the C99 '=' syntax.
3576  bool GNUSyntax : 1;
3577
3578  /// The number of designators in this initializer expression.
3579  unsigned NumDesignators : 15;
3580
3581  /// \brief The designators in this designated initialization
3582  /// expression.
3583  Designator *Designators;
3584
3585  /// The number of subexpressions of this initializer expression,
3586  /// which contains both the initializer and any additional
3587  /// expressions used by array and array-range designators.
3588  unsigned NumSubExprs : 16;
3589
3590
3591  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3592                     const Designator *Designators,
3593                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
3594                     Expr **IndexExprs, unsigned NumIndexExprs,
3595                     Expr *Init);
3596
3597  explicit DesignatedInitExpr(unsigned NumSubExprs)
3598    : Expr(DesignatedInitExprClass, EmptyShell()),
3599      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
3600
3601public:
3602  /// A field designator, e.g., ".x".
3603  struct FieldDesignator {
3604    /// Refers to the field that is being initialized. The low bit
3605    /// of this field determines whether this is actually a pointer
3606    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3607    /// initially constructed, a field designator will store an
3608    /// IdentifierInfo*. After semantic analysis has resolved that
3609    /// name, the field designator will instead store a FieldDecl*.
3610    uintptr_t NameOrField;
3611
3612    /// The location of the '.' in the designated initializer.
3613    unsigned DotLoc;
3614
3615    /// The location of the field name in the designated initializer.
3616    unsigned FieldLoc;
3617  };
3618
3619  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3620  struct ArrayOrRangeDesignator {
3621    /// Location of the first index expression within the designated
3622    /// initializer expression's list of subexpressions.
3623    unsigned Index;
3624    /// The location of the '[' starting the array range designator.
3625    unsigned LBracketLoc;
3626    /// The location of the ellipsis separating the start and end
3627    /// indices. Only valid for GNU array-range designators.
3628    unsigned EllipsisLoc;
3629    /// The location of the ']' terminating the array range designator.
3630    unsigned RBracketLoc;
3631  };
3632
3633  /// @brief Represents a single C99 designator.
3634  ///
3635  /// @todo This class is infuriatingly similar to clang::Designator,
3636  /// but minor differences (storing indices vs. storing pointers)
3637  /// keep us from reusing it. Try harder, later, to rectify these
3638  /// differences.
3639  class Designator {
3640    /// @brief The kind of designator this describes.
3641    enum {
3642      FieldDesignator,
3643      ArrayDesignator,
3644      ArrayRangeDesignator
3645    } Kind;
3646
3647    union {
3648      /// A field designator, e.g., ".x".
3649      struct FieldDesignator Field;
3650      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3651      struct ArrayOrRangeDesignator ArrayOrRange;
3652    };
3653    friend class DesignatedInitExpr;
3654
3655  public:
3656    Designator() {}
3657
3658    /// @brief Initializes a field designator.
3659    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3660               SourceLocation FieldLoc)
3661      : Kind(FieldDesignator) {
3662      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3663      Field.DotLoc = DotLoc.getRawEncoding();
3664      Field.FieldLoc = FieldLoc.getRawEncoding();
3665    }
3666
3667    /// @brief Initializes an array designator.
3668    Designator(unsigned Index, SourceLocation LBracketLoc,
3669               SourceLocation RBracketLoc)
3670      : Kind(ArrayDesignator) {
3671      ArrayOrRange.Index = Index;
3672      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3673      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3674      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3675    }
3676
3677    /// @brief Initializes a GNU array-range designator.
3678    Designator(unsigned Index, SourceLocation LBracketLoc,
3679               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3680      : Kind(ArrayRangeDesignator) {
3681      ArrayOrRange.Index = Index;
3682      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3683      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3684      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3685    }
3686
3687    bool isFieldDesignator() const { return Kind == FieldDesignator; }
3688    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3689    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3690
3691    IdentifierInfo *getFieldName() const;
3692
3693    FieldDecl *getField() const {
3694      assert(Kind == FieldDesignator && "Only valid on a field designator");
3695      if (Field.NameOrField & 0x01)
3696        return 0;
3697      else
3698        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3699    }
3700
3701    void setField(FieldDecl *FD) {
3702      assert(Kind == FieldDesignator && "Only valid on a field designator");
3703      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3704    }
3705
3706    SourceLocation getDotLoc() const {
3707      assert(Kind == FieldDesignator && "Only valid on a field designator");
3708      return SourceLocation::getFromRawEncoding(Field.DotLoc);
3709    }
3710
3711    SourceLocation getFieldLoc() const {
3712      assert(Kind == FieldDesignator && "Only valid on a field designator");
3713      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3714    }
3715
3716    SourceLocation getLBracketLoc() const {
3717      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3718             "Only valid on an array or array-range designator");
3719      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3720    }
3721
3722    SourceLocation getRBracketLoc() const {
3723      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3724             "Only valid on an array or array-range designator");
3725      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3726    }
3727
3728    SourceLocation getEllipsisLoc() const {
3729      assert(Kind == ArrayRangeDesignator &&
3730             "Only valid on an array-range designator");
3731      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3732    }
3733
3734    unsigned getFirstExprIndex() const {
3735      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3736             "Only valid on an array or array-range designator");
3737      return ArrayOrRange.Index;
3738    }
3739
3740    SourceLocation getStartLocation() const {
3741      if (Kind == FieldDesignator)
3742        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3743      else
3744        return getLBracketLoc();
3745    }
3746    SourceLocation getEndLocation() const {
3747      return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
3748    }
3749    SourceRange getSourceRange() const {
3750      return SourceRange(getStartLocation(), getEndLocation());
3751    }
3752  };
3753
3754  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3755                                    unsigned NumDesignators,
3756                                    Expr **IndexExprs, unsigned NumIndexExprs,
3757                                    SourceLocation EqualOrColonLoc,
3758                                    bool GNUSyntax, Expr *Init);
3759
3760  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3761
3762  /// @brief Returns the number of designators in this initializer.
3763  unsigned size() const { return NumDesignators; }
3764
3765  // Iterator access to the designators.
3766  typedef Designator *designators_iterator;
3767  designators_iterator designators_begin() { return Designators; }
3768  designators_iterator designators_end() {
3769    return Designators + NumDesignators;
3770  }
3771
3772  typedef const Designator *const_designators_iterator;
3773  const_designators_iterator designators_begin() const { return Designators; }
3774  const_designators_iterator designators_end() const {
3775    return Designators + NumDesignators;
3776  }
3777
3778  typedef std::reverse_iterator<designators_iterator>
3779          reverse_designators_iterator;
3780  reverse_designators_iterator designators_rbegin() {
3781    return reverse_designators_iterator(designators_end());
3782  }
3783  reverse_designators_iterator designators_rend() {
3784    return reverse_designators_iterator(designators_begin());
3785  }
3786
3787  typedef std::reverse_iterator<const_designators_iterator>
3788          const_reverse_designators_iterator;
3789  const_reverse_designators_iterator designators_rbegin() const {
3790    return const_reverse_designators_iterator(designators_end());
3791  }
3792  const_reverse_designators_iterator designators_rend() const {
3793    return const_reverse_designators_iterator(designators_begin());
3794  }
3795
3796  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3797
3798  void setDesignators(ASTContext &C, const Designator *Desigs,
3799                      unsigned NumDesigs);
3800
3801  Expr *getArrayIndex(const Designator& D);
3802  Expr *getArrayRangeStart(const Designator& D);
3803  Expr *getArrayRangeEnd(const Designator& D);
3804
3805  /// @brief Retrieve the location of the '=' that precedes the
3806  /// initializer value itself, if present.
3807  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3808  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3809
3810  /// @brief Determines whether this designated initializer used the
3811  /// deprecated GNU syntax for designated initializers.
3812  bool usesGNUSyntax() const { return GNUSyntax; }
3813  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3814
3815  /// @brief Retrieve the initializer value.
3816  Expr *getInit() const {
3817    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3818  }
3819
3820  void setInit(Expr *init) {
3821    *child_begin() = init;
3822  }
3823
3824  /// \brief Retrieve the total number of subexpressions in this
3825  /// designated initializer expression, including the actual
3826  /// initialized value and any expressions that occur within array
3827  /// and array-range designators.
3828  unsigned getNumSubExprs() const { return NumSubExprs; }
3829
3830  Expr *getSubExpr(unsigned Idx) {
3831    assert(Idx < NumSubExprs && "Subscript out of range");
3832    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3833    Ptr += sizeof(DesignatedInitExpr);
3834    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3835  }
3836
3837  void setSubExpr(unsigned Idx, Expr *E) {
3838    assert(Idx < NumSubExprs && "Subscript out of range");
3839    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3840    Ptr += sizeof(DesignatedInitExpr);
3841    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3842  }
3843
3844  /// \brief Replaces the designator at index @p Idx with the series
3845  /// of designators in [First, Last).
3846  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3847                        const Designator *Last);
3848
3849  SourceRange getDesignatorsSourceRange() const;
3850
3851  SourceRange getSourceRange() const;
3852
3853  static bool classof(const Stmt *T) {
3854    return T->getStmtClass() == DesignatedInitExprClass;
3855  }
3856  static bool classof(const DesignatedInitExpr *) { return true; }
3857
3858  // Iterators
3859  child_range children() {
3860    Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
3861    return child_range(begin, begin + NumSubExprs);
3862  }
3863};
3864
3865/// \brief Represents an implicitly-generated value initialization of
3866/// an object of a given type.
3867///
3868/// Implicit value initializations occur within semantic initializer
3869/// list expressions (InitListExpr) as placeholders for subobject
3870/// initializations not explicitly specified by the user.
3871///
3872/// \see InitListExpr
3873class ImplicitValueInitExpr : public Expr {
3874public:
3875  explicit ImplicitValueInitExpr(QualType ty)
3876    : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
3877           false, false, ty->isInstantiationDependentType(), false) { }
3878
3879  /// \brief Construct an empty implicit value initialization.
3880  explicit ImplicitValueInitExpr(EmptyShell Empty)
3881    : Expr(ImplicitValueInitExprClass, Empty) { }
3882
3883  static bool classof(const Stmt *T) {
3884    return T->getStmtClass() == ImplicitValueInitExprClass;
3885  }
3886  static bool classof(const ImplicitValueInitExpr *) { return true; }
3887
3888  SourceRange getSourceRange() const {
3889    return SourceRange();
3890  }
3891
3892  // Iterators
3893  child_range children() { return child_range(); }
3894};
3895
3896
3897class ParenListExpr : public Expr {
3898  Stmt **Exprs;
3899  unsigned NumExprs;
3900  SourceLocation LParenLoc, RParenLoc;
3901
3902public:
3903  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3904                unsigned numexprs, SourceLocation rparenloc, QualType T);
3905
3906  /// \brief Build an empty paren list.
3907  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3908
3909  unsigned getNumExprs() const { return NumExprs; }
3910
3911  const Expr* getExpr(unsigned Init) const {
3912    assert(Init < getNumExprs() && "Initializer access out of range!");
3913    return cast_or_null<Expr>(Exprs[Init]);
3914  }
3915
3916  Expr* getExpr(unsigned Init) {
3917    assert(Init < getNumExprs() && "Initializer access out of range!");
3918    return cast_or_null<Expr>(Exprs[Init]);
3919  }
3920
3921  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3922
3923  SourceLocation getLParenLoc() const { return LParenLoc; }
3924  SourceLocation getRParenLoc() const { return RParenLoc; }
3925
3926  SourceRange getSourceRange() const {
3927    return SourceRange(LParenLoc, RParenLoc);
3928  }
3929  static bool classof(const Stmt *T) {
3930    return T->getStmtClass() == ParenListExprClass;
3931  }
3932  static bool classof(const ParenListExpr *) { return true; }
3933
3934  // Iterators
3935  child_range children() {
3936    return child_range(&Exprs[0], &Exprs[0]+NumExprs);
3937  }
3938
3939  friend class ASTStmtReader;
3940  friend class ASTStmtWriter;
3941};
3942
3943
3944/// \brief Represents a C1X generic selection.
3945///
3946/// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling
3947/// expression, followed by one or more generic associations.  Each generic
3948/// association specifies a type name and an expression, or "default" and an
3949/// expression (in which case it is known as a default generic association).
3950/// The type and value of the generic selection are identical to those of its
3951/// result expression, which is defined as the expression in the generic
3952/// association with a type name that is compatible with the type of the
3953/// controlling expression, or the expression in the default generic association
3954/// if no types are compatible.  For example:
3955///
3956/// @code
3957/// _Generic(X, double: 1, float: 2, default: 3)
3958/// @endcode
3959///
3960/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
3961/// or 3 if "hello".
3962///
3963/// As an extension, generic selections are allowed in C++, where the following
3964/// additional semantics apply:
3965///
3966/// Any generic selection whose controlling expression is type-dependent or
3967/// which names a dependent type in its association list is result-dependent,
3968/// which means that the choice of result expression is dependent.
3969/// Result-dependent generic associations are both type- and value-dependent.
3970class GenericSelectionExpr : public Expr {
3971  enum { CONTROLLING, END_EXPR };
3972  TypeSourceInfo **AssocTypes;
3973  Stmt **SubExprs;
3974  unsigned NumAssocs, ResultIndex;
3975  SourceLocation GenericLoc, DefaultLoc, RParenLoc;
3976
3977public:
3978  GenericSelectionExpr(ASTContext &Context,
3979                       SourceLocation GenericLoc, Expr *ControllingExpr,
3980                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3981                       unsigned NumAssocs, SourceLocation DefaultLoc,
3982                       SourceLocation RParenLoc,
3983                       bool ContainsUnexpandedParameterPack,
3984                       unsigned ResultIndex);
3985
3986  /// This constructor is used in the result-dependent case.
3987  GenericSelectionExpr(ASTContext &Context,
3988                       SourceLocation GenericLoc, Expr *ControllingExpr,
3989                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3990                       unsigned NumAssocs, SourceLocation DefaultLoc,
3991                       SourceLocation RParenLoc,
3992                       bool ContainsUnexpandedParameterPack);
3993
3994  explicit GenericSelectionExpr(EmptyShell Empty)
3995    : Expr(GenericSelectionExprClass, Empty) { }
3996
3997  unsigned getNumAssocs() const { return NumAssocs; }
3998
3999  SourceLocation getGenericLoc() const { return GenericLoc; }
4000  SourceLocation getDefaultLoc() const { return DefaultLoc; }
4001  SourceLocation getRParenLoc() const { return RParenLoc; }
4002
4003  const Expr *getAssocExpr(unsigned i) const {
4004    return cast<Expr>(SubExprs[END_EXPR+i]);
4005  }
4006  Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4007
4008  const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4009    return AssocTypes[i];
4010  }
4011  TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4012
4013  QualType getAssocType(unsigned i) const {
4014    if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4015      return TS->getType();
4016    else
4017      return QualType();
4018  }
4019
4020  const Expr *getControllingExpr() const {
4021    return cast<Expr>(SubExprs[CONTROLLING]);
4022  }
4023  Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4024
4025  /// Whether this generic selection is result-dependent.
4026  bool isResultDependent() const { return ResultIndex == -1U; }
4027
4028  /// The zero-based index of the result expression's generic association in
4029  /// the generic selection's association list.  Defined only if the
4030  /// generic selection is not result-dependent.
4031  unsigned getResultIndex() const {
4032    assert(!isResultDependent() && "Generic selection is result-dependent");
4033    return ResultIndex;
4034  }
4035
4036  /// The generic selection's result expression.  Defined only if the
4037  /// generic selection is not result-dependent.
4038  const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4039  Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4040
4041  SourceRange getSourceRange() const {
4042    return SourceRange(GenericLoc, RParenLoc);
4043  }
4044  static bool classof(const Stmt *T) {
4045    return T->getStmtClass() == GenericSelectionExprClass;
4046  }
4047  static bool classof(const GenericSelectionExpr *) { return true; }
4048
4049  child_range children() {
4050    return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4051  }
4052
4053  friend class ASTStmtReader;
4054};
4055
4056//===----------------------------------------------------------------------===//
4057// Clang Extensions
4058//===----------------------------------------------------------------------===//
4059
4060
4061/// ExtVectorElementExpr - This represents access to specific elements of a
4062/// vector, and may occur on the left hand side or right hand side.  For example
4063/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
4064///
4065/// Note that the base may have either vector or pointer to vector type, just
4066/// like a struct field reference.
4067///
4068class ExtVectorElementExpr : public Expr {
4069  Stmt *Base;
4070  IdentifierInfo *Accessor;
4071  SourceLocation AccessorLoc;
4072public:
4073  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4074                       IdentifierInfo &accessor, SourceLocation loc)
4075    : Expr(ExtVectorElementExprClass, ty, VK,
4076           (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4077           base->isTypeDependent(), base->isValueDependent(),
4078           base->isInstantiationDependent(),
4079           base->containsUnexpandedParameterPack()),
4080      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4081
4082  /// \brief Build an empty vector element expression.
4083  explicit ExtVectorElementExpr(EmptyShell Empty)
4084    : Expr(ExtVectorElementExprClass, Empty) { }
4085
4086  const Expr *getBase() const { return cast<Expr>(Base); }
4087  Expr *getBase() { return cast<Expr>(Base); }
4088  void setBase(Expr *E) { Base = E; }
4089
4090  IdentifierInfo &getAccessor() const { return *Accessor; }
4091  void setAccessor(IdentifierInfo *II) { Accessor = II; }
4092
4093  SourceLocation getAccessorLoc() const { return AccessorLoc; }
4094  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4095
4096  /// getNumElements - Get the number of components being selected.
4097  unsigned getNumElements() const;
4098
4099  /// containsDuplicateElements - Return true if any element access is
4100  /// repeated.
4101  bool containsDuplicateElements() const;
4102
4103  /// getEncodedElementAccess - Encode the elements accessed into an llvm
4104  /// aggregate Constant of ConstantInt(s).
4105  void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4106
4107  SourceRange getSourceRange() const {
4108    return SourceRange(getBase()->getLocStart(), AccessorLoc);
4109  }
4110
4111  /// isArrow - Return true if the base expression is a pointer to vector,
4112  /// return false if the base expression is a vector.
4113  bool isArrow() const;
4114
4115  static bool classof(const Stmt *T) {
4116    return T->getStmtClass() == ExtVectorElementExprClass;
4117  }
4118  static bool classof(const ExtVectorElementExpr *) { return true; }
4119
4120  // Iterators
4121  child_range children() { return child_range(&Base, &Base+1); }
4122};
4123
4124
4125/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4126/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
4127class BlockExpr : public Expr {
4128protected:
4129  BlockDecl *TheBlock;
4130public:
4131  BlockExpr(BlockDecl *BD, QualType ty)
4132    : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4133           ty->isDependentType(), false,
4134           // FIXME: Check for instantiate-dependence in the statement?
4135           ty->isInstantiationDependentType(),
4136           false),
4137      TheBlock(BD) {}
4138
4139  /// \brief Build an empty block expression.
4140  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4141
4142  const BlockDecl *getBlockDecl() const { return TheBlock; }
4143  BlockDecl *getBlockDecl() { return TheBlock; }
4144  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4145
4146  // Convenience functions for probing the underlying BlockDecl.
4147  SourceLocation getCaretLocation() const;
4148  const Stmt *getBody() const;
4149  Stmt *getBody();
4150
4151  SourceRange getSourceRange() const {
4152    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
4153  }
4154
4155  /// getFunctionType - Return the underlying function type for this block.
4156  const FunctionType *getFunctionType() const;
4157
4158  static bool classof(const Stmt *T) {
4159    return T->getStmtClass() == BlockExprClass;
4160  }
4161  static bool classof(const BlockExpr *) { return true; }
4162
4163  // Iterators
4164  child_range children() { return child_range(); }
4165};
4166
4167/// BlockDeclRefExpr - A reference to a local variable declared in an
4168/// enclosing scope.
4169class BlockDeclRefExpr : public Expr {
4170  VarDecl *D;
4171  SourceLocation Loc;
4172  bool IsByRef : 1;
4173  bool ConstQualAdded : 1;
4174public:
4175  BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
4176                   SourceLocation l, bool ByRef, bool constAdded = false);
4177
4178  // \brief Build an empty reference to a declared variable in a
4179  // block.
4180  explicit BlockDeclRefExpr(EmptyShell Empty)
4181    : Expr(BlockDeclRefExprClass, Empty) { }
4182
4183  VarDecl *getDecl() { return D; }
4184  const VarDecl *getDecl() const { return D; }
4185  void setDecl(VarDecl *VD) { D = VD; }
4186
4187  SourceLocation getLocation() const { return Loc; }
4188  void setLocation(SourceLocation L) { Loc = L; }
4189
4190  SourceRange getSourceRange() const { return SourceRange(Loc); }
4191
4192  bool isByRef() const { return IsByRef; }
4193  void setByRef(bool BR) { IsByRef = BR; }
4194
4195  bool isConstQualAdded() const { return ConstQualAdded; }
4196  void setConstQualAdded(bool C) { ConstQualAdded = C; }
4197
4198  static bool classof(const Stmt *T) {
4199    return T->getStmtClass() == BlockDeclRefExprClass;
4200  }
4201  static bool classof(const BlockDeclRefExpr *) { return true; }
4202
4203  // Iterators
4204  child_range children() { return child_range(); }
4205};
4206
4207/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4208/// This AST node provides support for reinterpreting a type to another
4209/// type of the same size.
4210class AsTypeExpr : public Expr { // Should this be an ExplicitCastExpr?
4211private:
4212  Stmt *SrcExpr;
4213  SourceLocation BuiltinLoc, RParenLoc;
4214
4215  friend class ASTReader;
4216  friend class ASTStmtReader;
4217  explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4218
4219public:
4220  AsTypeExpr(Expr* SrcExpr, QualType DstType,
4221             ExprValueKind VK, ExprObjectKind OK,
4222             SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4223    : Expr(AsTypeExprClass, DstType, VK, OK,
4224           DstType->isDependentType(),
4225           DstType->isDependentType() || SrcExpr->isValueDependent(),
4226           (DstType->isInstantiationDependentType() ||
4227            SrcExpr->isInstantiationDependent()),
4228           (DstType->containsUnexpandedParameterPack() ||
4229            SrcExpr->containsUnexpandedParameterPack())),
4230  SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4231
4232  /// getSrcExpr - Return the Expr to be converted.
4233  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4234
4235  /// getBuiltinLoc - Return the location of the __builtin_astype token.
4236  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4237
4238  /// getRParenLoc - Return the location of final right parenthesis.
4239  SourceLocation getRParenLoc() const { return RParenLoc; }
4240
4241  SourceRange getSourceRange() const {
4242    return SourceRange(BuiltinLoc, RParenLoc);
4243  }
4244
4245  static bool classof(const Stmt *T) {
4246    return T->getStmtClass() == AsTypeExprClass;
4247  }
4248  static bool classof(const AsTypeExpr *) { return true; }
4249
4250  // Iterators
4251  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4252};
4253
4254/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4255/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4256/// similarly-named C++0x instructions.  All of these instructions take one
4257/// primary pointer and at least one memory order.
4258class AtomicExpr : public Expr {
4259public:
4260  enum AtomicOp { Load, Store, CmpXchgStrong, CmpXchgWeak, Xchg,
4261                  Add, Sub, And, Or, Xor };
4262private:
4263  enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, END_EXPR };
4264  Stmt* SubExprs[END_EXPR];
4265  unsigned NumSubExprs;
4266  SourceLocation BuiltinLoc, RParenLoc;
4267  AtomicOp Op;
4268
4269public:
4270  AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr, QualType t,
4271             AtomicOp op, SourceLocation RP);
4272
4273  /// \brief Build an empty AtomicExpr.
4274  explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4275
4276  Expr *getPtr() const {
4277    return cast<Expr>(SubExprs[PTR]);
4278  }
4279  void setPtr(Expr *E) {
4280    SubExprs[PTR] = E;
4281  }
4282  Expr *getOrder() const {
4283    return cast<Expr>(SubExprs[ORDER]);
4284  }
4285  void setOrder(Expr *E) {
4286    SubExprs[ORDER] = E;
4287  }
4288  Expr *getVal1() const {
4289    assert(NumSubExprs >= 3);
4290    return cast<Expr>(SubExprs[VAL1]);
4291  }
4292  void setVal1(Expr *E) {
4293    assert(NumSubExprs >= 3);
4294    SubExprs[VAL1] = E;
4295  }
4296  Expr *getOrderFail() const {
4297    assert(NumSubExprs == 5);
4298    return cast<Expr>(SubExprs[ORDER_FAIL]);
4299  }
4300  void setOrderFail(Expr *E) {
4301    assert(NumSubExprs == 5);
4302    SubExprs[ORDER_FAIL] = E;
4303  }
4304  Expr *getVal2() const {
4305    assert(NumSubExprs == 5);
4306    return cast<Expr>(SubExprs[VAL2]);
4307  }
4308  void setVal2(Expr *E) {
4309    assert(NumSubExprs == 5);
4310    SubExprs[VAL2] = E;
4311  }
4312
4313  AtomicOp getOp() const { return Op; }
4314  void setOp(AtomicOp op) { Op = op; }
4315  unsigned getNumSubExprs() { return NumSubExprs; }
4316  void setNumSubExprs(unsigned num) { NumSubExprs = num; }
4317
4318  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4319
4320  bool isVolatile() const {
4321    return getPtr()->getType()->getPointeeType().isVolatileQualified();
4322  }
4323
4324  bool isCmpXChg() const {
4325    return getOp() == AtomicExpr::CmpXchgStrong ||
4326           getOp() == AtomicExpr::CmpXchgWeak;
4327  }
4328
4329  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4330  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4331
4332  SourceLocation getRParenLoc() const { return RParenLoc; }
4333  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4334
4335  SourceRange getSourceRange() const {
4336    return SourceRange(BuiltinLoc, RParenLoc);
4337  }
4338  static bool classof(const Stmt *T) {
4339    return T->getStmtClass() == AtomicExprClass;
4340  }
4341  static bool classof(const AtomicExpr *) { return true; }
4342
4343  // Iterators
4344  child_range children() {
4345    return child_range(SubExprs, SubExprs+NumSubExprs);
4346  }
4347};
4348}  // end namespace clang
4349
4350#endif
4351