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