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