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