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