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