Expr.h revision 1a51b4a11b7db25cac2134249711ecaaf9d1c0a8
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() { delete [] SubExprs; }
780
781  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
782  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
783  void setCallee(Expr *F) { SubExprs[FN] = F; }
784
785  /// getNumArgs - Return the number of actual arguments to this call.
786  ///
787  unsigned getNumArgs() const { return NumArgs; }
788
789  /// getArg - Return the specified argument.
790  Expr *getArg(unsigned Arg) {
791    assert(Arg < NumArgs && "Arg access out of range!");
792    return cast<Expr>(SubExprs[Arg+ARGS_START]);
793  }
794  const Expr *getArg(unsigned Arg) const {
795    assert(Arg < NumArgs && "Arg access out of range!");
796    return cast<Expr>(SubExprs[Arg+ARGS_START]);
797  }
798  /// setArg - Set the specified argument.
799  void setArg(unsigned Arg, Expr *ArgExpr) {
800    assert(Arg < NumArgs && "Arg access out of range!");
801    SubExprs[Arg+ARGS_START] = ArgExpr;
802  }
803
804  /// setNumArgs - This changes the number of arguments present in this call.
805  /// Any orphaned expressions are deleted by this, and any new operands are set
806  /// to null.
807  void setNumArgs(ASTContext& C, unsigned NumArgs);
808
809  typedef ExprIterator arg_iterator;
810  typedef ConstExprIterator const_arg_iterator;
811
812  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
813  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
814  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
815  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
816
817  /// getNumCommas - Return the number of commas that must have been present in
818  /// this function call.
819  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
820
821  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
822  /// not, return 0.
823  unsigned isBuiltinCall() const;
824
825  SourceLocation getRParenLoc() const { return RParenLoc; }
826
827  virtual SourceRange getSourceRange() const {
828    return SourceRange(getCallee()->getLocStart(), RParenLoc);
829  }
830
831  static bool classof(const Stmt *T) {
832    return T->getStmtClass() == CallExprClass ||
833           T->getStmtClass() == CXXOperatorCallExprClass ||
834           T->getStmtClass() == CXXMemberCallExprClass;
835  }
836  static bool classof(const CallExpr *) { return true; }
837  static bool classof(const CXXOperatorCallExpr *) { return true; }
838  static bool classof(const CXXMemberCallExpr *) { return true; }
839
840  // Iterators
841  virtual child_iterator child_begin();
842  virtual child_iterator child_end();
843
844  virtual void EmitImpl(llvm::Serializer& S) const;
845  static CallExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C,
846                              StmtClass SC);
847};
848
849/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.
850///
851class MemberExpr : public Expr {
852  Stmt *Base;
853  NamedDecl *MemberDecl;
854  SourceLocation MemberLoc;
855  bool IsArrow;      // True if this is "X->F", false if this is "X.F".
856public:
857  MemberExpr(Expr *base, bool isarrow, NamedDecl *memberdecl, SourceLocation l,
858             QualType ty)
859    : Expr(MemberExprClass, ty),
860      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {}
861
862  void setBase(Expr *E) { Base = E; }
863  Expr *getBase() const { return cast<Expr>(Base); }
864  NamedDecl *getMemberDecl() const { return MemberDecl; }
865  void setMemberDecl(NamedDecl *D) { MemberDecl = D; }
866  bool isArrow() const { return IsArrow; }
867
868  virtual SourceRange getSourceRange() const {
869    return SourceRange(getBase()->getLocStart(), MemberLoc);
870  }
871
872  virtual SourceLocation getExprLoc() const { return MemberLoc; }
873
874  static bool classof(const Stmt *T) {
875    return T->getStmtClass() == MemberExprClass;
876  }
877  static bool classof(const MemberExpr *) { return true; }
878
879  // Iterators
880  virtual child_iterator child_begin();
881  virtual child_iterator child_end();
882
883  virtual void EmitImpl(llvm::Serializer& S) const;
884  static MemberExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
885};
886
887/// CompoundLiteralExpr - [C99 6.5.2.5]
888///
889class CompoundLiteralExpr : public Expr {
890  /// LParenLoc - If non-null, this is the location of the left paren in a
891  /// compound literal like "(int){4}".  This can be null if this is a
892  /// synthesized compound expression.
893  SourceLocation LParenLoc;
894  Stmt *Init;
895  bool FileScope;
896public:
897  CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init,
898                      bool fileScope)
899    : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init),
900      FileScope(fileScope) {}
901
902  const Expr *getInitializer() const { return cast<Expr>(Init); }
903  Expr *getInitializer() { return cast<Expr>(Init); }
904
905  bool isFileScope() const { return FileScope; }
906
907  SourceLocation getLParenLoc() const { return LParenLoc; }
908
909  virtual SourceRange getSourceRange() const {
910    // FIXME: Init should never be null.
911    if (!Init)
912      return SourceRange();
913    if (LParenLoc.isInvalid())
914      return Init->getSourceRange();
915    return SourceRange(LParenLoc, Init->getLocEnd());
916  }
917
918  static bool classof(const Stmt *T) {
919    return T->getStmtClass() == CompoundLiteralExprClass;
920  }
921  static bool classof(const CompoundLiteralExpr *) { return true; }
922
923  // Iterators
924  virtual child_iterator child_begin();
925  virtual child_iterator child_end();
926
927  virtual void EmitImpl(llvm::Serializer& S) const;
928  static CompoundLiteralExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
929};
930
931/// CastExpr - Base class for type casts, including both implicit
932/// casts (ImplicitCastExpr) and explicit casts that have some
933/// representation in the source code (ExplicitCastExpr's derived
934/// classes).
935class CastExpr : public Expr {
936  Stmt *Op;
937protected:
938  CastExpr(StmtClass SC, QualType ty, Expr *op) :
939    Expr(SC, ty,
940         // Cast expressions are type-dependent if the type is
941         // dependent (C++ [temp.dep.expr]p3).
942         ty->isDependentType(),
943         // Cast expressions are value-dependent if the type is
944         // dependent or if the subexpression is value-dependent.
945         ty->isDependentType() || (op && op->isValueDependent())),
946    Op(op) {}
947
948public:
949  Expr *getSubExpr() { return cast<Expr>(Op); }
950  const Expr *getSubExpr() const { return cast<Expr>(Op); }
951
952  static bool classof(const Stmt *T) {
953    StmtClass SC = T->getStmtClass();
954    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
955      return true;
956
957    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
958      return true;
959
960    return false;
961  }
962  static bool classof(const CastExpr *) { return true; }
963
964  // Iterators
965  virtual child_iterator child_begin();
966  virtual child_iterator child_end();
967};
968
969/// ImplicitCastExpr - Allows us to explicitly represent implicit type
970/// conversions, which have no direct representation in the original
971/// source code. For example: converting T[]->T*, void f()->void
972/// (*f)(), float->double, short->int, etc.
973///
974/// In C, implicit casts always produce rvalues. However, in C++, an
975/// implicit cast whose result is being bound to a reference will be
976/// an lvalue. For example:
977///
978/// @code
979/// class Base { };
980/// class Derived : public Base { };
981/// void f(Derived d) {
982///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
983/// }
984/// @endcode
985class ImplicitCastExpr : public CastExpr {
986  /// LvalueCast - Whether this cast produces an lvalue.
987  bool LvalueCast;
988
989public:
990  ImplicitCastExpr(QualType ty, Expr *op, bool Lvalue) :
991    CastExpr(ImplicitCastExprClass, ty, op), LvalueCast(Lvalue) { }
992
993  virtual SourceRange getSourceRange() const {
994    return getSubExpr()->getSourceRange();
995  }
996
997  /// isLvalueCast - Whether this cast produces an lvalue.
998  bool isLvalueCast() const { return LvalueCast; }
999
1000  /// setLvalueCast - Set whether this cast produces an lvalue.
1001  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1002
1003  static bool classof(const Stmt *T) {
1004    return T->getStmtClass() == ImplicitCastExprClass;
1005  }
1006  static bool classof(const ImplicitCastExpr *) { return true; }
1007
1008  virtual void EmitImpl(llvm::Serializer& S) const;
1009  static ImplicitCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1010};
1011
1012/// ExplicitCastExpr - An explicit cast written in the source
1013/// code.
1014///
1015/// This class is effectively an abstract class, because it provides
1016/// the basic representation of an explicitly-written cast without
1017/// specifying which kind of cast (C cast, functional cast, static
1018/// cast, etc.) was written; specific derived classes represent the
1019/// particular style of cast and its location information.
1020///
1021/// Unlike implicit casts, explicit cast nodes have two different
1022/// types: the type that was written into the source code, and the
1023/// actual type of the expression as determined by semantic
1024/// analysis. These types may differ slightly. For example, in C++ one
1025/// can cast to a reference type, which indicates that the resulting
1026/// expression will be an lvalue. The reference type, however, will
1027/// not be used as the type of the expression.
1028class ExplicitCastExpr : public CastExpr {
1029  /// TypeAsWritten - The type that this expression is casting to, as
1030  /// written in the source code.
1031  QualType TypeAsWritten;
1032
1033protected:
1034  ExplicitCastExpr(StmtClass SC, QualType exprTy, Expr *op, QualType writtenTy)
1035    : CastExpr(SC, exprTy, op), TypeAsWritten(writtenTy) {}
1036
1037public:
1038  /// getTypeAsWritten - Returns the type that this expression is
1039  /// casting to, as written in the source code.
1040  QualType getTypeAsWritten() const { return TypeAsWritten; }
1041
1042  static bool classof(const Stmt *T) {
1043    StmtClass SC = T->getStmtClass();
1044    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
1045      return true;
1046    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1047      return true;
1048
1049    return false;
1050  }
1051  static bool classof(const ExplicitCastExpr *) { return true; }
1052};
1053
1054/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1055/// cast in C++ (C++ [expr.cast]), which uses the syntax
1056/// (Type)expr. For example: @c (int)f.
1057class CStyleCastExpr : public ExplicitCastExpr {
1058  SourceLocation LPLoc; // the location of the left paren
1059  SourceLocation RPLoc; // the location of the right paren
1060public:
1061  CStyleCastExpr(QualType exprTy, Expr *op, QualType writtenTy,
1062                    SourceLocation l, SourceLocation r) :
1063    ExplicitCastExpr(CStyleCastExprClass, exprTy, op, writtenTy),
1064    LPLoc(l), RPLoc(r) {}
1065
1066  SourceLocation getLParenLoc() const { return LPLoc; }
1067  SourceLocation getRParenLoc() const { return RPLoc; }
1068
1069  virtual SourceRange getSourceRange() const {
1070    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1071  }
1072  static bool classof(const Stmt *T) {
1073    return T->getStmtClass() == CStyleCastExprClass;
1074  }
1075  static bool classof(const CStyleCastExpr *) { return true; }
1076
1077  virtual void EmitImpl(llvm::Serializer& S) const;
1078  static CStyleCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1079};
1080
1081class BinaryOperator : public Expr {
1082public:
1083  enum Opcode {
1084    // Operators listed in order of precedence.
1085    // Note that additions to this should also update the StmtVisitor class.
1086    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
1087    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1088    Add, Sub,         // [C99 6.5.6] Additive operators.
1089    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1090    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1091    EQ, NE,           // [C99 6.5.9] Equality operators.
1092    And,              // [C99 6.5.10] Bitwise AND operator.
1093    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1094    Or,               // [C99 6.5.12] Bitwise OR operator.
1095    LAnd,             // [C99 6.5.13] Logical AND operator.
1096    LOr,              // [C99 6.5.14] Logical OR operator.
1097    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1098    DivAssign, RemAssign,
1099    AddAssign, SubAssign,
1100    ShlAssign, ShrAssign,
1101    AndAssign, XorAssign,
1102    OrAssign,
1103    Comma             // [C99 6.5.17] Comma operator.
1104  };
1105private:
1106  enum { LHS, RHS, END_EXPR };
1107  Stmt* SubExprs[END_EXPR];
1108  Opcode Opc;
1109  SourceLocation OpLoc;
1110public:
1111
1112  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1113                 SourceLocation opLoc)
1114    : Expr(BinaryOperatorClass, ResTy,
1115           lhs->isTypeDependent() || rhs->isTypeDependent(),
1116           lhs->isValueDependent() || rhs->isValueDependent()),
1117      Opc(opc), OpLoc(opLoc) {
1118    SubExprs[LHS] = lhs;
1119    SubExprs[RHS] = rhs;
1120    assert(!isCompoundAssignmentOp() &&
1121           "Use ArithAssignBinaryOperator for compound assignments");
1122  }
1123
1124  SourceLocation getOperatorLoc() const { return OpLoc; }
1125  Opcode getOpcode() const { return Opc; }
1126  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1127  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1128  virtual SourceRange getSourceRange() const {
1129    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1130  }
1131
1132  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1133  /// corresponds to, e.g. "<<=".
1134  static const char *getOpcodeStr(Opcode Op);
1135
1136  /// predicates to categorize the respective opcodes.
1137  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1138  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1139  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
1140  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
1141
1142  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1143  bool isRelationalOp() const { return isRelationalOp(Opc); }
1144
1145  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1146  bool isEqualityOp() const { return isEqualityOp(Opc); }
1147
1148  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1149  bool isLogicalOp() const { return isLogicalOp(Opc); }
1150
1151  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1152  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1153  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
1154
1155  static bool classof(const Stmt *S) {
1156    return S->getStmtClass() == BinaryOperatorClass ||
1157           S->getStmtClass() == CompoundAssignOperatorClass;
1158  }
1159  static bool classof(const BinaryOperator *) { return true; }
1160
1161  // Iterators
1162  virtual child_iterator child_begin();
1163  virtual child_iterator child_end();
1164
1165  virtual void EmitImpl(llvm::Serializer& S) const;
1166  static BinaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1167
1168protected:
1169  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1170                 SourceLocation oploc, bool dead)
1171    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
1172    SubExprs[LHS] = lhs;
1173    SubExprs[RHS] = rhs;
1174  }
1175};
1176
1177/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
1178/// track of the type the operation is performed in.  Due to the semantics of
1179/// these operators, the operands are promoted, the aritmetic performed, an
1180/// implicit conversion back to the result type done, then the assignment takes
1181/// place.  This captures the intermediate type which the computation is done
1182/// in.
1183class CompoundAssignOperator : public BinaryOperator {
1184  QualType ComputationType;
1185public:
1186  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1187                         QualType ResType, QualType CompType,
1188                         SourceLocation OpLoc)
1189    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1190      ComputationType(CompType) {
1191    assert(isCompoundAssignmentOp() &&
1192           "Only should be used for compound assignments");
1193  }
1194
1195  QualType getComputationType() const { return ComputationType; }
1196
1197  static bool classof(const CompoundAssignOperator *) { return true; }
1198  static bool classof(const Stmt *S) {
1199    return S->getStmtClass() == CompoundAssignOperatorClass;
1200  }
1201
1202  virtual void EmitImpl(llvm::Serializer& S) const;
1203  static CompoundAssignOperator* CreateImpl(llvm::Deserializer& D,
1204                                            ASTContext& C);
1205};
1206
1207/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1208/// GNU "missing LHS" extension is in use.
1209///
1210class ConditionalOperator : public Expr {
1211  enum { COND, LHS, RHS, END_EXPR };
1212  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1213public:
1214  ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t)
1215    : Expr(ConditionalOperatorClass, t,
1216           // FIXME: the type of the conditional operator doesn't
1217           // depend on the type of the conditional, but the standard
1218           // seems to imply that it could. File a bug!
1219           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
1220           (cond->isValueDependent() ||
1221            (lhs && lhs->isValueDependent()) ||
1222            (rhs && rhs->isValueDependent()))) {
1223    SubExprs[COND] = cond;
1224    SubExprs[LHS] = lhs;
1225    SubExprs[RHS] = rhs;
1226  }
1227
1228  // getCond - Return the expression representing the condition for
1229  //  the ?: operator.
1230  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1231
1232  // getTrueExpr - Return the subexpression representing the value of the ?:
1233  //  expression if the condition evaluates to true.  In most cases this value
1234  //  will be the same as getLHS() except a GCC extension allows the left
1235  //  subexpression to be omitted, and instead of the condition be returned.
1236  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1237  //  is only evaluated once.
1238  Expr *getTrueExpr() const {
1239    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1240  }
1241
1242  // getTrueExpr - Return the subexpression representing the value of the ?:
1243  // expression if the condition evaluates to false. This is the same as getRHS.
1244  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1245
1246  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1247  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1248
1249  virtual SourceRange getSourceRange() const {
1250    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1251  }
1252  static bool classof(const Stmt *T) {
1253    return T->getStmtClass() == ConditionalOperatorClass;
1254  }
1255  static bool classof(const ConditionalOperator *) { return true; }
1256
1257  // Iterators
1258  virtual child_iterator child_begin();
1259  virtual child_iterator child_end();
1260
1261  virtual void EmitImpl(llvm::Serializer& S) const;
1262  static ConditionalOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1263};
1264
1265/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1266class AddrLabelExpr : public Expr {
1267  SourceLocation AmpAmpLoc, LabelLoc;
1268  LabelStmt *Label;
1269public:
1270  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1271                QualType t)
1272    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1273
1274  virtual SourceRange getSourceRange() const {
1275    return SourceRange(AmpAmpLoc, LabelLoc);
1276  }
1277
1278  LabelStmt *getLabel() const { return Label; }
1279
1280  static bool classof(const Stmt *T) {
1281    return T->getStmtClass() == AddrLabelExprClass;
1282  }
1283  static bool classof(const AddrLabelExpr *) { return true; }
1284
1285  // Iterators
1286  virtual child_iterator child_begin();
1287  virtual child_iterator child_end();
1288
1289  virtual void EmitImpl(llvm::Serializer& S) const;
1290  static AddrLabelExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1291};
1292
1293/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1294/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1295/// takes the value of the last subexpression.
1296class StmtExpr : public Expr {
1297  Stmt *SubStmt;
1298  SourceLocation LParenLoc, RParenLoc;
1299public:
1300  StmtExpr(CompoundStmt *substmt, QualType T,
1301           SourceLocation lp, SourceLocation rp) :
1302    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1303
1304  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1305  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1306
1307  virtual SourceRange getSourceRange() const {
1308    return SourceRange(LParenLoc, RParenLoc);
1309  }
1310
1311  static bool classof(const Stmt *T) {
1312    return T->getStmtClass() == StmtExprClass;
1313  }
1314  static bool classof(const StmtExpr *) { return true; }
1315
1316  // Iterators
1317  virtual child_iterator child_begin();
1318  virtual child_iterator child_end();
1319
1320  virtual void EmitImpl(llvm::Serializer& S) const;
1321  static StmtExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1322};
1323
1324/// TypesCompatibleExpr - GNU builtin-in function __builtin_type_compatible_p.
1325/// This AST node represents a function that returns 1 if two *types* (not
1326/// expressions) are compatible. The result of this built-in function can be
1327/// used in integer constant expressions.
1328class TypesCompatibleExpr : public Expr {
1329  QualType Type1;
1330  QualType Type2;
1331  SourceLocation BuiltinLoc, RParenLoc;
1332public:
1333  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1334                      QualType t1, QualType t2, SourceLocation RP) :
1335    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1336    BuiltinLoc(BLoc), RParenLoc(RP) {}
1337
1338  QualType getArgType1() const { return Type1; }
1339  QualType getArgType2() const { return Type2; }
1340
1341  virtual SourceRange getSourceRange() const {
1342    return SourceRange(BuiltinLoc, RParenLoc);
1343  }
1344  static bool classof(const Stmt *T) {
1345    return T->getStmtClass() == TypesCompatibleExprClass;
1346  }
1347  static bool classof(const TypesCompatibleExpr *) { return true; }
1348
1349  // Iterators
1350  virtual child_iterator child_begin();
1351  virtual child_iterator child_end();
1352
1353  virtual void EmitImpl(llvm::Serializer& S) const;
1354  static TypesCompatibleExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1355};
1356
1357/// ShuffleVectorExpr - clang-specific builtin-in function
1358/// __builtin_shufflevector.
1359/// This AST node represents a operator that does a constant
1360/// shuffle, similar to LLVM's shufflevector instruction. It takes
1361/// two vectors and a variable number of constant indices,
1362/// and returns the appropriately shuffled vector.
1363class ShuffleVectorExpr : public Expr {
1364  SourceLocation BuiltinLoc, RParenLoc;
1365
1366  // SubExprs - the list of values passed to the __builtin_shufflevector
1367  // function. The first two are vectors, and the rest are constant
1368  // indices.  The number of values in this list is always
1369  // 2+the number of indices in the vector type.
1370  Stmt **SubExprs;
1371  unsigned NumExprs;
1372
1373public:
1374  ShuffleVectorExpr(Expr **args, unsigned nexpr,
1375                    QualType Type, SourceLocation BLoc,
1376                    SourceLocation RP) :
1377    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1378    RParenLoc(RP), NumExprs(nexpr) {
1379
1380    SubExprs = new Stmt*[nexpr];
1381    for (unsigned i = 0; i < nexpr; i++)
1382      SubExprs[i] = args[i];
1383  }
1384
1385  virtual SourceRange getSourceRange() const {
1386    return SourceRange(BuiltinLoc, RParenLoc);
1387  }
1388  static bool classof(const Stmt *T) {
1389    return T->getStmtClass() == ShuffleVectorExprClass;
1390  }
1391  static bool classof(const ShuffleVectorExpr *) { return true; }
1392
1393  ~ShuffleVectorExpr() {
1394    delete [] SubExprs;
1395  }
1396
1397  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1398  /// constant expression, the actual arguments passed in, and the function
1399  /// pointers.
1400  unsigned getNumSubExprs() const { return NumExprs; }
1401
1402  /// getExpr - Return the Expr at the specified index.
1403  Expr *getExpr(unsigned Index) {
1404    assert((Index < NumExprs) && "Arg access out of range!");
1405    return cast<Expr>(SubExprs[Index]);
1406  }
1407  const Expr *getExpr(unsigned Index) const {
1408    assert((Index < NumExprs) && "Arg access out of range!");
1409    return cast<Expr>(SubExprs[Index]);
1410  }
1411
1412  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1413    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1414    return getExpr(N+2)->getIntegerConstantExprValue(Ctx).getZExtValue();
1415  }
1416
1417  // Iterators
1418  virtual child_iterator child_begin();
1419  virtual child_iterator child_end();
1420
1421  virtual void EmitImpl(llvm::Serializer& S) const;
1422  static ShuffleVectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1423};
1424
1425/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1426/// This AST node is similar to the conditional operator (?:) in C, with
1427/// the following exceptions:
1428/// - the test expression must be a constant expression.
1429/// - the expression returned has it's type unaltered by promotion rules.
1430/// - does not evaluate the expression that was not chosen.
1431class ChooseExpr : public Expr {
1432  enum { COND, LHS, RHS, END_EXPR };
1433  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1434  SourceLocation BuiltinLoc, RParenLoc;
1435public:
1436  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1437             SourceLocation RP)
1438    : Expr(ChooseExprClass, t),
1439      BuiltinLoc(BLoc), RParenLoc(RP) {
1440      SubExprs[COND] = cond;
1441      SubExprs[LHS] = lhs;
1442      SubExprs[RHS] = rhs;
1443    }
1444
1445  /// isConditionTrue - Return true if the condition is true.  This is always
1446  /// statically knowable for a well-formed choosexpr.
1447  bool isConditionTrue(ASTContext &C) const;
1448
1449  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1450  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1451  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1452
1453  virtual SourceRange getSourceRange() const {
1454    return SourceRange(BuiltinLoc, RParenLoc);
1455  }
1456  static bool classof(const Stmt *T) {
1457    return T->getStmtClass() == ChooseExprClass;
1458  }
1459  static bool classof(const ChooseExpr *) { return true; }
1460
1461  // Iterators
1462  virtual child_iterator child_begin();
1463  virtual child_iterator child_end();
1464
1465  virtual void EmitImpl(llvm::Serializer& S) const;
1466  static ChooseExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1467};
1468
1469/// GNUNullExpr - Implements the GNU __null extension, which is a name
1470/// for a null pointer constant that has integral type (e.g., int or
1471/// long) and is the same size and alignment as a pointer. The __null
1472/// extension is typically only used by system headers, which define
1473/// NULL as __null in C++ rather than using 0 (which is an integer
1474/// that may not match the size of a pointer).
1475class GNUNullExpr : public Expr {
1476  /// TokenLoc - The location of the __null keyword.
1477  SourceLocation TokenLoc;
1478
1479public:
1480  GNUNullExpr(QualType Ty, SourceLocation Loc)
1481    : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { }
1482
1483  /// getTokenLocation - The location of the __null token.
1484  SourceLocation getTokenLocation() const { return TokenLoc; }
1485
1486  virtual SourceRange getSourceRange() const {
1487    return SourceRange(TokenLoc);
1488  }
1489  static bool classof(const Stmt *T) {
1490    return T->getStmtClass() == GNUNullExprClass;
1491  }
1492  static bool classof(const GNUNullExpr *) { return true; }
1493
1494  // Iterators
1495  virtual child_iterator child_begin();
1496  virtual child_iterator child_end();
1497
1498  virtual void EmitImpl(llvm::Serializer& S) const;
1499  static GNUNullExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1500};
1501
1502/// OverloadExpr - Clang builtin function __builtin_overload.
1503/// This AST node provides a way to overload functions in C.
1504///
1505/// The first argument is required to be a constant expression, for the number
1506/// of arguments passed to each candidate function.
1507///
1508/// The next N arguments, where N is the value of the constant expression,
1509/// are the values to be passed as arguments.
1510///
1511/// The rest of the arguments are values of pointer to function type, which
1512/// are the candidate functions for overloading.
1513///
1514/// The result is a equivalent to a CallExpr taking N arguments to the
1515/// candidate function whose parameter types match the types of the N arguments.
1516///
1517/// example: float Z = __builtin_overload(2, X, Y, modf, mod, modl);
1518/// If X and Y are long doubles, Z will assigned the result of modl(X, Y);
1519/// If X and Y are floats, Z will be assigned the result of modf(X, Y);
1520class OverloadExpr : public Expr {
1521  // SubExprs - the list of values passed to the __builtin_overload function.
1522  // SubExpr[0] is a constant expression
1523  // SubExpr[1-N] are the parameters to pass to the matching function call
1524  // SubExpr[N-...] are the candidate functions, of type pointer to function.
1525  Stmt **SubExprs;
1526
1527  // NumExprs - the size of the SubExprs array
1528  unsigned NumExprs;
1529
1530  // The index of the matching candidate function
1531  unsigned FnIndex;
1532
1533  SourceLocation BuiltinLoc;
1534  SourceLocation RParenLoc;
1535public:
1536  OverloadExpr(Expr **args, unsigned nexprs, unsigned idx, QualType t,
1537               SourceLocation bloc, SourceLocation rploc)
1538    : Expr(OverloadExprClass, t), NumExprs(nexprs), FnIndex(idx),
1539      BuiltinLoc(bloc), RParenLoc(rploc) {
1540    SubExprs = new Stmt*[nexprs];
1541    for (unsigned i = 0; i != nexprs; ++i)
1542      SubExprs[i] = args[i];
1543  }
1544  ~OverloadExpr() {
1545    delete [] SubExprs;
1546  }
1547
1548  /// arg_begin - Return a pointer to the list of arguments that will be passed
1549  /// to the matching candidate function, skipping over the initial constant
1550  /// expression.
1551  typedef ConstExprIterator const_arg_iterator;
1552  const_arg_iterator arg_begin() const { return &SubExprs[0]+1; }
1553  const_arg_iterator arg_end(ASTContext& Ctx) const {
1554    return &SubExprs[0]+1+getNumArgs(Ctx);
1555  }
1556
1557  /// getNumArgs - Return the number of arguments to pass to the candidate
1558  /// functions.
1559  unsigned getNumArgs(ASTContext &Ctx) const {
1560    return getExpr(0)->getIntegerConstantExprValue(Ctx).getZExtValue();
1561  }
1562
1563  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1564  /// constant expression, the actual arguments passed in, and the function
1565  /// pointers.
1566  unsigned getNumSubExprs() const { return NumExprs; }
1567
1568  /// getExpr - Return the Expr at the specified index.
1569  Expr *getExpr(unsigned Index) const {
1570    assert((Index < NumExprs) && "Arg access out of range!");
1571    return cast<Expr>(SubExprs[Index]);
1572  }
1573
1574  /// getFn - Return the matching candidate function for this OverloadExpr.
1575  Expr *getFn() const { return cast<Expr>(SubExprs[FnIndex]); }
1576
1577  virtual SourceRange getSourceRange() const {
1578    return SourceRange(BuiltinLoc, RParenLoc);
1579  }
1580  static bool classof(const Stmt *T) {
1581    return T->getStmtClass() == OverloadExprClass;
1582  }
1583  static bool classof(const OverloadExpr *) { return true; }
1584
1585  // Iterators
1586  virtual child_iterator child_begin();
1587  virtual child_iterator child_end();
1588
1589  virtual void EmitImpl(llvm::Serializer& S) const;
1590  static OverloadExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1591};
1592
1593/// VAArgExpr, used for the builtin function __builtin_va_start.
1594class VAArgExpr : public Expr {
1595  Stmt *Val;
1596  SourceLocation BuiltinLoc, RParenLoc;
1597public:
1598  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1599    : Expr(VAArgExprClass, t),
1600      Val(e),
1601      BuiltinLoc(BLoc),
1602      RParenLoc(RPLoc) { }
1603
1604  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1605  Expr *getSubExpr() { return cast<Expr>(Val); }
1606  virtual SourceRange getSourceRange() const {
1607    return SourceRange(BuiltinLoc, RParenLoc);
1608  }
1609  static bool classof(const Stmt *T) {
1610    return T->getStmtClass() == VAArgExprClass;
1611  }
1612  static bool classof(const VAArgExpr *) { return true; }
1613
1614  // Iterators
1615  virtual child_iterator child_begin();
1616  virtual child_iterator child_end();
1617
1618  virtual void EmitImpl(llvm::Serializer& S) const;
1619  static VAArgExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1620};
1621
1622/// @brief Describes an C or C++ initializer list.
1623///
1624/// InitListExpr describes an initializer list, which can be used to
1625/// initialize objects of different types, including
1626/// struct/class/union types, arrays, and vectors. For example:
1627///
1628/// @code
1629/// struct foo x = { 1, { 2, 3 } };
1630/// @endcode
1631///
1632/// Prior to semantic analysis, an initializer list will represent the
1633/// initializer list as written by the user, but will have the
1634/// placeholder type "void". This initializer list is called the
1635/// syntactic form of the initializer, and may contain C99 designated
1636/// initializers (represented as DesignatedInitExprs), initializations
1637/// of subobject members without explicit braces, and so on. Clients
1638/// interested in the original syntax of the initializer list should
1639/// use the syntactic form of the initializer list.
1640///
1641/// After semantic analysis, the initializer list will represent the
1642/// semantic form of the initializer, where the initializations of all
1643/// subobjects are made explicit with nested InitListExpr nodes and
1644/// C99 designators have been eliminated by placing the designated
1645/// initializations into the subobject they initialize. Additionally,
1646/// any "holes" in the initialization, where no initializer has been
1647/// specified for a particular subobject, will be replaced with
1648/// implicitly-generated ImplicitValueInitExpr expressions that
1649/// value-initialize the subobjects. Note, however, that the
1650/// initializer lists may still have fewer initializers than there are
1651/// elements to initialize within the object.
1652///
1653/// Given the semantic form of the initializer list, one can retrieve
1654/// the original syntactic form of that initializer list (if it
1655/// exists) using getSyntacticForm(). Since many initializer lists
1656/// have the same syntactic and semantic forms, getSyntacticForm() may
1657/// return NULL, indicating that the current initializer list also
1658/// serves as its syntactic form.
1659class InitListExpr : public Expr {
1660  std::vector<Stmt *> InitExprs;
1661  SourceLocation LBraceLoc, RBraceLoc;
1662
1663  /// Contains the initializer list that describes the syntactic form
1664  /// written in the source code.
1665  InitListExpr *SyntacticForm;
1666
1667  /// If this initializer list initializes a union, specifies which
1668  /// field within the union will be initialized.
1669  FieldDecl *UnionFieldInit;
1670
1671  /// Whether this initializer list originally had a GNU array-range
1672  /// designator in it. This is a temporary marker used by CodeGen.
1673  bool HadArrayRangeDesignator;
1674
1675public:
1676  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
1677               SourceLocation rbraceloc);
1678
1679  unsigned getNumInits() const { return InitExprs.size(); }
1680
1681  const Expr* getInit(unsigned Init) const {
1682    assert(Init < getNumInits() && "Initializer access out of range!");
1683    return cast_or_null<Expr>(InitExprs[Init]);
1684  }
1685
1686  Expr* getInit(unsigned Init) {
1687    assert(Init < getNumInits() && "Initializer access out of range!");
1688    return cast_or_null<Expr>(InitExprs[Init]);
1689  }
1690
1691  void setInit(unsigned Init, Expr *expr) {
1692    assert(Init < getNumInits() && "Initializer access out of range!");
1693    InitExprs[Init] = expr;
1694  }
1695
1696  /// @brief Specify the number of initializers
1697  ///
1698  /// If there are more than @p NumInits initializers, the remaining
1699  /// initializers will be destroyed. If there are fewer than @p
1700  /// NumInits initializers, NULL expressions will be added for the
1701  /// unknown initializers.
1702  void resizeInits(ASTContext &Context, unsigned NumInits);
1703
1704  /// @brief Updates the initializer at index @p Init with the new
1705  /// expression @p expr, and returns the old expression at that
1706  /// location.
1707  ///
1708  /// When @p Init is out of range for this initializer list, the
1709  /// initializer list will be extended with NULL expressions to
1710  /// accomodate the new entry.
1711  Expr *updateInit(unsigned Init, Expr *expr);
1712
1713  /// \brief If this initializes a union, specifies which field in the
1714  /// union to initialize.
1715  ///
1716  /// Typically, this field is the first named field within the
1717  /// union. However, a designated initializer can specify the
1718  /// initialization of a different field within the union.
1719  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
1720  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
1721
1722  // Explicit InitListExpr's originate from source code (and have valid source
1723  // locations). Implicit InitListExpr's are created by the semantic analyzer.
1724  bool isExplicit() {
1725    return LBraceLoc.isValid() && RBraceLoc.isValid();
1726  }
1727
1728  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
1729
1730  /// @brief Retrieve the initializer list that describes the
1731  /// syntactic form of the initializer.
1732  ///
1733  ///
1734  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
1735  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
1736
1737  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
1738  void sawArrayRangeDesignator() {
1739    HadArrayRangeDesignator = true;
1740  }
1741
1742  virtual SourceRange getSourceRange() const {
1743    return SourceRange(LBraceLoc, RBraceLoc);
1744  }
1745  static bool classof(const Stmt *T) {
1746    return T->getStmtClass() == InitListExprClass;
1747  }
1748  static bool classof(const InitListExpr *) { return true; }
1749
1750  // Iterators
1751  virtual child_iterator child_begin();
1752  virtual child_iterator child_end();
1753
1754  typedef std::vector<Stmt *>::iterator iterator;
1755  typedef std::vector<Stmt *>::reverse_iterator reverse_iterator;
1756
1757  iterator begin() { return InitExprs.begin(); }
1758  iterator end() { return InitExprs.end(); }
1759  reverse_iterator rbegin() { return InitExprs.rbegin(); }
1760  reverse_iterator rend() { return InitExprs.rend(); }
1761
1762  // Serailization.
1763  virtual void EmitImpl(llvm::Serializer& S) const;
1764  static InitListExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1765
1766private:
1767  // Used by serializer.
1768  InitListExpr() : Expr(InitListExprClass, QualType()) {}
1769};
1770
1771/// @brief Represents a C99 designated initializer expression.
1772///
1773/// A designated initializer expression (C99 6.7.8) contains one or
1774/// more designators (which can be field designators, array
1775/// designators, or GNU array-range designators) followed by an
1776/// expression that initializes the field or element(s) that the
1777/// designators refer to. For example, given:
1778///
1779/// @code
1780/// struct point {
1781///   double x;
1782///   double y;
1783/// };
1784/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1785/// @endcode
1786///
1787/// The InitListExpr contains three DesignatedInitExprs, the first of
1788/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
1789/// designators, one array designator for @c [2] followed by one field
1790/// designator for @c .y. The initalization expression will be 1.0.
1791class DesignatedInitExpr : public Expr {
1792  /// The location of the '=' or ':' prior to the actual initializer
1793  /// expression.
1794  SourceLocation EqualOrColonLoc;
1795
1796  /// Whether this designated initializer used the GNU deprecated ':'
1797  /// syntax rather than the C99 '=' syntax.
1798  bool UsesColonSyntax : 1;
1799
1800  /// The number of designators in this initializer expression.
1801  unsigned NumDesignators : 15;
1802
1803  /// The number of subexpressions of this initializer expression,
1804  /// which contains both the initializer and any additional
1805  /// expressions used by array and array-range designators.
1806  unsigned NumSubExprs : 16;
1807
1808  DesignatedInitExpr(QualType Ty, unsigned NumDesignators,
1809                     SourceLocation EqualOrColonLoc, bool UsesColonSyntax,
1810                     unsigned NumSubExprs)
1811    : Expr(DesignatedInitExprClass, Ty),
1812      EqualOrColonLoc(EqualOrColonLoc), UsesColonSyntax(UsesColonSyntax),
1813      NumDesignators(NumDesignators), NumSubExprs(NumSubExprs) { }
1814
1815public:
1816  /// A field designator, e.g., ".x".
1817  struct FieldDesignator {
1818    /// Refers to the field that is being initialized. The low bit
1819    /// of this field determines whether this is actually a pointer
1820    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
1821    /// initially constructed, a field designator will store an
1822    /// IdentifierInfo*. After semantic analysis has resolved that
1823    /// name, the field designator will instead store a FieldDecl*.
1824    uintptr_t NameOrField;
1825
1826    /// The location of the '.' in the designated initializer.
1827    unsigned DotLoc;
1828
1829    /// The location of the field name in the designated initializer.
1830    unsigned FieldLoc;
1831  };
1832
1833  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
1834  struct ArrayOrRangeDesignator {
1835    /// Location of the first index expression within the designated
1836    /// initializer expression's list of subexpressions.
1837    unsigned Index;
1838    /// The location of the '[' starting the array range designator.
1839    unsigned LBracketLoc;
1840    /// The location of the ellipsis separating the start and end
1841    /// indices. Only valid for GNU array-range designators.
1842    unsigned EllipsisLoc;
1843    /// The location of the ']' terminating the array range designator.
1844    unsigned RBracketLoc;
1845  };
1846
1847  /// @brief Represents a single C99 designator.
1848  ///
1849  /// @todo This class is infuriatingly similar to clang::Designator,
1850  /// but minor differences (storing indices vs. storing pointers)
1851  /// keep us from reusing it. Try harder, later, to rectify these
1852  /// differences.
1853  class Designator {
1854    /// @brief The kind of designator this describes.
1855    enum {
1856      FieldDesignator,
1857      ArrayDesignator,
1858      ArrayRangeDesignator
1859    } Kind;
1860
1861    union {
1862      /// A field designator, e.g., ".x".
1863      struct FieldDesignator Field;
1864      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
1865      struct ArrayOrRangeDesignator ArrayOrRange;
1866    };
1867    friend class DesignatedInitExpr;
1868
1869  public:
1870    /// @brief Initializes a field designator.
1871    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
1872               SourceLocation FieldLoc)
1873      : Kind(FieldDesignator) {
1874      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
1875      Field.DotLoc = DotLoc.getRawEncoding();
1876      Field.FieldLoc = FieldLoc.getRawEncoding();
1877    }
1878
1879    /// @brief Initializes an array designator.
1880    Designator(unsigned Index, SourceLocation LBracketLoc,
1881               SourceLocation RBracketLoc)
1882      : Kind(ArrayDesignator) {
1883      ArrayOrRange.Index = Index;
1884      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
1885      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
1886      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
1887    }
1888
1889    /// @brief Initializes a GNU array-range designator.
1890    Designator(unsigned Index, SourceLocation LBracketLoc,
1891               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
1892      : Kind(ArrayRangeDesignator) {
1893      ArrayOrRange.Index = Index;
1894      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
1895      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
1896      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
1897    }
1898
1899    bool isFieldDesignator() const { return Kind == FieldDesignator; }
1900    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
1901    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
1902
1903    IdentifierInfo * getFieldName();
1904
1905    FieldDecl *getField() {
1906      assert(Kind == FieldDesignator && "Only valid on a field designator");
1907      if (Field.NameOrField & 0x01)
1908        return 0;
1909      else
1910        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
1911    }
1912
1913    void setField(FieldDecl *FD) {
1914      assert(Kind == FieldDesignator && "Only valid on a field designator");
1915      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
1916    }
1917
1918    SourceLocation getDotLoc() const {
1919      assert(Kind == FieldDesignator && "Only valid on a field designator");
1920      return SourceLocation::getFromRawEncoding(Field.DotLoc);
1921    }
1922
1923    SourceLocation getFieldLoc() const {
1924      assert(Kind == FieldDesignator && "Only valid on a field designator");
1925      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
1926    }
1927
1928    SourceLocation getLBracketLoc() const {
1929      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
1930             "Only valid on an array or array-range designator");
1931      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
1932    }
1933
1934    SourceLocation getRBracketLoc() const {
1935      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
1936             "Only valid on an array or array-range designator");
1937      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
1938    }
1939
1940    SourceLocation getEllipsisLoc() const {
1941      assert(Kind == ArrayRangeDesignator &&
1942             "Only valid on an array-range designator");
1943      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
1944    }
1945
1946    SourceLocation getStartLocation() const {
1947      if (Kind == FieldDesignator)
1948        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
1949      else
1950        return getLBracketLoc();
1951    }
1952  };
1953
1954  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
1955                                    unsigned NumDesignators,
1956                                    Expr **IndexExprs, unsigned NumIndexExprs,
1957                                    SourceLocation EqualOrColonLoc,
1958                                    bool UsesColonSyntax, Expr *Init);
1959
1960  /// @brief Returns the number of designators in this initializer.
1961  unsigned size() const { return NumDesignators; }
1962
1963  // Iterator access to the designators.
1964  typedef Designator* designators_iterator;
1965  designators_iterator designators_begin();
1966  designators_iterator designators_end();
1967
1968  Expr *getArrayIndex(const Designator& D);
1969  Expr *getArrayRangeStart(const Designator& D);
1970  Expr *getArrayRangeEnd(const Designator& D);
1971
1972  /// @brief Retrieve the location of the '=' that precedes the
1973  /// initializer value itself, if present.
1974  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
1975
1976  /// @brief Determines whether this designated initializer used the
1977  /// GNU 'fieldname:' syntax or the C99 '=' syntax.
1978  bool usesColonSyntax() const { return UsesColonSyntax; }
1979
1980  /// @brief Retrieve the initializer value.
1981  Expr *getInit() const {
1982    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
1983  }
1984
1985  void setInit(Expr *init) {
1986    *child_begin() = init;
1987  }
1988
1989  virtual SourceRange getSourceRange() const;
1990
1991  static bool classof(const Stmt *T) {
1992    return T->getStmtClass() == DesignatedInitExprClass;
1993  }
1994  static bool classof(const DesignatedInitExpr *) { return true; }
1995
1996  // Iterators
1997  virtual child_iterator child_begin();
1998  virtual child_iterator child_end();
1999};
2000
2001/// \brief Represents an implicitly-generated value initialization of
2002/// an object of a given type.
2003///
2004/// Implicit value initializations occur within semantic initializer
2005/// list expressions (InitListExpr) as placeholders for subobject
2006/// initializations not explicitly specified by the user.
2007///
2008/// \see InitListExpr
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