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