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