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