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