Expr.h revision 87f55cf59e82f246d8605733e9300d0c5f6830a6
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 <vector>
24
25namespace clang {
26  class ASTContext;
27  class APValue;
28  class Decl;
29  class IdentifierInfo;
30  class ParmVarDecl;
31  class NamedDecl;
32  class ValueDecl;
33  class BlockDecl;
34  class CXXOperatorCallExpr;
35  class CXXMemberCallExpr;
36
37/// Expr - This represents one expression.  Note that Expr's are subclasses of
38/// Stmt.  This allows an expression to be transparently used any place a Stmt
39/// is required.
40///
41class Expr : public Stmt {
42  QualType TR;
43
44  /// TypeDependent - Whether this expression is type-dependent
45  /// (C++ [temp.dep.expr]).
46  bool TypeDependent : 1;
47
48  /// ValueDependent - Whether this expression is value-dependent
49  /// (C++ [temp.dep.constexpr]).
50  bool ValueDependent : 1;
51
52protected:
53  // FIXME: Eventually, this constructor should go away and we should
54  // require every subclass to provide type/value-dependence
55  // information.
56  Expr(StmtClass SC, QualType T)
57    : Stmt(SC), TypeDependent(false), ValueDependent(false) {
58    setType(T);
59  }
60
61  Expr(StmtClass SC, QualType T, bool TD, bool VD)
62    : Stmt(SC), TypeDependent(TD), ValueDependent(VD) {
63    setType(T);
64  }
65
66public:
67  QualType getType() const { return TR; }
68  void setType(QualType t) {
69    // In C++, the type of an expression is always adjusted so that it
70    // will not have reference type an expression will never have
71    // reference type (C++ [expr]p6). Use
72    // QualType::getNonReferenceType() to retrieve the non-reference
73    // type. Additionally, inspect Expr::isLvalue to determine whether
74    // an expression that is adjusted in this manner should be
75    // considered an lvalue.
76    assert((TR.isNull() || !TR->isReferenceType()) &&
77           "Expressions can't have reference type");
78
79    TR = t;
80  }
81
82  /// isValueDependent - Determines whether this expression is
83  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
84  /// array bound of "Chars" in the following example is
85  /// value-dependent.
86  /// @code
87  /// template<int Size, char (&Chars)[Size]> struct meta_string;
88  /// @endcode
89  bool isValueDependent() const { return ValueDependent; }
90
91  /// isTypeDependent - Determines whether this expression is
92  /// type-dependent (C++ [temp.dep.expr]), which means that its type
93  /// could change from one template instantiation to the next. For
94  /// example, the expressions "x" and "x + y" are type-dependent in
95  /// the following code, but "y" is not type-dependent:
96  /// @code
97  /// template<typename T>
98  /// void add(T x, int y) {
99  ///   x + y;
100  /// }
101  /// @endcode
102  bool isTypeDependent() const { return TypeDependent; }
103
104  /// SourceLocation tokens are not useful in isolation - they are low level
105  /// value objects created/interpreted by SourceManager. We assume AST
106  /// clients will have a pointer to the respective SourceManager.
107  virtual SourceRange getSourceRange() const = 0;
108
109  /// getExprLoc - Return the preferred location for the arrow when diagnosing
110  /// a problem with a generic expression.
111  virtual SourceLocation getExprLoc() const { return getLocStart(); }
112
113  /// hasLocalSideEffect - Return true if this immediate expression has side
114  /// effects, not counting any sub-expressions.
115  bool hasLocalSideEffect() const;
116
117  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
118  /// incomplete type other than void. Nonarray expressions that can be lvalues:
119  ///  - name, where name must be a variable
120  ///  - e[i]
121  ///  - (e), where e must be an lvalue
122  ///  - e.name, where e must be an lvalue
123  ///  - e->name
124  ///  - *e, the type of e cannot be a function type
125  ///  - string-constant
126  ///  - reference type [C++ [expr]]
127  ///
128  enum isLvalueResult {
129    LV_Valid,
130    LV_NotObjectType,
131    LV_IncompleteVoidType,
132    LV_DuplicateVectorComponents,
133    LV_InvalidExpression,
134    LV_MemberFunction
135  };
136  isLvalueResult isLvalue(ASTContext &Ctx) const;
137
138  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
139  /// does not have an incomplete type, does not have a const-qualified type,
140  /// and if it is a structure or union, does not have any member (including,
141  /// recursively, any member or element of all contained aggregates or unions)
142  /// with a const-qualified type.
143  enum isModifiableLvalueResult {
144    MLV_Valid,
145    MLV_NotObjectType,
146    MLV_IncompleteVoidType,
147    MLV_DuplicateVectorComponents,
148    MLV_InvalidExpression,
149    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
150    MLV_IncompleteType,
151    MLV_ConstQualified,
152    MLV_ArrayType,
153    MLV_NotBlockQualified,
154    MLV_ReadonlyProperty,
155    MLV_NoSetterProperty,
156    MLV_MemberFunction
157  };
158  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx) const;
159
160  bool isBitField();
161
162  /// getIntegerConstantExprValue() - Return the value of an integer
163  /// constant expression. The expression must be a valid integer
164  /// constant expression as determined by isIntegerConstantExpr.
165  llvm::APSInt getIntegerConstantExprValue(ASTContext &Ctx) const {
166    llvm::APSInt X;
167    bool success = isIntegerConstantExpr(X, Ctx);
168    success = success;
169    assert(success && "Illegal argument to getIntegerConstantExpr");
170    return X;
171  }
172
173  /// isIntegerConstantExpr - Return true if this expression is a valid integer
174  /// constant expression, and, if so, return its value in Result.  If not a
175  /// valid i-c-e, return false and fill in Loc (if specified) with the location
176  /// of the invalid expression.
177  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
178                             SourceLocation *Loc = 0,
179                             bool isEvaluated = true) const;
180  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
181    llvm::APSInt X;
182    return isIntegerConstantExpr(X, Ctx, Loc);
183  }
184  /// isConstantExpr - Return true if this expression is a valid constant expr.
185  bool isConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const;
186
187  /// EvalResult is a struct with detailed info about an evaluated expression.
188  struct EvalResult {
189    /// Val - This is the scalar value the expression can be folded to.
190    APValue Val;
191
192    /// HasSideEffects - Whether the evaluated expression has side effects.
193    /// For example, (f() && 0) can be folded, but it still has side effects.
194    bool HasSideEffects;
195
196    /// Diag - If the expression is unfoldable, then Diag contains a note
197    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
198    /// position for the error, and DiagExpr is the expression that caused
199    /// the error.
200    /// If the expression is foldable, but not an integer constant expression,
201    /// Diag contains a note diagnostic that describes why it isn't an integer
202    /// constant expression. If the expression *is* an integer constant
203    /// expression, then Diag will be zero.
204    unsigned Diag;
205    const Expr *DiagExpr;
206    SourceLocation DiagLoc;
207
208    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
209  };
210
211  /// Evaluate - Return true if this is a constant which we can fold using
212  /// any crazy technique (that has nothing to do with language standards) that
213  /// we want to.  If this function returns true, it returns the folded constant
214  /// in Result.
215  bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
216
217  /// isEvaluatable - Call Evaluate to see if this expression can be constant
218  /// folded, but discard the result.
219  bool isEvaluatable(ASTContext &Ctx) const;
220
221  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
222  /// must be called on an expression that constant folds to an integer.
223  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
224
225  /// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
226  /// integer constant expression with the value zero, or if this is one that is
227  /// cast to void*.
228  bool isNullPointerConstant(ASTContext &Ctx) const;
229
230  /// hasGlobalStorage - Return true if this expression has static storage
231  /// duration.  This means that the address of this expression is a link-time
232  /// constant.
233  bool hasGlobalStorage() const;
234
235  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
236  ///  its subexpression.  If that subexpression is also a ParenExpr,
237  ///  then this method recursively returns its subexpression, and so forth.
238  ///  Otherwise, the method returns the current Expr.
239  Expr* IgnoreParens();
240
241  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
242  /// or CastExprs, returning their operand.
243  Expr *IgnoreParenCasts();
244
245  const Expr* IgnoreParens() const {
246    return const_cast<Expr*>(this)->IgnoreParens();
247  }
248  const Expr *IgnoreParenCasts() const {
249    return const_cast<Expr*>(this)->IgnoreParenCasts();
250  }
251
252  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
253  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
254
255  static bool classof(const Stmt *T) {
256    return T->getStmtClass() >= firstExprConstant &&
257           T->getStmtClass() <= lastExprConstant;
258  }
259  static bool classof(const Expr *) { return true; }
260
261  static inline Expr* Create(llvm::Deserializer& D, ASTContext& C) {
262    return cast<Expr>(Stmt::Create(D, C));
263  }
264};
265
266
267//===----------------------------------------------------------------------===//
268// Primary Expressions.
269//===----------------------------------------------------------------------===//
270
271/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
272/// enum, etc.
273class DeclRefExpr : public Expr {
274  NamedDecl *D;
275  SourceLocation Loc;
276
277protected:
278  // FIXME: Eventually, this constructor will go away and all subclasses
279  // will have to provide the type- and value-dependent flags.
280  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l) :
281    Expr(SC, t), D(d), Loc(l) {}
282
283  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l, bool TD,
284              bool VD) :
285    Expr(SC, t, TD, VD), D(d), Loc(l) {}
286
287public:
288  // FIXME: Eventually, this constructor will go away and all clients
289  // will have to provide the type- and value-dependent flags.
290  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) :
291    Expr(DeclRefExprClass, t), D(d), Loc(l) {}
292
293  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, bool VD) :
294    Expr(DeclRefExprClass, t, TD, VD), D(d), Loc(l) {}
295
296  NamedDecl *getDecl() { return D; }
297  const NamedDecl *getDecl() const { return D; }
298  void setDecl(NamedDecl *NewD) { D = NewD; }
299
300  SourceLocation getLocation() const { return Loc; }
301  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
302
303  static bool classof(const Stmt *T) {
304    return T->getStmtClass() == DeclRefExprClass ||
305           T->getStmtClass() == CXXConditionDeclExprClass ||
306           T->getStmtClass() == QualifiedDeclRefExprClass;
307  }
308  static bool classof(const DeclRefExpr *) { return true; }
309
310  // Iterators
311  virtual child_iterator child_begin();
312  virtual child_iterator child_end();
313
314  virtual void EmitImpl(llvm::Serializer& S) const;
315  static DeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
316};
317
318/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
319class PredefinedExpr : public Expr {
320public:
321  enum IdentType {
322    Func,
323    Function,
324    PrettyFunction
325  };
326
327private:
328  SourceLocation Loc;
329  IdentType Type;
330public:
331  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
332    : Expr(PredefinedExprClass, type), Loc(l), Type(IT) {}
333
334  IdentType getIdentType() const { return Type; }
335
336  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
337
338  static bool classof(const Stmt *T) {
339    return T->getStmtClass() == PredefinedExprClass;
340  }
341  static bool classof(const PredefinedExpr *) { return true; }
342
343  // Iterators
344  virtual child_iterator child_begin();
345  virtual child_iterator child_end();
346
347  virtual void EmitImpl(llvm::Serializer& S) const;
348  static PredefinedExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
349};
350
351class IntegerLiteral : public Expr {
352  llvm::APInt Value;
353  SourceLocation Loc;
354public:
355  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
356  // or UnsignedLongLongTy
357  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
358    : Expr(IntegerLiteralClass, type), Value(V), Loc(l) {
359    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
360  }
361  const llvm::APInt &getValue() const { return Value; }
362  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
363
364  static bool classof(const Stmt *T) {
365    return T->getStmtClass() == IntegerLiteralClass;
366  }
367  static bool classof(const IntegerLiteral *) { return true; }
368
369  // Iterators
370  virtual child_iterator child_begin();
371  virtual child_iterator child_end();
372
373  virtual void EmitImpl(llvm::Serializer& S) const;
374  static IntegerLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
375};
376
377class CharacterLiteral : public Expr {
378  unsigned Value;
379  SourceLocation Loc;
380  bool IsWide;
381public:
382  // type should be IntTy
383  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
384    : Expr(CharacterLiteralClass, type), Value(value), Loc(l), IsWide(iswide) {
385  }
386  SourceLocation getLoc() const { return Loc; }
387  bool isWide() const { return IsWide; }
388
389  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
390
391  unsigned getValue() const { return Value; }
392
393  static bool classof(const Stmt *T) {
394    return T->getStmtClass() == CharacterLiteralClass;
395  }
396  static bool classof(const CharacterLiteral *) { return true; }
397
398  // Iterators
399  virtual child_iterator child_begin();
400  virtual child_iterator child_end();
401
402  virtual void EmitImpl(llvm::Serializer& S) const;
403  static CharacterLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
404};
405
406class FloatingLiteral : public Expr {
407  llvm::APFloat Value;
408  bool IsExact : 1;
409  SourceLocation Loc;
410public:
411  FloatingLiteral(const llvm::APFloat &V, bool* isexact,
412                  QualType Type, SourceLocation L)
413    : Expr(FloatingLiteralClass, Type), Value(V), IsExact(*isexact), Loc(L) {}
414
415  const llvm::APFloat &getValue() const { return Value; }
416
417  bool isExact() const { return IsExact; }
418
419  /// getValueAsApproximateDouble - This returns the value as an inaccurate
420  /// double.  Note that this may cause loss of precision, but is useful for
421  /// debugging dumps, etc.
422  double getValueAsApproximateDouble() const;
423
424  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
425
426  static bool classof(const Stmt *T) {
427    return T->getStmtClass() == FloatingLiteralClass;
428  }
429  static bool classof(const FloatingLiteral *) { return true; }
430
431  // Iterators
432  virtual child_iterator child_begin();
433  virtual child_iterator child_end();
434
435  virtual void EmitImpl(llvm::Serializer& S) const;
436  static FloatingLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
437};
438
439/// ImaginaryLiteral - We support imaginary integer and floating point literals,
440/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
441/// IntegerLiteral classes.  Instances of this class always have a Complex type
442/// whose element type matches the subexpression.
443///
444class ImaginaryLiteral : public Expr {
445  Stmt *Val;
446public:
447  ImaginaryLiteral(Expr *val, QualType Ty)
448    : Expr(ImaginaryLiteralClass, Ty), Val(val) {}
449
450  const Expr *getSubExpr() const { return cast<Expr>(Val); }
451  Expr *getSubExpr() { return cast<Expr>(Val); }
452
453  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
454  static bool classof(const Stmt *T) {
455    return T->getStmtClass() == ImaginaryLiteralClass;
456  }
457  static bool classof(const ImaginaryLiteral *) { return true; }
458
459  // Iterators
460  virtual child_iterator child_begin();
461  virtual child_iterator child_end();
462
463  virtual void EmitImpl(llvm::Serializer& S) const;
464  static ImaginaryLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
465};
466
467/// StringLiteral - This represents a string literal expression, e.g. "foo"
468/// or L"bar" (wide strings).  The actual string is returned by getStrData()
469/// is NOT null-terminated, and the length of the string is determined by
470/// calling getByteLength().  The C type for a string is always a
471/// ConstantArrayType.
472class StringLiteral : public Expr {
473  const char *StrData;
474  unsigned ByteLength;
475  bool IsWide;
476  // if the StringLiteral was composed using token pasting, both locations
477  // are needed. If not (the common case), firstTokLoc == lastTokLoc.
478  // FIXME: if space becomes an issue, we should create a sub-class.
479  SourceLocation firstTokLoc, lastTokLoc;
480public:
481  StringLiteral(const char *strData, unsigned byteLength, bool Wide,
482                QualType t, SourceLocation b, SourceLocation e);
483  virtual ~StringLiteral();
484
485  const char *getStrData() const { return StrData; }
486  unsigned getByteLength() const { return ByteLength; }
487  bool isWide() const { return IsWide; }
488
489  virtual SourceRange getSourceRange() const {
490    return SourceRange(firstTokLoc,lastTokLoc);
491  }
492  static bool classof(const Stmt *T) {
493    return T->getStmtClass() == StringLiteralClass;
494  }
495  static bool classof(const StringLiteral *) { return true; }
496
497  // Iterators
498  virtual child_iterator child_begin();
499  virtual child_iterator child_end();
500
501  virtual void EmitImpl(llvm::Serializer& S) const;
502  static StringLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
503};
504
505/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
506/// AST node is only formed if full location information is requested.
507class ParenExpr : public Expr {
508  SourceLocation L, R;
509  Stmt *Val;
510public:
511  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
512    : Expr(ParenExprClass, val->getType(),
513           val->isTypeDependent(), val->isValueDependent()),
514      L(l), R(r), Val(val) {}
515
516  const Expr *getSubExpr() const { return cast<Expr>(Val); }
517  Expr *getSubExpr() { return cast<Expr>(Val); }
518  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
519
520  static bool classof(const Stmt *T) {
521    return T->getStmtClass() == ParenExprClass;
522  }
523  static bool classof(const ParenExpr *) { return true; }
524
525  // Iterators
526  virtual child_iterator child_begin();
527  virtual child_iterator child_end();
528
529  virtual void EmitImpl(llvm::Serializer& S) const;
530  static ParenExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
531};
532
533
534/// UnaryOperator - This represents the unary-expression's (except sizeof and
535/// alignof), the postinc/postdec operators from postfix-expression, and various
536/// extensions.
537///
538/// Notes on various nodes:
539///
540/// Real/Imag - These return the real/imag part of a complex operand.  If
541///   applied to a non-complex value, the former returns its operand and the
542///   later returns zero in the type of the operand.
543///
544/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
545///   subexpression is a compound literal with the various MemberExpr and
546///   ArraySubscriptExpr's applied to it.
547///
548class UnaryOperator : public Expr {
549public:
550  // Note that additions to this should also update the StmtVisitor class.
551  enum Opcode {
552    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
553    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
554    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
555    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
556    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
557    Real, Imag,       // "__real expr"/"__imag expr" Extension.
558    Extension,        // __extension__ marker.
559    OffsetOf          // __builtin_offsetof
560  };
561private:
562  Stmt *Val;
563  Opcode Opc;
564  SourceLocation Loc;
565public:
566
567  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
568    : Expr(UnaryOperatorClass, type,
569           input->isTypeDependent() && opc != OffsetOf,
570           input->isValueDependent()),
571      Val(input), Opc(opc), Loc(l) {}
572
573  Opcode getOpcode() const { return Opc; }
574  Expr *getSubExpr() const { return cast<Expr>(Val); }
575
576  /// getOperatorLoc - Return the location of the operator.
577  SourceLocation getOperatorLoc() const { return Loc; }
578
579  /// isPostfix - Return true if this is a postfix operation, like x++.
580  static bool isPostfix(Opcode Op);
581
582  /// isPostfix - Return true if this is a prefix operation, like --x.
583  static bool isPrefix(Opcode Op);
584
585  bool isPrefix() const { return isPrefix(Opc); }
586  bool isPostfix() const { return isPostfix(Opc); }
587  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
588  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
589  bool isOffsetOfOp() const { return Opc == OffsetOf; }
590  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
591
592  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
593  /// corresponds to, e.g. "sizeof" or "[pre]++"
594  static const char *getOpcodeStr(Opcode Op);
595
596  virtual SourceRange getSourceRange() const {
597    if (isPostfix())
598      return SourceRange(Val->getLocStart(), Loc);
599    else
600      return SourceRange(Loc, Val->getLocEnd());
601  }
602  virtual SourceLocation getExprLoc() const { return Loc; }
603
604  static bool classof(const Stmt *T) {
605    return T->getStmtClass() == UnaryOperatorClass;
606  }
607  static bool classof(const UnaryOperator *) { return true; }
608
609  int64_t evaluateOffsetOf(ASTContext& C) const;
610
611  // Iterators
612  virtual child_iterator child_begin();
613  virtual child_iterator child_end();
614
615  virtual void EmitImpl(llvm::Serializer& S) const;
616  static UnaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
617};
618
619/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
620/// types and expressions.
621class SizeOfAlignOfExpr : public Expr {
622  bool isSizeof : 1;  // true if sizeof, false if alignof.
623  bool isType : 1;    // true if operand is a type, false if an expression
624  union {
625    void *Ty;
626    Stmt *Ex;
627  } Argument;
628  SourceLocation OpLoc, RParenLoc;
629public:
630  SizeOfAlignOfExpr(bool issizeof, bool istype, void *argument,
631                    QualType resultType, SourceLocation op,
632                    SourceLocation rp) :
633      Expr(SizeOfAlignOfExprClass, resultType), isSizeof(issizeof),
634      isType(istype), OpLoc(op), RParenLoc(rp) {
635    if (isType)
636      Argument.Ty = argument;
637    else
638      // argument was an Expr*, so cast it back to that to be safe
639      Argument.Ex = static_cast<Expr*>(argument);
640  }
641
642  virtual void Destroy(ASTContext& C);
643
644  bool isSizeOf() const { return isSizeof; }
645  bool isArgumentType() const { return isType; }
646  QualType getArgumentType() const {
647    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
648    return QualType::getFromOpaquePtr(Argument.Ty);
649  }
650  Expr* getArgumentExpr() const {
651    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
652    return static_cast<Expr*>(Argument.Ex);
653  }
654  /// Gets the argument type, or the type of the argument expression, whichever
655  /// is appropriate.
656  QualType getTypeOfArgument() const {
657    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
658  }
659
660  SourceLocation getOperatorLoc() const { return OpLoc; }
661
662  virtual SourceRange getSourceRange() const {
663    return SourceRange(OpLoc, RParenLoc);
664  }
665
666  static bool classof(const Stmt *T) {
667    return T->getStmtClass() == SizeOfAlignOfExprClass;
668  }
669  static bool classof(const SizeOfAlignOfExpr *) { return true; }
670
671  // Iterators
672  virtual child_iterator child_begin();
673  virtual child_iterator child_end();
674
675  virtual void EmitImpl(llvm::Serializer& S) const;
676  static SizeOfAlignOfExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
677};
678
679//===----------------------------------------------------------------------===//
680// Postfix Operators.
681//===----------------------------------------------------------------------===//
682
683/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
684class ArraySubscriptExpr : public Expr {
685  enum { LHS, RHS, END_EXPR=2 };
686  Stmt* SubExprs[END_EXPR];
687  SourceLocation RBracketLoc;
688public:
689  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
690                     SourceLocation rbracketloc)
691  : Expr(ArraySubscriptExprClass, t), RBracketLoc(rbracketloc) {
692    SubExprs[LHS] = lhs;
693    SubExprs[RHS] = rhs;
694  }
695
696  /// An array access can be written A[4] or 4[A] (both are equivalent).
697  /// - getBase() and getIdx() always present the normalized view: A[4].
698  ///    In this case getBase() returns "A" and getIdx() returns "4".
699  /// - getLHS() and getRHS() present the syntactic view. e.g. for
700  ///    4[A] getLHS() returns "4".
701  /// Note: Because vector element access is also written A[4] we must
702  /// predicate the format conversion in getBase and getIdx only on the
703  /// the type of the RHS, as it is possible for the LHS to be a vector of
704  /// integer type
705  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
706  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
707
708  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
709  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
710
711  Expr *getBase() {
712    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
713  }
714
715  const Expr *getBase() const {
716    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
717  }
718
719  Expr *getIdx() {
720    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
721  }
722
723  const Expr *getIdx() const {
724    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
725  }
726
727  virtual SourceRange getSourceRange() const {
728    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
729  }
730
731  virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
732
733  static bool classof(const Stmt *T) {
734    return T->getStmtClass() == ArraySubscriptExprClass;
735  }
736  static bool classof(const ArraySubscriptExpr *) { return true; }
737
738  // Iterators
739  virtual child_iterator child_begin();
740  virtual child_iterator child_end();
741
742  virtual void EmitImpl(llvm::Serializer& S) const;
743  static ArraySubscriptExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
744};
745
746
747/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
748/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
749/// while its subclasses may represent alternative syntax that (semantically)
750/// results in a function call. For example, CXXOperatorCallExpr is
751/// a subclass for overloaded operator calls that use operator syntax, e.g.,
752/// "str1 + str2" to resolve to a function call.
753class CallExpr : public Expr {
754  enum { FN=0, ARGS_START=1 };
755  Stmt **SubExprs;
756  unsigned NumArgs;
757  SourceLocation RParenLoc;
758
759  // This version of the ctor is for deserialization.
760  CallExpr(StmtClass SC, Stmt** subexprs, unsigned numargs, QualType t,
761           SourceLocation rparenloc)
762  : Expr(SC,t), SubExprs(subexprs),
763    NumArgs(numargs), RParenLoc(rparenloc) {}
764
765protected:
766  // This version of the constructor is for derived classes.
767  CallExpr(StmtClass SC, Expr *fn, Expr **args, unsigned numargs, QualType t,
768           SourceLocation rparenloc);
769
770public:
771  CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
772           SourceLocation rparenloc);
773  ~CallExpr() {
774    delete [] SubExprs;
775  }
776
777  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
778  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
779  void setCallee(Expr *F) { SubExprs[FN] = F; }
780
781  /// getNumArgs - Return the number of actual arguments to this call.
782  ///
783  unsigned getNumArgs() const { return NumArgs; }
784
785  /// getArg - Return the specified argument.
786  Expr *getArg(unsigned Arg) {
787    assert(Arg < NumArgs && "Arg access out of range!");
788    return cast<Expr>(SubExprs[Arg+ARGS_START]);
789  }
790  const Expr *getArg(unsigned Arg) const {
791    assert(Arg < NumArgs && "Arg access out of range!");
792    return cast<Expr>(SubExprs[Arg+ARGS_START]);
793  }
794  /// setArg - Set the specified argument.
795  void setArg(unsigned Arg, Expr *ArgExpr) {
796    assert(Arg < NumArgs && "Arg access out of range!");
797    SubExprs[Arg+ARGS_START] = ArgExpr;
798  }
799
800  /// setNumArgs - This changes the number of arguments present in this call.
801  /// Any orphaned expressions are deleted by this, and any new operands are set
802  /// to null.
803  void setNumArgs(unsigned NumArgs);
804
805  typedef ExprIterator arg_iterator;
806  typedef ConstExprIterator const_arg_iterator;
807
808  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
809  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
810  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
811  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
812
813  /// getNumCommas - Return the number of commas that must have been present in
814  /// this function call.
815  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
816
817  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
818  /// not, return 0.
819  unsigned isBuiltinCall() const;
820
821  SourceLocation getRParenLoc() const { return RParenLoc; }
822
823  virtual SourceRange getSourceRange() const {
824    return SourceRange(getCallee()->getLocStart(), RParenLoc);
825  }
826
827  static bool classof(const Stmt *T) {
828    return T->getStmtClass() == CallExprClass ||
829           T->getStmtClass() == CXXOperatorCallExprClass ||
830           T->getStmtClass() == CXXMemberCallExprClass;
831  }
832  static bool classof(const CallExpr *) { return true; }
833  static bool classof(const CXXOperatorCallExpr *) { return true; }
834  static bool classof(const CXXMemberCallExpr *) { return true; }
835
836  // Iterators
837  virtual child_iterator child_begin();
838  virtual child_iterator child_end();
839
840  virtual void EmitImpl(llvm::Serializer& S) const;
841  static CallExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C,
842                              StmtClass SC);
843};
844
845/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.
846///
847class MemberExpr : public Expr {
848  Stmt *Base;
849  NamedDecl *MemberDecl;
850  SourceLocation MemberLoc;
851  bool IsArrow;      // True if this is "X->F", false if this is "X.F".
852public:
853  MemberExpr(Expr *base, bool isarrow, NamedDecl *memberdecl, SourceLocation l,
854             QualType ty)
855    : Expr(MemberExprClass, ty),
856      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {}
857
858  void setBase(Expr *E) { Base = E; }
859  Expr *getBase() const { return cast<Expr>(Base); }
860  NamedDecl *getMemberDecl() const { return MemberDecl; }
861  void setMemberDecl(NamedDecl *D) { MemberDecl = D; }
862  bool isArrow() const { return IsArrow; }
863
864  virtual SourceRange getSourceRange() const {
865    return SourceRange(getBase()->getLocStart(), MemberLoc);
866  }
867
868  virtual SourceLocation getExprLoc() const { return MemberLoc; }
869
870  static bool classof(const Stmt *T) {
871    return T->getStmtClass() == MemberExprClass;
872  }
873  static bool classof(const MemberExpr *) { return true; }
874
875  // Iterators
876  virtual child_iterator child_begin();
877  virtual child_iterator child_end();
878
879  virtual void EmitImpl(llvm::Serializer& S) const;
880  static MemberExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
881};
882
883/// CompoundLiteralExpr - [C99 6.5.2.5]
884///
885class CompoundLiteralExpr : public Expr {
886  /// LParenLoc - If non-null, this is the location of the left paren in a
887  /// compound literal like "(int){4}".  This can be null if this is a
888  /// synthesized compound expression.
889  SourceLocation LParenLoc;
890  Stmt *Init;
891  bool FileScope;
892public:
893  CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init,
894                      bool fileScope)
895    : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init),
896      FileScope(fileScope) {}
897
898  const Expr *getInitializer() const { return cast<Expr>(Init); }
899  Expr *getInitializer() { return cast<Expr>(Init); }
900
901  bool isFileScope() const { return FileScope; }
902
903  SourceLocation getLParenLoc() const { return LParenLoc; }
904
905  virtual SourceRange getSourceRange() const {
906    // FIXME: Init should never be null.
907    if (!Init)
908      return SourceRange();
909    if (LParenLoc.isInvalid())
910      return Init->getSourceRange();
911    return SourceRange(LParenLoc, Init->getLocEnd());
912  }
913
914  static bool classof(const Stmt *T) {
915    return T->getStmtClass() == CompoundLiteralExprClass;
916  }
917  static bool classof(const CompoundLiteralExpr *) { return true; }
918
919  // Iterators
920  virtual child_iterator child_begin();
921  virtual child_iterator child_end();
922
923  virtual void EmitImpl(llvm::Serializer& S) const;
924  static CompoundLiteralExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
925};
926
927/// CastExpr - Base class for type casts, including both implicit
928/// casts (ImplicitCastExpr) and explicit casts that have some
929/// representation in the source code (ExplicitCastExpr's derived
930/// classes).
931class CastExpr : public Expr {
932  Stmt *Op;
933protected:
934  CastExpr(StmtClass SC, QualType ty, Expr *op) :
935    Expr(SC, ty,
936         // Cast expressions are type-dependent if the type is
937         // dependent (C++ [temp.dep.expr]p3).
938         ty->isDependentType(),
939         // Cast expressions are value-dependent if the type is
940         // dependent or if the subexpression is value-dependent.
941         ty->isDependentType() || (op && op->isValueDependent())),
942    Op(op) {}
943
944public:
945  Expr *getSubExpr() { return cast<Expr>(Op); }
946  const Expr *getSubExpr() const { return cast<Expr>(Op); }
947
948  static bool classof(const Stmt *T) {
949    StmtClass SC = T->getStmtClass();
950    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
951      return true;
952
953    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
954      return true;
955
956    return false;
957  }
958  static bool classof(const CastExpr *) { return true; }
959
960  // Iterators
961  virtual child_iterator child_begin();
962  virtual child_iterator child_end();
963};
964
965/// ImplicitCastExpr - Allows us to explicitly represent implicit type
966/// conversions, which have no direct representation in the original
967/// source code. For example: converting T[]->T*, void f()->void
968/// (*f)(), float->double, short->int, etc.
969///
970/// In C, implicit casts always produce rvalues. However, in C++, an
971/// implicit cast whose result is being bound to a reference will be
972/// an lvalue. For example:
973///
974/// @code
975/// class Base { };
976/// class Derived : public Base { };
977/// void f(Derived d) {
978///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
979/// }
980/// @endcode
981class ImplicitCastExpr : public CastExpr {
982  /// LvalueCast - Whether this cast produces an lvalue.
983  bool LvalueCast;
984
985public:
986  ImplicitCastExpr(QualType ty, Expr *op, bool Lvalue) :
987    CastExpr(ImplicitCastExprClass, ty, op), LvalueCast(Lvalue) { }
988
989  virtual SourceRange getSourceRange() const {
990    return getSubExpr()->getSourceRange();
991  }
992
993  /// isLvalueCast - Whether this cast produces an lvalue.
994  bool isLvalueCast() const { return LvalueCast; }
995
996  /// setLvalueCast - Set whether this cast produces an lvalue.
997  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
998
999  static bool classof(const Stmt *T) {
1000    return T->getStmtClass() == ImplicitCastExprClass;
1001  }
1002  static bool classof(const ImplicitCastExpr *) { return true; }
1003
1004  virtual void EmitImpl(llvm::Serializer& S) const;
1005  static ImplicitCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1006};
1007
1008/// ExplicitCastExpr - An explicit cast written in the source
1009/// code.
1010///
1011/// This class is effectively an abstract class, because it provides
1012/// the basic representation of an explicitly-written cast without
1013/// specifying which kind of cast (C cast, functional cast, static
1014/// cast, etc.) was written; specific derived classes represent the
1015/// particular style of cast and its location information.
1016///
1017/// Unlike implicit casts, explicit cast nodes have two different
1018/// types: the type that was written into the source code, and the
1019/// actual type of the expression as determined by semantic
1020/// analysis. These types may differ slightly. For example, in C++ one
1021/// can cast to a reference type, which indicates that the resulting
1022/// expression will be an lvalue. The reference type, however, will
1023/// not be used as the type of the expression.
1024class ExplicitCastExpr : public CastExpr {
1025  /// TypeAsWritten - The type that this expression is casting to, as
1026  /// written in the source code.
1027  QualType TypeAsWritten;
1028
1029protected:
1030  ExplicitCastExpr(StmtClass SC, QualType exprTy, Expr *op, QualType writtenTy)
1031    : CastExpr(SC, exprTy, op), TypeAsWritten(writtenTy) {}
1032
1033public:
1034  /// getTypeAsWritten - Returns the type that this expression is
1035  /// casting to, as written in the source code.
1036  QualType getTypeAsWritten() const { return TypeAsWritten; }
1037
1038  static bool classof(const Stmt *T) {
1039    StmtClass SC = T->getStmtClass();
1040    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
1041      return true;
1042    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1043      return true;
1044
1045    return false;
1046  }
1047  static bool classof(const ExplicitCastExpr *) { return true; }
1048};
1049
1050/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1051/// cast in C++ (C++ [expr.cast]), which uses the syntax
1052/// (Type)expr. For example: @c (int)f.
1053class CStyleCastExpr : public ExplicitCastExpr {
1054  SourceLocation LPLoc; // the location of the left paren
1055  SourceLocation RPLoc; // the location of the right paren
1056public:
1057  CStyleCastExpr(QualType exprTy, Expr *op, QualType writtenTy,
1058                    SourceLocation l, SourceLocation r) :
1059    ExplicitCastExpr(CStyleCastExprClass, exprTy, op, writtenTy),
1060    LPLoc(l), RPLoc(r) {}
1061
1062  SourceLocation getLParenLoc() const { return LPLoc; }
1063  SourceLocation getRParenLoc() const { return RPLoc; }
1064
1065  virtual SourceRange getSourceRange() const {
1066    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1067  }
1068  static bool classof(const Stmt *T) {
1069    return T->getStmtClass() == CStyleCastExprClass;
1070  }
1071  static bool classof(const CStyleCastExpr *) { return true; }
1072
1073  virtual void EmitImpl(llvm::Serializer& S) const;
1074  static CStyleCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1075};
1076
1077class BinaryOperator : public Expr {
1078public:
1079  enum Opcode {
1080    // Operators listed in order of precedence.
1081    // Note that additions to this should also update the StmtVisitor class.
1082    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1083    Add, Sub,         // [C99 6.5.6] Additive operators.
1084    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1085    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1086    EQ, NE,           // [C99 6.5.9] Equality operators.
1087    And,              // [C99 6.5.10] Bitwise AND operator.
1088    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1089    Or,               // [C99 6.5.12] Bitwise OR operator.
1090    LAnd,             // [C99 6.5.13] Logical AND operator.
1091    LOr,              // [C99 6.5.14] Logical OR operator.
1092    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1093    DivAssign, RemAssign,
1094    AddAssign, SubAssign,
1095    ShlAssign, ShrAssign,
1096    AndAssign, XorAssign,
1097    OrAssign,
1098    Comma             // [C99 6.5.17] Comma operator.
1099  };
1100private:
1101  enum { LHS, RHS, END_EXPR };
1102  Stmt* SubExprs[END_EXPR];
1103  Opcode Opc;
1104  SourceLocation OpLoc;
1105public:
1106
1107  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1108                 SourceLocation opLoc)
1109    : Expr(BinaryOperatorClass, ResTy,
1110           lhs->isTypeDependent() || rhs->isTypeDependent(),
1111           lhs->isValueDependent() || rhs->isValueDependent()),
1112      Opc(opc), OpLoc(opLoc) {
1113    SubExprs[LHS] = lhs;
1114    SubExprs[RHS] = rhs;
1115    assert(!isCompoundAssignmentOp() &&
1116           "Use ArithAssignBinaryOperator for compound assignments");
1117  }
1118
1119  SourceLocation getOperatorLoc() const { return OpLoc; }
1120  Opcode getOpcode() const { return Opc; }
1121  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1122  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1123  virtual SourceRange getSourceRange() const {
1124    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1125  }
1126
1127  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1128  /// corresponds to, e.g. "<<=".
1129  static const char *getOpcodeStr(Opcode Op);
1130
1131  /// predicates to categorize the respective opcodes.
1132  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1133  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1134  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
1135  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
1136
1137  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1138  bool isRelationalOp() const { return isRelationalOp(Opc); }
1139
1140  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1141  bool isEqualityOp() const { return isEqualityOp(Opc); }
1142
1143  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1144  bool isLogicalOp() const { return isLogicalOp(Opc); }
1145
1146  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1147  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1148  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
1149
1150  static bool classof(const Stmt *S) {
1151    return S->getStmtClass() == BinaryOperatorClass ||
1152           S->getStmtClass() == CompoundAssignOperatorClass;
1153  }
1154  static bool classof(const BinaryOperator *) { return true; }
1155
1156  // Iterators
1157  virtual child_iterator child_begin();
1158  virtual child_iterator child_end();
1159
1160  virtual void EmitImpl(llvm::Serializer& S) const;
1161  static BinaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1162
1163protected:
1164  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1165                 SourceLocation oploc, bool dead)
1166    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
1167    SubExprs[LHS] = lhs;
1168    SubExprs[RHS] = rhs;
1169  }
1170};
1171
1172/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
1173/// track of the type the operation is performed in.  Due to the semantics of
1174/// these operators, the operands are promoted, the aritmetic performed, an
1175/// implicit conversion back to the result type done, then the assignment takes
1176/// place.  This captures the intermediate type which the computation is done
1177/// in.
1178class CompoundAssignOperator : public BinaryOperator {
1179  QualType ComputationType;
1180public:
1181  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1182                         QualType ResType, QualType CompType,
1183                         SourceLocation OpLoc)
1184    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1185      ComputationType(CompType) {
1186    assert(isCompoundAssignmentOp() &&
1187           "Only should be used for compound assignments");
1188  }
1189
1190  QualType getComputationType() const { return ComputationType; }
1191
1192  static bool classof(const CompoundAssignOperator *) { return true; }
1193  static bool classof(const Stmt *S) {
1194    return S->getStmtClass() == CompoundAssignOperatorClass;
1195  }
1196
1197  virtual void EmitImpl(llvm::Serializer& S) const;
1198  static CompoundAssignOperator* CreateImpl(llvm::Deserializer& D,
1199                                            ASTContext& C);
1200};
1201
1202/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1203/// GNU "missing LHS" extension is in use.
1204///
1205class ConditionalOperator : public Expr {
1206  enum { COND, LHS, RHS, END_EXPR };
1207  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1208public:
1209  ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t)
1210    : Expr(ConditionalOperatorClass, t,
1211           // FIXME: the type of the conditional operator doesn't
1212           // depend on the type of the conditional, but the standard
1213           // seems to imply that it could. File a bug!
1214           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
1215           (cond->isValueDependent() ||
1216            (lhs && lhs->isValueDependent()) ||
1217            (rhs && rhs->isValueDependent()))) {
1218    SubExprs[COND] = cond;
1219    SubExprs[LHS] = lhs;
1220    SubExprs[RHS] = rhs;
1221  }
1222
1223  // getCond - Return the expression representing the condition for
1224  //  the ?: operator.
1225  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1226
1227  // getTrueExpr - Return the subexpression representing the value of the ?:
1228  //  expression if the condition evaluates to true.  In most cases this value
1229  //  will be the same as getLHS() except a GCC extension allows the left
1230  //  subexpression to be omitted, and instead of the condition be returned.
1231  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1232  //  is only evaluated once.
1233  Expr *getTrueExpr() const {
1234    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1235  }
1236
1237  // getTrueExpr - Return the subexpression representing the value of the ?:
1238  // expression if the condition evaluates to false. This is the same as getRHS.
1239  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1240
1241  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1242  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1243
1244  virtual SourceRange getSourceRange() const {
1245    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1246  }
1247  static bool classof(const Stmt *T) {
1248    return T->getStmtClass() == ConditionalOperatorClass;
1249  }
1250  static bool classof(const ConditionalOperator *) { return true; }
1251
1252  // Iterators
1253  virtual child_iterator child_begin();
1254  virtual child_iterator child_end();
1255
1256  virtual void EmitImpl(llvm::Serializer& S) const;
1257  static ConditionalOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1258};
1259
1260/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1261class AddrLabelExpr : public Expr {
1262  SourceLocation AmpAmpLoc, LabelLoc;
1263  LabelStmt *Label;
1264public:
1265  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1266                QualType t)
1267    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1268
1269  virtual SourceRange getSourceRange() const {
1270    return SourceRange(AmpAmpLoc, LabelLoc);
1271  }
1272
1273  LabelStmt *getLabel() const { return Label; }
1274
1275  static bool classof(const Stmt *T) {
1276    return T->getStmtClass() == AddrLabelExprClass;
1277  }
1278  static bool classof(const AddrLabelExpr *) { return true; }
1279
1280  // Iterators
1281  virtual child_iterator child_begin();
1282  virtual child_iterator child_end();
1283
1284  virtual void EmitImpl(llvm::Serializer& S) const;
1285  static AddrLabelExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1286};
1287
1288/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1289/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1290/// takes the value of the last subexpression.
1291class StmtExpr : public Expr {
1292  Stmt *SubStmt;
1293  SourceLocation LParenLoc, RParenLoc;
1294public:
1295  StmtExpr(CompoundStmt *substmt, QualType T,
1296           SourceLocation lp, SourceLocation rp) :
1297    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1298
1299  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1300  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1301
1302  virtual SourceRange getSourceRange() const {
1303    return SourceRange(LParenLoc, RParenLoc);
1304  }
1305
1306  static bool classof(const Stmt *T) {
1307    return T->getStmtClass() == StmtExprClass;
1308  }
1309  static bool classof(const StmtExpr *) { return true; }
1310
1311  // Iterators
1312  virtual child_iterator child_begin();
1313  virtual child_iterator child_end();
1314
1315  virtual void EmitImpl(llvm::Serializer& S) const;
1316  static StmtExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1317};
1318
1319/// TypesCompatibleExpr - GNU builtin-in function __builtin_type_compatible_p.
1320/// This AST node represents a function that returns 1 if two *types* (not
1321/// expressions) are compatible. The result of this built-in function can be
1322/// used in integer constant expressions.
1323class TypesCompatibleExpr : public Expr {
1324  QualType Type1;
1325  QualType Type2;
1326  SourceLocation BuiltinLoc, RParenLoc;
1327public:
1328  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1329                      QualType t1, QualType t2, SourceLocation RP) :
1330    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1331    BuiltinLoc(BLoc), RParenLoc(RP) {}
1332
1333  QualType getArgType1() const { return Type1; }
1334  QualType getArgType2() const { return Type2; }
1335
1336  virtual SourceRange getSourceRange() const {
1337    return SourceRange(BuiltinLoc, RParenLoc);
1338  }
1339  static bool classof(const Stmt *T) {
1340    return T->getStmtClass() == TypesCompatibleExprClass;
1341  }
1342  static bool classof(const TypesCompatibleExpr *) { return true; }
1343
1344  // Iterators
1345  virtual child_iterator child_begin();
1346  virtual child_iterator child_end();
1347
1348  virtual void EmitImpl(llvm::Serializer& S) const;
1349  static TypesCompatibleExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1350};
1351
1352/// ShuffleVectorExpr - clang-specific builtin-in function
1353/// __builtin_shufflevector.
1354/// This AST node represents a operator that does a constant
1355/// shuffle, similar to LLVM's shufflevector instruction. It takes
1356/// two vectors and a variable number of constant indices,
1357/// and returns the appropriately shuffled vector.
1358class ShuffleVectorExpr : public Expr {
1359  SourceLocation BuiltinLoc, RParenLoc;
1360
1361  // SubExprs - the list of values passed to the __builtin_shufflevector
1362  // function. The first two are vectors, and the rest are constant
1363  // indices.  The number of values in this list is always
1364  // 2+the number of indices in the vector type.
1365  Stmt **SubExprs;
1366  unsigned NumExprs;
1367
1368public:
1369  ShuffleVectorExpr(Expr **args, unsigned nexpr,
1370                    QualType Type, SourceLocation BLoc,
1371                    SourceLocation RP) :
1372    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1373    RParenLoc(RP), NumExprs(nexpr) {
1374
1375    SubExprs = new Stmt*[nexpr];
1376    for (unsigned i = 0; i < nexpr; i++)
1377      SubExprs[i] = args[i];
1378  }
1379
1380  virtual SourceRange getSourceRange() const {
1381    return SourceRange(BuiltinLoc, RParenLoc);
1382  }
1383  static bool classof(const Stmt *T) {
1384    return T->getStmtClass() == ShuffleVectorExprClass;
1385  }
1386  static bool classof(const ShuffleVectorExpr *) { return true; }
1387
1388  ~ShuffleVectorExpr() {
1389    delete [] SubExprs;
1390  }
1391
1392  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1393  /// constant expression, the actual arguments passed in, and the function
1394  /// pointers.
1395  unsigned getNumSubExprs() const { return NumExprs; }
1396
1397  /// getExpr - Return the Expr at the specified index.
1398  Expr *getExpr(unsigned Index) {
1399    assert((Index < NumExprs) && "Arg access out of range!");
1400    return cast<Expr>(SubExprs[Index]);
1401  }
1402  const Expr *getExpr(unsigned Index) const {
1403    assert((Index < NumExprs) && "Arg access out of range!");
1404    return cast<Expr>(SubExprs[Index]);
1405  }
1406
1407  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1408    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1409    return getExpr(N+2)->getIntegerConstantExprValue(Ctx).getZExtValue();
1410  }
1411
1412  // Iterators
1413  virtual child_iterator child_begin();
1414  virtual child_iterator child_end();
1415
1416  virtual void EmitImpl(llvm::Serializer& S) const;
1417  static ShuffleVectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1418};
1419
1420/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1421/// This AST node is similar to the conditional operator (?:) in C, with
1422/// the following exceptions:
1423/// - the test expression must be a constant expression.
1424/// - the expression returned has it's type unaltered by promotion rules.
1425/// - does not evaluate the expression that was not chosen.
1426class ChooseExpr : public Expr {
1427  enum { COND, LHS, RHS, END_EXPR };
1428  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1429  SourceLocation BuiltinLoc, RParenLoc;
1430public:
1431  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1432             SourceLocation RP)
1433    : Expr(ChooseExprClass, t),
1434      BuiltinLoc(BLoc), RParenLoc(RP) {
1435      SubExprs[COND] = cond;
1436      SubExprs[LHS] = lhs;
1437      SubExprs[RHS] = rhs;
1438    }
1439
1440  /// isConditionTrue - Return true if the condition is true.  This is always
1441  /// statically knowable for a well-formed choosexpr.
1442  bool isConditionTrue(ASTContext &C) const;
1443
1444  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1445  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1446  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1447
1448  virtual SourceRange getSourceRange() const {
1449    return SourceRange(BuiltinLoc, RParenLoc);
1450  }
1451  static bool classof(const Stmt *T) {
1452    return T->getStmtClass() == ChooseExprClass;
1453  }
1454  static bool classof(const ChooseExpr *) { return true; }
1455
1456  // Iterators
1457  virtual child_iterator child_begin();
1458  virtual child_iterator child_end();
1459
1460  virtual void EmitImpl(llvm::Serializer& S) const;
1461  static ChooseExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1462};
1463
1464/// GNUNullExpr - Implements the GNU __null extension, which is a name
1465/// for a null pointer constant that has integral type (e.g., int or
1466/// long) and is the same size and alignment as a pointer. The __null
1467/// extension is typically only used by system headers, which define
1468/// NULL as __null in C++ rather than using 0 (which is an integer
1469/// that may not match the size of a pointer).
1470class GNUNullExpr : public Expr {
1471  /// TokenLoc - The location of the __null keyword.
1472  SourceLocation TokenLoc;
1473
1474public:
1475  GNUNullExpr(QualType Ty, SourceLocation Loc)
1476    : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { }
1477
1478  /// getTokenLocation - The location of the __null token.
1479  SourceLocation getTokenLocation() const { return TokenLoc; }
1480
1481  virtual SourceRange getSourceRange() const {
1482    return SourceRange(TokenLoc);
1483  }
1484  static bool classof(const Stmt *T) {
1485    return T->getStmtClass() == GNUNullExprClass;
1486  }
1487  static bool classof(const GNUNullExpr *) { return true; }
1488
1489  // Iterators
1490  virtual child_iterator child_begin();
1491  virtual child_iterator child_end();
1492
1493  virtual void EmitImpl(llvm::Serializer& S) const;
1494  static GNUNullExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1495};
1496
1497/// OverloadExpr - Clang builtin function __builtin_overload.
1498/// This AST node provides a way to overload functions in C.
1499///
1500/// The first argument is required to be a constant expression, for the number
1501/// of arguments passed to each candidate function.
1502///
1503/// The next N arguments, where N is the value of the constant expression,
1504/// are the values to be passed as arguments.
1505///
1506/// The rest of the arguments are values of pointer to function type, which
1507/// are the candidate functions for overloading.
1508///
1509/// The result is a equivalent to a CallExpr taking N arguments to the
1510/// candidate function whose parameter types match the types of the N arguments.
1511///
1512/// example: float Z = __builtin_overload(2, X, Y, modf, mod, modl);
1513/// If X and Y are long doubles, Z will assigned the result of modl(X, Y);
1514/// If X and Y are floats, Z will be assigned the result of modf(X, Y);
1515class OverloadExpr : public Expr {
1516  // SubExprs - the list of values passed to the __builtin_overload function.
1517  // SubExpr[0] is a constant expression
1518  // SubExpr[1-N] are the parameters to pass to the matching function call
1519  // SubExpr[N-...] are the candidate functions, of type pointer to function.
1520  Stmt **SubExprs;
1521
1522  // NumExprs - the size of the SubExprs array
1523  unsigned NumExprs;
1524
1525  // The index of the matching candidate function
1526  unsigned FnIndex;
1527
1528  SourceLocation BuiltinLoc;
1529  SourceLocation RParenLoc;
1530public:
1531  OverloadExpr(Expr **args, unsigned nexprs, unsigned idx, QualType t,
1532               SourceLocation bloc, SourceLocation rploc)
1533    : Expr(OverloadExprClass, t), NumExprs(nexprs), FnIndex(idx),
1534      BuiltinLoc(bloc), RParenLoc(rploc) {
1535    SubExprs = new Stmt*[nexprs];
1536    for (unsigned i = 0; i != nexprs; ++i)
1537      SubExprs[i] = args[i];
1538  }
1539  ~OverloadExpr() {
1540    delete [] SubExprs;
1541  }
1542
1543  /// arg_begin - Return a pointer to the list of arguments that will be passed
1544  /// to the matching candidate function, skipping over the initial constant
1545  /// expression.
1546  typedef ConstExprIterator const_arg_iterator;
1547  const_arg_iterator arg_begin() const { return &SubExprs[0]+1; }
1548  const_arg_iterator arg_end(ASTContext& Ctx) const {
1549    return &SubExprs[0]+1+getNumArgs(Ctx);
1550  }
1551
1552  /// getNumArgs - Return the number of arguments to pass to the candidate
1553  /// functions.
1554  unsigned getNumArgs(ASTContext &Ctx) const {
1555    return getExpr(0)->getIntegerConstantExprValue(Ctx).getZExtValue();
1556  }
1557
1558  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1559  /// constant expression, the actual arguments passed in, and the function
1560  /// pointers.
1561  unsigned getNumSubExprs() const { return NumExprs; }
1562
1563  /// getExpr - Return the Expr at the specified index.
1564  Expr *getExpr(unsigned Index) const {
1565    assert((Index < NumExprs) && "Arg access out of range!");
1566    return cast<Expr>(SubExprs[Index]);
1567  }
1568
1569  /// getFn - Return the matching candidate function for this OverloadExpr.
1570  Expr *getFn() const { return cast<Expr>(SubExprs[FnIndex]); }
1571
1572  virtual SourceRange getSourceRange() const {
1573    return SourceRange(BuiltinLoc, RParenLoc);
1574  }
1575  static bool classof(const Stmt *T) {
1576    return T->getStmtClass() == OverloadExprClass;
1577  }
1578  static bool classof(const OverloadExpr *) { return true; }
1579
1580  // Iterators
1581  virtual child_iterator child_begin();
1582  virtual child_iterator child_end();
1583
1584  virtual void EmitImpl(llvm::Serializer& S) const;
1585  static OverloadExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1586};
1587
1588/// VAArgExpr, used for the builtin function __builtin_va_start.
1589class VAArgExpr : public Expr {
1590  Stmt *Val;
1591  SourceLocation BuiltinLoc, RParenLoc;
1592public:
1593  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1594    : Expr(VAArgExprClass, t),
1595      Val(e),
1596      BuiltinLoc(BLoc),
1597      RParenLoc(RPLoc) { }
1598
1599  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1600  Expr *getSubExpr() { return cast<Expr>(Val); }
1601  virtual SourceRange getSourceRange() const {
1602    return SourceRange(BuiltinLoc, RParenLoc);
1603  }
1604  static bool classof(const Stmt *T) {
1605    return T->getStmtClass() == VAArgExprClass;
1606  }
1607  static bool classof(const VAArgExpr *) { return true; }
1608
1609  // Iterators
1610  virtual child_iterator child_begin();
1611  virtual child_iterator child_end();
1612
1613  virtual void EmitImpl(llvm::Serializer& S) const;
1614  static VAArgExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1615};
1616
1617/// InitListExpr - used for struct and array initializers, such as:
1618///    struct foo x = { 1, { 2, 3 } };
1619///
1620/// Because C is somewhat loose with braces, the AST does not necessarily
1621/// directly model the C source.  Instead, the semantic analyzer aims to make
1622/// the InitListExprs match up with the type of the decl being initialized.  We
1623/// have the following exceptions:
1624///
1625///  1. Elements at the end of the list may be dropped from the initializer.
1626///     These elements are defined to be initialized to zero.  For example:
1627///         int x[20] = { 1 };
1628///  2. Initializers may have excess initializers which are to be ignored by the
1629///     compiler.  For example:
1630///         int x[1] = { 1, 2 };
1631///  3. Redundant InitListExprs may be present around scalar elements.  These
1632///     always have a single element whose type is the same as the InitListExpr.
1633///     this can only happen for Type::isScalarType() types.
1634///         int x = { 1 };  int y[2] = { {1}, {2} };
1635///
1636class InitListExpr : public Expr {
1637  std::vector<Stmt *> InitExprs;
1638  SourceLocation LBraceLoc, RBraceLoc;
1639
1640  /// HadDesignators - Return true if there were any designators in this
1641  /// init list expr.  FIXME: this should be replaced by storing the designators
1642  /// somehow and updating codegen.
1643  bool HadDesignators;
1644public:
1645  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
1646               SourceLocation rbraceloc, bool HadDesignators);
1647
1648  unsigned getNumInits() const { return InitExprs.size(); }
1649  bool hadDesignators() const { return HadDesignators; }
1650
1651  const Expr* getInit(unsigned Init) const {
1652    assert(Init < getNumInits() && "Initializer access out of range!");
1653    return cast<Expr>(InitExprs[Init]);
1654  }
1655
1656  Expr* getInit(unsigned Init) {
1657    assert(Init < getNumInits() && "Initializer access out of range!");
1658    return cast<Expr>(InitExprs[Init]);
1659  }
1660
1661  void setInit(unsigned Init, Expr *expr) {
1662    assert(Init < getNumInits() && "Initializer access out of range!");
1663    InitExprs[Init] = expr;
1664  }
1665
1666  // Dynamic removal/addition (for constructing implicit InitExpr's).
1667  void removeInit(unsigned Init) {
1668    InitExprs.erase(InitExprs.begin()+Init);
1669  }
1670  void addInit(unsigned Init, Expr *expr) {
1671    InitExprs.insert(InitExprs.begin()+Init, expr);
1672  }
1673
1674  // Explicit InitListExpr's originate from source code (and have valid source
1675  // locations). Implicit InitListExpr's are created by the semantic analyzer.
1676  bool isExplicit() {
1677    return LBraceLoc.isValid() && RBraceLoc.isValid();
1678  }
1679
1680  virtual SourceRange getSourceRange() const {
1681    return SourceRange(LBraceLoc, RBraceLoc);
1682  }
1683  static bool classof(const Stmt *T) {
1684    return T->getStmtClass() == InitListExprClass;
1685  }
1686  static bool classof(const InitListExpr *) { return true; }
1687
1688  // Iterators
1689  virtual child_iterator child_begin();
1690  virtual child_iterator child_end();
1691
1692  typedef std::vector<Stmt *>::iterator iterator;
1693  typedef std::vector<Stmt *>::reverse_iterator reverse_iterator;
1694
1695  iterator begin() { return InitExprs.begin(); }
1696  iterator end() { return InitExprs.end(); }
1697  reverse_iterator rbegin() { return InitExprs.rbegin(); }
1698  reverse_iterator rend() { return InitExprs.rend(); }
1699
1700  // Serailization.
1701  virtual void EmitImpl(llvm::Serializer& S) const;
1702  static InitListExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1703
1704private:
1705  // Used by serializer.
1706  InitListExpr() : Expr(InitListExprClass, QualType()) {}
1707};
1708
1709/// @brief Represents a C99 designated initializer expression.
1710///
1711/// A designated initializer expression (C99 6.7.8) contains one or
1712/// more designators (which can be field designators, array
1713/// designators, or GNU array-range designators) followed by an
1714/// expression that initializes the field or element(s) that the
1715/// designators refer to. For example, given:
1716///
1717/// @code
1718/// struct point {
1719///   double x;
1720///   double y;
1721/// };
1722/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1723/// @endcode
1724///
1725/// The InitListExpr contains three DesignatedInitExprs, the first of
1726/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
1727/// designators, one array designator for @c [2] followed by one field
1728/// designator for @c .y. The initalization expression will be 1.0.
1729class DesignatedInitExpr : public Expr {
1730  /// The location of the '=' or ':' prior to the actual initializer
1731  /// expression.
1732  SourceLocation EqualOrColonLoc;
1733
1734  /// Whether this designated initializer used the GNU deprecated ':'
1735  /// syntax rather than the C99 '=' syntax.
1736  bool UsesColonSyntax : 1;
1737
1738  /// The number of designators in this initializer expression.
1739  unsigned NumDesignators : 15;
1740
1741  /// The number of subexpressions of this initializer expression,
1742  /// which contains both the initializer and any additional
1743  /// expressions used by array and array-range designators.
1744  unsigned NumSubExprs : 16;
1745
1746  DesignatedInitExpr(QualType Ty, unsigned NumDesignators,
1747                     SourceLocation EqualOrColonLoc, bool UsesColonSyntax,
1748                     unsigned NumSubExprs)
1749    : Expr(DesignatedInitExprClass, Ty),
1750      EqualOrColonLoc(EqualOrColonLoc), UsesColonSyntax(UsesColonSyntax),
1751      NumDesignators(NumDesignators), NumSubExprs(NumSubExprs) { }
1752
1753public:
1754  /// A field designator, e.g., ".x".
1755  struct FieldDesignator {
1756    /// Refers to the field that is being initialized. The low bit
1757    /// of this field determines whether this is actually a pointer
1758    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
1759    /// initially constructed, a field designator will store an
1760    /// IdentifierInfo*. After semantic analysis has resolved that
1761    /// name, the field designator will instead store a FieldDecl*.
1762    uintptr_t NameOrField;
1763
1764    /// The location of the '.' in the designated initializer.
1765    unsigned DotLoc;
1766
1767    /// The location of the field name in the designated initializer.
1768    unsigned FieldLoc;
1769  };
1770
1771  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
1772  struct ArrayOrRangeDesignator {
1773    /// Location of the first index expression within the designated
1774    /// initializer expression's list of subexpressions.
1775    unsigned Index;
1776    /// The location of the '[' starting the array range designator.
1777    unsigned LBracketLoc;
1778    /// The location of the ellipsis separating the start and end
1779    /// indices. Only valid for GNU array-range designators.
1780    unsigned EllipsisLoc;
1781    /// The location of the ']' terminating the array range designator.
1782    unsigned RBracketLoc;
1783  };
1784
1785  /// @brief Represents a single C99 designator.
1786  ///
1787  /// @todo This class is infuriatingly similar to clang::Designator,
1788  /// but minor differences (storing indices vs. storing pointers)
1789  /// keep us from reusing it. Try harder, later, to rectify these
1790  /// differences.
1791  class Designator {
1792    /// @brief The kind of designator this describes.
1793    enum {
1794      FieldDesignator,
1795      ArrayDesignator,
1796      ArrayRangeDesignator
1797    } Kind;
1798
1799    union {
1800      /// A field designator, e.g., ".x".
1801      struct FieldDesignator Field;
1802      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
1803      struct ArrayOrRangeDesignator ArrayOrRange;
1804    };
1805    friend class DesignatedInitExpr;
1806
1807  public:
1808    /// @brief Initializes a field designator.
1809    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
1810               SourceLocation FieldLoc)
1811      : Kind(FieldDesignator) {
1812      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
1813      Field.DotLoc = DotLoc.getRawEncoding();
1814      Field.FieldLoc = FieldLoc.getRawEncoding();
1815    }
1816
1817    /// @brief Initializes an array designator.
1818    Designator(unsigned Index, SourceLocation LBracketLoc,
1819               SourceLocation RBracketLoc)
1820      : Kind(ArrayDesignator) {
1821      ArrayOrRange.Index = Index;
1822      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
1823      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
1824      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
1825    }
1826
1827    /// @brief Initializes a GNU array-range designator.
1828    Designator(unsigned Index, SourceLocation LBracketLoc,
1829               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
1830      : Kind(ArrayRangeDesignator) {
1831      ArrayOrRange.Index = Index;
1832      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
1833      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
1834      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
1835    }
1836
1837    bool isFieldDesignator() const { return Kind == FieldDesignator; }
1838    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
1839    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
1840
1841    IdentifierInfo * getFieldName();
1842
1843    FieldDecl *getField() {
1844      assert(Kind == FieldDesignator && "Only valid on a field designator");
1845      if (Field.NameOrField & 0x01)
1846        return 0;
1847      else
1848        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
1849    }
1850
1851    void setField(FieldDecl *FD) {
1852      assert(Kind == FieldDesignator && "Only valid on a field designator");
1853      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
1854    }
1855
1856    SourceLocation getDotLoc() const {
1857      assert(Kind == FieldDesignator && "Only valid on a field designator");
1858      return SourceLocation::getFromRawEncoding(Field.DotLoc);
1859    }
1860
1861    SourceLocation getFieldLoc() const {
1862      assert(Kind == FieldDesignator && "Only valid on a field designator");
1863      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
1864    }
1865
1866    SourceLocation getLBracketLoc() const {
1867      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
1868             "Only valid on an array or array-range designator");
1869      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
1870    }
1871
1872    SourceLocation getRBracketLoc() const {
1873      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
1874             "Only valid on an array or array-range designator");
1875      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
1876    }
1877
1878    SourceLocation getEllipsisLoc() const {
1879      assert(Kind == ArrayRangeDesignator &&
1880             "Only valid on an array-range designator");
1881      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
1882    }
1883  };
1884
1885  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
1886                                    unsigned NumDesignators,
1887                                    Expr **IndexExprs, unsigned NumIndexExprs,
1888                                    SourceLocation EqualOrColonLoc,
1889                                    bool UsesColonSyntax, Expr *Init);
1890
1891  /// @brief Returns the number of designators in this initializer.
1892  unsigned size() const { return NumDesignators; }
1893
1894  // Iterator access to the designators.
1895  typedef Designator* designators_iterator;
1896  designators_iterator designators_begin();
1897  designators_iterator designators_end();
1898
1899  Expr *getArrayIndex(const Designator& D);
1900  Expr *getArrayRangeStart(const Designator& D);
1901  Expr *getArrayRangeEnd(const Designator& D);
1902
1903  /// @brief Retrieve the location of the '=' that precedes the
1904  /// initializer value itself, if present.
1905  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
1906
1907  /// @brief Determines whether this designated initializer used the
1908  /// GNU 'fieldname:' syntax or the C99 '=' syntax.
1909  bool usesColonSyntax() const { return UsesColonSyntax; }
1910
1911  /// @brief Retrieve the initializer value.
1912  Expr *getInit() const {
1913    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
1914  }
1915
1916  void setInit(Expr *init) {
1917    *child_begin() = init;
1918  }
1919
1920  virtual SourceRange getSourceRange() const;
1921
1922  static bool classof(const Stmt *T) {
1923    return T->getStmtClass() == DesignatedInitExprClass;
1924  }
1925  static bool classof(const DesignatedInitExpr *) { return true; }
1926
1927  // Iterators
1928  virtual child_iterator child_begin();
1929  virtual child_iterator child_end();
1930};
1931
1932//===----------------------------------------------------------------------===//
1933// Clang Extensions
1934//===----------------------------------------------------------------------===//
1935
1936
1937/// ExtVectorElementExpr - This represents access to specific elements of a
1938/// vector, and may occur on the left hand side or right hand side.  For example
1939/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
1940///
1941class ExtVectorElementExpr : public Expr {
1942  Stmt *Base;
1943  IdentifierInfo &Accessor;
1944  SourceLocation AccessorLoc;
1945public:
1946  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
1947                       SourceLocation loc)
1948    : Expr(ExtVectorElementExprClass, ty),
1949      Base(base), Accessor(accessor), AccessorLoc(loc) {}
1950
1951  const Expr *getBase() const { return cast<Expr>(Base); }
1952  Expr *getBase() { return cast<Expr>(Base); }
1953
1954  IdentifierInfo &getAccessor() const { return Accessor; }
1955
1956  /// getNumElements - Get the number of components being selected.
1957  unsigned getNumElements() const;
1958
1959  /// containsDuplicateElements - Return true if any element access is
1960  /// repeated.
1961  bool containsDuplicateElements() const;
1962
1963  /// getEncodedElementAccess - Encode the elements accessed into an llvm
1964  /// aggregate Constant of ConstantInt(s).
1965  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
1966
1967  virtual SourceRange getSourceRange() const {
1968    return SourceRange(getBase()->getLocStart(), AccessorLoc);
1969  }
1970
1971  static bool classof(const Stmt *T) {
1972    return T->getStmtClass() == ExtVectorElementExprClass;
1973  }
1974  static bool classof(const ExtVectorElementExpr *) { return true; }
1975
1976  // Iterators
1977  virtual child_iterator child_begin();
1978  virtual child_iterator child_end();
1979
1980  virtual void EmitImpl(llvm::Serializer& S) const;
1981  static ExtVectorElementExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1982};
1983
1984
1985/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
1986/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1987class BlockExpr : public Expr {
1988protected:
1989  BlockDecl *TheBlock;
1990public:
1991  BlockExpr(BlockDecl *BD, QualType ty) : Expr(BlockExprClass, ty),
1992            TheBlock(BD) {}
1993
1994  BlockDecl *getBlockDecl() { return TheBlock; }
1995
1996  // Convenience functions for probing the underlying BlockDecl.
1997  SourceLocation getCaretLocation() const;
1998  const Stmt *getBody() const;
1999  Stmt *getBody();
2000
2001  virtual SourceRange getSourceRange() const {
2002    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
2003  }
2004
2005  /// getFunctionType - Return the underlying function type for this block.
2006  const FunctionType *getFunctionType() const;
2007
2008  static bool classof(const Stmt *T) {
2009    return T->getStmtClass() == BlockExprClass;
2010  }
2011  static bool classof(const BlockExpr *) { return true; }
2012
2013  // Iterators
2014  virtual child_iterator child_begin();
2015  virtual child_iterator child_end();
2016
2017  virtual void EmitImpl(llvm::Serializer& S) const;
2018  static BlockExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
2019};
2020
2021/// BlockDeclRefExpr - A reference to a declared variable, function,
2022/// enum, etc.
2023class BlockDeclRefExpr : public Expr {
2024  ValueDecl *D;
2025  SourceLocation Loc;
2026  bool IsByRef;
2027public:
2028  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef) :
2029       Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef) {}
2030
2031  ValueDecl *getDecl() { return D; }
2032  const ValueDecl *getDecl() const { return D; }
2033  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
2034
2035  bool isByRef() const { return IsByRef; }
2036
2037  static bool classof(const Stmt *T) {
2038    return T->getStmtClass() == BlockDeclRefExprClass;
2039  }
2040  static bool classof(const BlockDeclRefExpr *) { return true; }
2041
2042  // Iterators
2043  virtual child_iterator child_begin();
2044  virtual child_iterator child_end();
2045
2046  virtual void EmitImpl(llvm::Serializer& S) const;
2047  static BlockDeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
2048};
2049
2050}  // end namespace clang
2051
2052#endif
2053