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