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