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