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