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