Expr.h revision 8320aaaa01d931aa234fc3bce05b399ef41898d5
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/Stmt.h"
18#include "clang/AST/Type.h"
19#include "llvm/ADT/APSInt.h"
20#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/SmallVector.h"
22#include <vector>
23
24namespace clang {
25  class ASTContext;
26  class APValue;
27  class Decl;
28  class IdentifierInfo;
29  class ParmVarDecl;
30  class NamedDecl;
31  class ValueDecl;
32  class BlockDecl;
33
34/// Expr - This represents one expression.  Note that Expr's are subclasses of
35/// Stmt.  This allows an expression to be transparently used any place a Stmt
36/// is required.
37///
38class Expr : public Stmt {
39  QualType TR;
40protected:
41  Expr(StmtClass SC, QualType T) : Stmt(SC), TR(T) {
42    // In C++, the type of an expression is always adjusted so that it
43    // will not have reference type an expression will never have
44    // reference type (C++ [expr]p6). Use
45    // QualType::getNonReferenceType() to retrieve the non-reference
46    // type. Additionally, inspect Expr::isLvalue to determine whether
47    // an expression that is adjusted in this manner should be
48    // considered an lvalue.
49    assert((T.isNull() || !T->isReferenceType()) &&
50           "Expressions can't have reference type");
51  }
52public:
53  QualType getType() const { return TR; }
54  void setType(QualType t) { TR = t; }
55
56  /// SourceLocation tokens are not useful in isolation - they are low level
57  /// value objects created/interpreted by SourceManager. We assume AST
58  /// clients will have a pointer to the respective SourceManager.
59  virtual SourceRange getSourceRange() const = 0;
60
61  /// getExprLoc - Return the preferred location for the arrow when diagnosing
62  /// a problem with a generic expression.
63  virtual SourceLocation getExprLoc() const { return getLocStart(); }
64
65  /// hasLocalSideEffect - Return true if this immediate expression has side
66  /// effects, not counting any sub-expressions.
67  bool hasLocalSideEffect() const;
68
69  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
70  /// incomplete type other than void. Nonarray expressions that can be lvalues:
71  ///  - name, where name must be a variable
72  ///  - e[i]
73  ///  - (e), where e must be an lvalue
74  ///  - e.name, where e must be an lvalue
75  ///  - e->name
76  ///  - *e, the type of e cannot be a function type
77  ///  - string-constant
78  ///  - reference type [C++ [expr]]
79  ///
80  enum isLvalueResult {
81    LV_Valid,
82    LV_NotObjectType,
83    LV_IncompleteVoidType,
84    LV_DuplicateVectorComponents,
85    LV_InvalidExpression
86  };
87  isLvalueResult isLvalue(ASTContext &Ctx) const;
88
89  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
90  /// does not have an incomplete type, does not have a const-qualified type,
91  /// and if it is a structure or union, does not have any member (including,
92  /// recursively, any member or element of all contained aggregates or unions)
93  /// with a const-qualified type.
94  enum isModifiableLvalueResult {
95    MLV_Valid,
96    MLV_NotObjectType,
97    MLV_IncompleteVoidType,
98    MLV_DuplicateVectorComponents,
99    MLV_InvalidExpression,
100    MLV_IncompleteType,
101    MLV_ConstQualified,
102    MLV_ArrayType,
103    MLV_NotBlockQualified
104  };
105  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx) const;
106
107  bool isNullPointerConstant(ASTContext &Ctx) const;
108
109  /// getIntegerConstantExprValue() - Return the value of an integer
110  /// constant expression. The expression must be a valid integer
111  /// constant expression as determined by isIntegerConstantExpr.
112  llvm::APSInt getIntegerConstantExprValue(ASTContext &Ctx) const {
113    llvm::APSInt X;
114    bool success = isIntegerConstantExpr(X, Ctx);
115    success = success;
116    assert(success && "Illegal argument to getIntegerConstantExpr");
117    return X;
118  }
119
120  /// isIntegerConstantExpr - Return true if this expression is a valid integer
121  /// constant expression, and, if so, return its value in Result.  If not a
122  /// valid i-c-e, return false and fill in Loc (if specified) with the location
123  /// of the invalid expression.
124  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
125                             SourceLocation *Loc = 0,
126                             bool isEvaluated = true) const;
127  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
128    llvm::APSInt X;
129    return isIntegerConstantExpr(X, Ctx, Loc);
130  }
131  /// isConstantExpr - Return true if this expression is a valid constant expr.
132  bool isConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const;
133
134  /// tryEvaluate - Return true if this is a constant which we can fold using
135  /// any crazy technique (that has nothing to do with language standards) that
136  /// we want to.  If this function returns true, it returns the folded constant
137  /// in Result.
138  bool tryEvaluate(APValue& Result, ASTContext &Ctx) const;
139
140  /// isEvaluatable - Call tryEvaluate to see if this expression can be constant
141  /// folded, but discard the result.
142  bool isEvaluatable(ASTContext &Ctx) const;
143
144  /// hasGlobalStorage - Return true if this expression has static storage
145  /// duration.  This means that the address of this expression is a link-time
146  /// constant.
147  bool hasGlobalStorage() const;
148
149  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
150  ///  its subexpression.  If that subexpression is also a ParenExpr,
151  ///  then this method recursively returns its subexpression, and so forth.
152  ///  Otherwise, the method returns the current Expr.
153  Expr* IgnoreParens();
154
155  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
156  /// or CastExprs or ImplicitCastExprs, returning their operand.
157  Expr *IgnoreParenCasts();
158
159  const Expr* IgnoreParens() const {
160    return const_cast<Expr*>(this)->IgnoreParens();
161  }
162  const Expr *IgnoreParenCasts() const {
163    return const_cast<Expr*>(this)->IgnoreParenCasts();
164  }
165
166  static bool classof(const Stmt *T) {
167    return T->getStmtClass() >= firstExprConstant &&
168           T->getStmtClass() <= lastExprConstant;
169  }
170  static bool classof(const Expr *) { return true; }
171
172  static inline Expr* Create(llvm::Deserializer& D, ASTContext& C) {
173    return cast<Expr>(Stmt::Create(D, C));
174  }
175};
176
177
178//===----------------------------------------------------------------------===//
179// Primary Expressions.
180//===----------------------------------------------------------------------===//
181
182/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
183/// enum, etc.
184class DeclRefExpr : public Expr {
185  NamedDecl *D;
186  SourceLocation Loc;
187
188protected:
189  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l) :
190    Expr(SC, t), D(d), Loc(l) {}
191
192public:
193  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) :
194    Expr(DeclRefExprClass, t), D(d), Loc(l) {}
195
196  NamedDecl *getDecl() { return D; }
197  const NamedDecl *getDecl() const { return D; }
198  SourceLocation getLocation() const { return Loc; }
199  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
200
201
202  static bool classof(const Stmt *T) {
203    return T->getStmtClass() == DeclRefExprClass ||
204           T->getStmtClass() == CXXConditionDeclExprClass;
205  }
206  static bool classof(const DeclRefExpr *) { return true; }
207
208  // Iterators
209  virtual child_iterator child_begin();
210  virtual child_iterator child_end();
211
212  virtual void EmitImpl(llvm::Serializer& S) const;
213  static DeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
214};
215
216/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
217class PredefinedExpr : public Expr {
218public:
219  enum IdentType {
220    Func,
221    Function,
222    PrettyFunction,
223    CXXThis,
224    ObjCSuper // super
225  };
226
227private:
228  SourceLocation Loc;
229  IdentType Type;
230public:
231  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
232    : Expr(PredefinedExprClass, type), Loc(l), Type(IT) {}
233
234  IdentType getIdentType() const { return Type; }
235
236  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
237
238  static bool classof(const Stmt *T) {
239    return T->getStmtClass() == PredefinedExprClass;
240  }
241  static bool classof(const PredefinedExpr *) { return true; }
242
243  // Iterators
244  virtual child_iterator child_begin();
245  virtual child_iterator child_end();
246
247  virtual void EmitImpl(llvm::Serializer& S) const;
248  static PredefinedExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
249};
250
251class IntegerLiteral : public Expr {
252  llvm::APInt Value;
253  SourceLocation Loc;
254public:
255  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
256  // or UnsignedLongLongTy
257  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
258    : Expr(IntegerLiteralClass, type), Value(V), Loc(l) {
259    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
260  }
261  const llvm::APInt &getValue() const { return Value; }
262  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
263
264  static bool classof(const Stmt *T) {
265    return T->getStmtClass() == IntegerLiteralClass;
266  }
267  static bool classof(const IntegerLiteral *) { return true; }
268
269  // Iterators
270  virtual child_iterator child_begin();
271  virtual child_iterator child_end();
272
273  virtual void EmitImpl(llvm::Serializer& S) const;
274  static IntegerLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
275};
276
277class CharacterLiteral : public Expr {
278  unsigned Value;
279  SourceLocation Loc;
280  bool IsWide;
281public:
282  // type should be IntTy
283  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
284    : Expr(CharacterLiteralClass, type), Value(value), Loc(l), IsWide(iswide) {
285  }
286  SourceLocation getLoc() const { return Loc; }
287  bool isWide() const { return IsWide; }
288
289  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
290
291  unsigned getValue() const { return Value; }
292
293  static bool classof(const Stmt *T) {
294    return T->getStmtClass() == CharacterLiteralClass;
295  }
296  static bool classof(const CharacterLiteral *) { return true; }
297
298  // Iterators
299  virtual child_iterator child_begin();
300  virtual child_iterator child_end();
301
302  virtual void EmitImpl(llvm::Serializer& S) const;
303  static CharacterLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
304};
305
306class FloatingLiteral : public Expr {
307  llvm::APFloat Value;
308  bool IsExact : 1;
309  SourceLocation Loc;
310public:
311  FloatingLiteral(const llvm::APFloat &V, bool* isexact,
312                  QualType Type, SourceLocation L)
313    : Expr(FloatingLiteralClass, Type), Value(V), IsExact(*isexact), Loc(L) {}
314
315  const llvm::APFloat &getValue() const { return Value; }
316
317  bool isExact() const { return IsExact; }
318
319  /// getValueAsApproximateDouble - This returns the value as an inaccurate
320  /// double.  Note that this may cause loss of precision, but is useful for
321  /// debugging dumps, etc.
322  double getValueAsApproximateDouble() const;
323
324  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
325
326  static bool classof(const Stmt *T) {
327    return T->getStmtClass() == FloatingLiteralClass;
328  }
329  static bool classof(const FloatingLiteral *) { return true; }
330
331  // Iterators
332  virtual child_iterator child_begin();
333  virtual child_iterator child_end();
334
335  virtual void EmitImpl(llvm::Serializer& S) const;
336  static FloatingLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
337};
338
339/// ImaginaryLiteral - We support imaginary integer and floating point literals,
340/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
341/// IntegerLiteral classes.  Instances of this class always have a Complex type
342/// whose element type matches the subexpression.
343///
344class ImaginaryLiteral : public Expr {
345  Stmt *Val;
346public:
347  ImaginaryLiteral(Expr *val, QualType Ty)
348    : Expr(ImaginaryLiteralClass, Ty), Val(val) {}
349
350  const Expr *getSubExpr() const { return cast<Expr>(Val); }
351  Expr *getSubExpr() { return cast<Expr>(Val); }
352
353  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
354  static bool classof(const Stmt *T) {
355    return T->getStmtClass() == ImaginaryLiteralClass;
356  }
357  static bool classof(const ImaginaryLiteral *) { return true; }
358
359  // Iterators
360  virtual child_iterator child_begin();
361  virtual child_iterator child_end();
362
363  virtual void EmitImpl(llvm::Serializer& S) const;
364  static ImaginaryLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
365};
366
367/// StringLiteral - This represents a string literal expression, e.g. "foo"
368/// or L"bar" (wide strings).  The actual string is returned by getStrData()
369/// is NOT null-terminated, and the length of the string is determined by
370/// calling getByteLength().  The C type for a string is always a
371/// ConstantArrayType.
372class StringLiteral : public Expr {
373  const char *StrData;
374  unsigned ByteLength;
375  bool IsWide;
376  // if the StringLiteral was composed using token pasting, both locations
377  // are needed. If not (the common case), firstTokLoc == lastTokLoc.
378  // FIXME: if space becomes an issue, we should create a sub-class.
379  SourceLocation firstTokLoc, lastTokLoc;
380public:
381  StringLiteral(const char *strData, unsigned byteLength, bool Wide,
382                QualType t, SourceLocation b, SourceLocation e);
383  virtual ~StringLiteral();
384
385  const char *getStrData() const { return StrData; }
386  unsigned getByteLength() const { return ByteLength; }
387  bool isWide() const { return IsWide; }
388
389  virtual SourceRange getSourceRange() const {
390    return SourceRange(firstTokLoc,lastTokLoc);
391  }
392  static bool classof(const Stmt *T) {
393    return T->getStmtClass() == StringLiteralClass;
394  }
395  static bool classof(const StringLiteral *) { return true; }
396
397  // Iterators
398  virtual child_iterator child_begin();
399  virtual child_iterator child_end();
400
401  virtual void EmitImpl(llvm::Serializer& S) const;
402  static StringLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
403};
404
405/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
406/// AST node is only formed if full location information is requested.
407class ParenExpr : public Expr {
408  SourceLocation L, R;
409  Stmt *Val;
410public:
411  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
412    : Expr(ParenExprClass, val->getType()), L(l), R(r), Val(val) {}
413
414  const Expr *getSubExpr() const { return cast<Expr>(Val); }
415  Expr *getSubExpr() { return cast<Expr>(Val); }
416  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
417
418  static bool classof(const Stmt *T) {
419    return T->getStmtClass() == ParenExprClass;
420  }
421  static bool classof(const ParenExpr *) { return true; }
422
423  // Iterators
424  virtual child_iterator child_begin();
425  virtual child_iterator child_end();
426
427  virtual void EmitImpl(llvm::Serializer& S) const;
428  static ParenExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
429};
430
431
432/// UnaryOperator - This represents the unary-expression's (except sizeof of
433/// types), the postinc/postdec operators from postfix-expression, and various
434/// extensions.
435///
436/// Notes on various nodes:
437///
438/// Real/Imag - These return the real/imag part of a complex operand.  If
439///   applied to a non-complex value, the former returns its operand and the
440///   later returns zero in the type of the operand.
441///
442/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
443///   subexpression is a compound literal with the various MemberExpr and
444///   ArraySubscriptExpr's applied to it.
445///
446class UnaryOperator : public Expr {
447public:
448  // Note that additions to this should also update the StmtVisitor class.
449  enum Opcode {
450    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
451    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
452    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
453    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
454    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
455    SizeOf, AlignOf,  // [C99 6.5.3.4] Sizeof (expr, not type) operator.
456    Real, Imag,       // "__real expr"/"__imag expr" Extension.
457    Extension,        // __extension__ marker.
458    OffsetOf          // __builtin_offsetof
459  };
460private:
461  Stmt *Val;
462  Opcode Opc;
463  SourceLocation Loc;
464public:
465
466  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
467    : Expr(UnaryOperatorClass, type), Val(input), Opc(opc), Loc(l) {}
468
469  Opcode getOpcode() const { return Opc; }
470  Expr *getSubExpr() const { return cast<Expr>(Val); }
471
472  /// getOperatorLoc - Return the location of the operator.
473  SourceLocation getOperatorLoc() const { return Loc; }
474
475  /// isPostfix - Return true if this is a postfix operation, like x++.
476  static bool isPostfix(Opcode Op);
477
478  /// isPostfix - Return true if this is a prefix operation, like --x.
479  static bool isPrefix(Opcode Op);
480
481  bool isPrefix() const { return isPrefix(Opc); }
482  bool isPostfix() const { return isPostfix(Opc); }
483  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
484  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
485  bool isSizeOfAlignOfOp() const { return Opc == SizeOf || Opc == AlignOf; }
486  bool isOffsetOfOp() const { return Opc == OffsetOf; }
487  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
488
489  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
490  /// corresponds to, e.g. "sizeof" or "[pre]++"
491  static const char *getOpcodeStr(Opcode Op);
492
493  virtual SourceRange getSourceRange() const {
494    if (isPostfix())
495      return SourceRange(Val->getLocStart(), Loc);
496    else
497      return SourceRange(Loc, Val->getLocEnd());
498  }
499  virtual SourceLocation getExprLoc() const { return Loc; }
500
501  static bool classof(const Stmt *T) {
502    return T->getStmtClass() == UnaryOperatorClass;
503  }
504  static bool classof(const UnaryOperator *) { return true; }
505
506  int64_t evaluateOffsetOf(ASTContext& C) const;
507
508  // Iterators
509  virtual child_iterator child_begin();
510  virtual child_iterator child_end();
511
512  virtual void EmitImpl(llvm::Serializer& S) const;
513  static UnaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
514};
515
516/// SizeOfAlignOfTypeExpr - [C99 6.5.3.4] - This is only for sizeof/alignof of
517/// *types*.  sizeof(expr) is handled by UnaryOperator.
518class SizeOfAlignOfTypeExpr : public Expr {
519  bool isSizeof;  // true if sizeof, false if alignof.
520  QualType Ty;
521  SourceLocation OpLoc, RParenLoc;
522public:
523  SizeOfAlignOfTypeExpr(bool issizeof, QualType argType, QualType resultType,
524                        SourceLocation op, SourceLocation rp) :
525    Expr(SizeOfAlignOfTypeExprClass, resultType),
526    isSizeof(issizeof), Ty(argType), OpLoc(op), RParenLoc(rp) {}
527
528  virtual void Destroy(ASTContext& C);
529
530  bool isSizeOf() const { return isSizeof; }
531  QualType getArgumentType() const { return Ty; }
532
533  SourceLocation getOperatorLoc() const { return OpLoc; }
534
535  virtual SourceRange getSourceRange() const {
536    return SourceRange(OpLoc, RParenLoc);
537  }
538
539  static bool classof(const Stmt *T) {
540    return T->getStmtClass() == SizeOfAlignOfTypeExprClass;
541  }
542  static bool classof(const SizeOfAlignOfTypeExpr *) { 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 SizeOfAlignOfTypeExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
550};
551
552//===----------------------------------------------------------------------===//
553// Postfix Operators.
554//===----------------------------------------------------------------------===//
555
556/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
557class ArraySubscriptExpr : public Expr {
558  enum { LHS, RHS, END_EXPR=2 };
559  Stmt* SubExprs[END_EXPR];
560  SourceLocation RBracketLoc;
561public:
562  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
563                     SourceLocation rbracketloc)
564  : Expr(ArraySubscriptExprClass, t), RBracketLoc(rbracketloc) {
565    SubExprs[LHS] = lhs;
566    SubExprs[RHS] = rhs;
567  }
568
569  /// An array access can be written A[4] or 4[A] (both are equivalent).
570  /// - getBase() and getIdx() always present the normalized view: A[4].
571  ///    In this case getBase() returns "A" and getIdx() returns "4".
572  /// - getLHS() and getRHS() present the syntactic view. e.g. for
573  ///    4[A] getLHS() returns "4".
574  /// Note: Because vector element access is also written A[4] we must
575  /// predicate the format conversion in getBase and getIdx only on the
576  /// the type of the RHS, as it is possible for the LHS to be a vector of
577  /// integer type
578  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
579  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
580
581  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
582  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
583
584  Expr *getBase() {
585    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
586  }
587
588  const Expr *getBase() const {
589    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
590  }
591
592  Expr *getIdx() {
593    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
594  }
595
596  const Expr *getIdx() const {
597    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
598  }
599
600  virtual SourceRange getSourceRange() const {
601    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
602  }
603
604  virtual SourceLocation getExprLoc() const { return RBracketLoc; }
605
606  static bool classof(const Stmt *T) {
607    return T->getStmtClass() == ArraySubscriptExprClass;
608  }
609  static bool classof(const ArraySubscriptExpr *) { return true; }
610
611  // Iterators
612  virtual child_iterator child_begin();
613  virtual child_iterator child_end();
614
615  virtual void EmitImpl(llvm::Serializer& S) const;
616  static ArraySubscriptExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
617};
618
619
620/// CallExpr - [C99 6.5.2.2] Function Calls.
621///
622class CallExpr : public Expr {
623  enum { FN=0, ARGS_START=1 };
624  Stmt **SubExprs;
625  unsigned NumArgs;
626  SourceLocation RParenLoc;
627
628  // This version of the ctor is for deserialization.
629  CallExpr(Stmt** subexprs, unsigned numargs, QualType t,
630           SourceLocation rparenloc)
631  : Expr(CallExprClass,t), SubExprs(subexprs),
632    NumArgs(numargs), RParenLoc(rparenloc) {}
633
634public:
635  CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
636           SourceLocation rparenloc);
637  ~CallExpr() {
638    delete [] SubExprs;
639  }
640
641  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
642  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
643  void setCallee(Expr *F) { SubExprs[FN] = F; }
644
645  /// getNumArgs - Return the number of actual arguments to this call.
646  ///
647  unsigned getNumArgs() const { return NumArgs; }
648
649  /// getArg - Return the specified argument.
650  Expr *getArg(unsigned Arg) {
651    assert(Arg < NumArgs && "Arg access out of range!");
652    return cast<Expr>(SubExprs[Arg+ARGS_START]);
653  }
654  const Expr *getArg(unsigned Arg) const {
655    assert(Arg < NumArgs && "Arg access out of range!");
656    return cast<Expr>(SubExprs[Arg+ARGS_START]);
657  }
658  /// setArg - Set the specified argument.
659  void setArg(unsigned Arg, Expr *ArgExpr) {
660    assert(Arg < NumArgs && "Arg access out of range!");
661    SubExprs[Arg+ARGS_START] = ArgExpr;
662  }
663
664  /// setNumArgs - This changes the number of arguments present in this call.
665  /// Any orphaned expressions are deleted by this, and any new operands are set
666  /// to null.
667  void setNumArgs(unsigned NumArgs);
668
669  typedef ExprIterator arg_iterator;
670  typedef ConstExprIterator const_arg_iterator;
671
672  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
673  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
674  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
675  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
676
677  /// getNumCommas - Return the number of commas that must have been present in
678  /// this function call.
679  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
680
681  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
682  /// not, return 0.
683  unsigned isBuiltinCall() const;
684
685  SourceLocation getRParenLoc() const { return RParenLoc; }
686
687  virtual SourceRange getSourceRange() const {
688    return SourceRange(getCallee()->getLocStart(), RParenLoc);
689  }
690
691  static bool classof(const Stmt *T) {
692    return T->getStmtClass() == CallExprClass;
693  }
694  static bool classof(const CallExpr *) { return true; }
695
696  // Iterators
697  virtual child_iterator child_begin();
698  virtual child_iterator child_end();
699
700  virtual void EmitImpl(llvm::Serializer& S) const;
701  static CallExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
702};
703
704/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.
705///
706class MemberExpr : public Expr {
707  Stmt *Base;
708  FieldDecl *MemberDecl;
709  SourceLocation MemberLoc;
710  bool IsArrow;      // True if this is "X->F", false if this is "X.F".
711public:
712  MemberExpr(Expr *base, bool isarrow, FieldDecl *memberdecl, SourceLocation l,
713             QualType ty)
714    : Expr(MemberExprClass, ty),
715      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {}
716
717  Expr *getBase() const { return cast<Expr>(Base); }
718  FieldDecl *getMemberDecl() const { return MemberDecl; }
719  bool isArrow() const { return IsArrow; }
720
721  virtual SourceRange getSourceRange() const {
722    return SourceRange(getBase()->getLocStart(), MemberLoc);
723  }
724
725  virtual SourceLocation getExprLoc() const { return MemberLoc; }
726
727  static bool classof(const Stmt *T) {
728    return T->getStmtClass() == MemberExprClass;
729  }
730  static bool classof(const MemberExpr *) { return true; }
731
732  // Iterators
733  virtual child_iterator child_begin();
734  virtual child_iterator child_end();
735
736  virtual void EmitImpl(llvm::Serializer& S) const;
737  static MemberExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
738};
739
740/// CompoundLiteralExpr - [C99 6.5.2.5]
741///
742class CompoundLiteralExpr : public Expr {
743  /// LParenLoc - If non-null, this is the location of the left paren in a
744  /// compound literal like "(int){4}".  This can be null if this is a
745  /// synthesized compound expression.
746  SourceLocation LParenLoc;
747  Stmt *Init;
748  bool FileScope;
749public:
750  CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init,
751                      bool fileScope)
752    : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init),
753      FileScope(fileScope) {}
754
755  const Expr *getInitializer() const { return cast<Expr>(Init); }
756  Expr *getInitializer() { return cast<Expr>(Init); }
757
758  bool isFileScope() const { return FileScope; }
759
760  SourceLocation getLParenLoc() const { return LParenLoc; }
761
762  virtual SourceRange getSourceRange() const {
763    // FIXME: Init should never be null.
764    if (!Init)
765      return SourceRange();
766    if (LParenLoc.isInvalid())
767      return Init->getSourceRange();
768    return SourceRange(LParenLoc, Init->getLocEnd());
769  }
770
771  static bool classof(const Stmt *T) {
772    return T->getStmtClass() == CompoundLiteralExprClass;
773  }
774  static bool classof(const CompoundLiteralExpr *) { return true; }
775
776  // Iterators
777  virtual child_iterator child_begin();
778  virtual child_iterator child_end();
779
780  virtual void EmitImpl(llvm::Serializer& S) const;
781  static CompoundLiteralExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
782};
783
784/// CastExpr - Base class for type casts, including both implicit
785/// casts (ImplicitCastExpr) and explicit casts that have some
786/// representation in the source code (ExplicitCastExpr's derived
787/// classes).
788class CastExpr : public Expr {
789  Stmt *Op;
790protected:
791  CastExpr(StmtClass SC, QualType ty, Expr *op) :
792    Expr(SC, ty), Op(op) {}
793
794public:
795  Expr *getSubExpr() { return cast<Expr>(Op); }
796  const Expr *getSubExpr() const { return cast<Expr>(Op); }
797
798  static bool classof(const Stmt *T) {
799    StmtClass SC = T->getStmtClass();
800    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
801      return true;
802
803    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
804      return true;
805
806    return false;
807  }
808  static bool classof(const CastExpr *) { return true; }
809
810  // Iterators
811  virtual child_iterator child_begin();
812  virtual child_iterator child_end();
813};
814
815/// ImplicitCastExpr - Allows us to explicitly represent implicit type
816/// conversions, which have no direct representation in the original
817/// source code. For example: converting T[]->T*, void f()->void
818/// (*f)(), float->double, short->int, etc.
819///
820class ImplicitCastExpr : public CastExpr {
821public:
822  ImplicitCastExpr(QualType ty, Expr *op) :
823    CastExpr(ImplicitCastExprClass, ty, op) {}
824
825  virtual SourceRange getSourceRange() const {
826    return getSubExpr()->getSourceRange();
827  }
828
829  static bool classof(const Stmt *T) {
830    return T->getStmtClass() == ImplicitCastExprClass;
831  }
832  static bool classof(const ImplicitCastExpr *) { return true; }
833
834  virtual void EmitImpl(llvm::Serializer& S) const;
835  static ImplicitCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
836};
837
838/// ExplicitCastExpr - An explicit cast written in the source
839/// code.
840///
841/// This class is effectively an abstract class, because it provides
842/// the basic representation of an explicitly-written cast without
843/// specifying which kind of cast (C cast, functional cast, static
844/// cast, etc.) was written; specific derived classes represent the
845/// particular style of cast and its location information.
846///
847/// Unlike implicit casts, explicit cast nodes have two different
848/// types: the type that was written into the source code, and the
849/// actual type of the expression as determined by semantic
850/// analysis. These types may differ slightly. For example, in C++ one
851/// can cast to a reference type, which indicates that the resulting
852/// expression will be an lvalue. The reference type, however, will
853/// not be used as the type of the expression.
854class ExplicitCastExpr : public CastExpr {
855  /// TypeAsWritten - The type that this expression is casting to, as
856  /// written in the source code.
857  QualType TypeAsWritten;
858
859protected:
860  ExplicitCastExpr(StmtClass SC, QualType exprTy, Expr *op, QualType writtenTy)
861    : CastExpr(SC, exprTy, op), TypeAsWritten(writtenTy) {}
862
863public:
864  /// getTypeAsWritten - Returns the type that this expression is
865  /// casting to, as written in the source code.
866  QualType getTypeAsWritten() const { return TypeAsWritten; }
867
868  static bool classof(const Stmt *T) {
869    StmtClass SC = T->getStmtClass();
870    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
871      return true;
872    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
873      return true;
874
875    return false;
876  }
877  static bool classof(const ExplicitCastExpr *) { return true; }
878};
879
880/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
881/// cast in C++ (C++ [expr.cast]), which uses the syntax
882/// (Type)expr. For example: @c (int)f.
883class CStyleCastExpr : public ExplicitCastExpr {
884  SourceLocation Loc; // the location of the left paren
885public:
886  CStyleCastExpr(QualType exprTy, Expr *op, QualType writtenTy,
887                    SourceLocation l) :
888    ExplicitCastExpr(CStyleCastExprClass, exprTy, op, writtenTy), Loc(l) {}
889
890  SourceLocation getLParenLoc() const { return Loc; }
891
892  virtual SourceRange getSourceRange() const {
893    return SourceRange(Loc, getSubExpr()->getSourceRange().getEnd());
894  }
895  static bool classof(const Stmt *T) {
896    return T->getStmtClass() == CStyleCastExprClass;
897  }
898  static bool classof(const CStyleCastExpr *) { return true; }
899
900  virtual void EmitImpl(llvm::Serializer& S) const;
901  static CStyleCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
902};
903
904class BinaryOperator : public Expr {
905public:
906  enum Opcode {
907    // Operators listed in order of precedence.
908    // Note that additions to this should also update the StmtVisitor class.
909    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
910    Add, Sub,         // [C99 6.5.6] Additive operators.
911    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
912    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
913    EQ, NE,           // [C99 6.5.9] Equality operators.
914    And,              // [C99 6.5.10] Bitwise AND operator.
915    Xor,              // [C99 6.5.11] Bitwise XOR operator.
916    Or,               // [C99 6.5.12] Bitwise OR operator.
917    LAnd,             // [C99 6.5.13] Logical AND operator.
918    LOr,              // [C99 6.5.14] Logical OR operator.
919    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
920    DivAssign, RemAssign,
921    AddAssign, SubAssign,
922    ShlAssign, ShrAssign,
923    AndAssign, XorAssign,
924    OrAssign,
925    Comma             // [C99 6.5.17] Comma operator.
926  };
927private:
928  enum { LHS, RHS, END_EXPR };
929  Stmt* SubExprs[END_EXPR];
930  Opcode Opc;
931  SourceLocation OpLoc;
932public:
933
934  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
935                 SourceLocation opLoc)
936    : Expr(BinaryOperatorClass, ResTy), Opc(opc), OpLoc(opLoc) {
937    SubExprs[LHS] = lhs;
938    SubExprs[RHS] = rhs;
939    assert(!isCompoundAssignmentOp() &&
940           "Use ArithAssignBinaryOperator for compound assignments");
941  }
942
943  SourceLocation getOperatorLoc() const { return OpLoc; }
944  Opcode getOpcode() const { return Opc; }
945  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
946  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
947  virtual SourceRange getSourceRange() const {
948    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
949  }
950
951  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
952  /// corresponds to, e.g. "<<=".
953  static const char *getOpcodeStr(Opcode Op);
954
955  /// predicates to categorize the respective opcodes.
956  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
957  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
958  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
959  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
960
961  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
962  bool isRelationalOp() const { return isRelationalOp(Opc); }
963
964  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
965  bool isEqualityOp() const { return isEqualityOp(Opc); }
966
967  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
968  bool isLogicalOp() const { return isLogicalOp(Opc); }
969
970  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
971  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
972  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
973
974  static bool classof(const Stmt *S) {
975    return S->getStmtClass() == BinaryOperatorClass ||
976           S->getStmtClass() == CompoundAssignOperatorClass;
977  }
978  static bool classof(const BinaryOperator *) { return true; }
979
980  // Iterators
981  virtual child_iterator child_begin();
982  virtual child_iterator child_end();
983
984  virtual void EmitImpl(llvm::Serializer& S) const;
985  static BinaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
986
987protected:
988  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
989                 SourceLocation oploc, bool dead)
990    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
991    SubExprs[LHS] = lhs;
992    SubExprs[RHS] = rhs;
993  }
994};
995
996/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
997/// track of the type the operation is performed in.  Due to the semantics of
998/// these operators, the operands are promoted, the aritmetic performed, an
999/// implicit conversion back to the result type done, then the assignment takes
1000/// place.  This captures the intermediate type which the computation is done
1001/// in.
1002class CompoundAssignOperator : public BinaryOperator {
1003  QualType ComputationType;
1004public:
1005  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1006                         QualType ResType, QualType CompType,
1007                         SourceLocation OpLoc)
1008    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1009      ComputationType(CompType) {
1010    assert(isCompoundAssignmentOp() &&
1011           "Only should be used for compound assignments");
1012  }
1013
1014  QualType getComputationType() const { return ComputationType; }
1015
1016  static bool classof(const CompoundAssignOperator *) { return true; }
1017  static bool classof(const Stmt *S) {
1018    return S->getStmtClass() == CompoundAssignOperatorClass;
1019  }
1020
1021  virtual void EmitImpl(llvm::Serializer& S) const;
1022  static CompoundAssignOperator* CreateImpl(llvm::Deserializer& D,
1023                                            ASTContext& C);
1024};
1025
1026/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1027/// GNU "missing LHS" extension is in use.
1028///
1029class ConditionalOperator : public Expr {
1030  enum { COND, LHS, RHS, END_EXPR };
1031  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1032public:
1033  ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t)
1034    : Expr(ConditionalOperatorClass, t) {
1035    SubExprs[COND] = cond;
1036    SubExprs[LHS] = lhs;
1037    SubExprs[RHS] = rhs;
1038  }
1039
1040  // getCond - Return the expression representing the condition for
1041  //  the ?: operator.
1042  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1043
1044  // getTrueExpr - Return the subexpression representing the value of the ?:
1045  //  expression if the condition evaluates to true.  In most cases this value
1046  //  will be the same as getLHS() except a GCC extension allows the left
1047  //  subexpression to be omitted, and instead of the condition be returned.
1048  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1049  //  is only evaluated once.
1050  Expr *getTrueExpr() const {
1051    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1052  }
1053
1054  // getTrueExpr - Return the subexpression representing the value of the ?:
1055  // expression if the condition evaluates to false. This is the same as getRHS.
1056  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1057
1058  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1059  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1060
1061  virtual SourceRange getSourceRange() const {
1062    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1063  }
1064  static bool classof(const Stmt *T) {
1065    return T->getStmtClass() == ConditionalOperatorClass;
1066  }
1067  static bool classof(const ConditionalOperator *) { return true; }
1068
1069  // Iterators
1070  virtual child_iterator child_begin();
1071  virtual child_iterator child_end();
1072
1073  virtual void EmitImpl(llvm::Serializer& S) const;
1074  static ConditionalOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1075};
1076
1077/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1078class AddrLabelExpr : public Expr {
1079  SourceLocation AmpAmpLoc, LabelLoc;
1080  LabelStmt *Label;
1081public:
1082  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1083                QualType t)
1084    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1085
1086  virtual SourceRange getSourceRange() const {
1087    return SourceRange(AmpAmpLoc, LabelLoc);
1088  }
1089
1090  LabelStmt *getLabel() const { return Label; }
1091
1092  static bool classof(const Stmt *T) {
1093    return T->getStmtClass() == AddrLabelExprClass;
1094  }
1095  static bool classof(const AddrLabelExpr *) { return true; }
1096
1097  // Iterators
1098  virtual child_iterator child_begin();
1099  virtual child_iterator child_end();
1100
1101  virtual void EmitImpl(llvm::Serializer& S) const;
1102  static AddrLabelExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1103};
1104
1105/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1106/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1107/// takes the value of the last subexpression.
1108class StmtExpr : public Expr {
1109  Stmt *SubStmt;
1110  SourceLocation LParenLoc, RParenLoc;
1111public:
1112  StmtExpr(CompoundStmt *substmt, QualType T,
1113           SourceLocation lp, SourceLocation rp) :
1114    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1115
1116  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1117  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1118
1119  virtual SourceRange getSourceRange() const {
1120    return SourceRange(LParenLoc, RParenLoc);
1121  }
1122
1123  static bool classof(const Stmt *T) {
1124    return T->getStmtClass() == StmtExprClass;
1125  }
1126  static bool classof(const StmtExpr *) { return true; }
1127
1128  // Iterators
1129  virtual child_iterator child_begin();
1130  virtual child_iterator child_end();
1131
1132  virtual void EmitImpl(llvm::Serializer& S) const;
1133  static StmtExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1134};
1135
1136/// TypesCompatibleExpr - GNU builtin-in function __builtin_type_compatible_p.
1137/// This AST node represents a function that returns 1 if two *types* (not
1138/// expressions) are compatible. The result of this built-in function can be
1139/// used in integer constant expressions.
1140class TypesCompatibleExpr : public Expr {
1141  QualType Type1;
1142  QualType Type2;
1143  SourceLocation BuiltinLoc, RParenLoc;
1144public:
1145  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1146                      QualType t1, QualType t2, SourceLocation RP) :
1147    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1148    BuiltinLoc(BLoc), RParenLoc(RP) {}
1149
1150  QualType getArgType1() const { return Type1; }
1151  QualType getArgType2() const { return Type2; }
1152
1153  virtual SourceRange getSourceRange() const {
1154    return SourceRange(BuiltinLoc, RParenLoc);
1155  }
1156  static bool classof(const Stmt *T) {
1157    return T->getStmtClass() == TypesCompatibleExprClass;
1158  }
1159  static bool classof(const TypesCompatibleExpr *) { return true; }
1160
1161  // Iterators
1162  virtual child_iterator child_begin();
1163  virtual child_iterator child_end();
1164
1165  virtual void EmitImpl(llvm::Serializer& S) const;
1166  static TypesCompatibleExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1167};
1168
1169/// ShuffleVectorExpr - clang-specific builtin-in function
1170/// __builtin_shufflevector.
1171/// This AST node represents a operator that does a constant
1172/// shuffle, similar to LLVM's shufflevector instruction. It takes
1173/// two vectors and a variable number of constant indices,
1174/// and returns the appropriately shuffled vector.
1175class ShuffleVectorExpr : public Expr {
1176  SourceLocation BuiltinLoc, RParenLoc;
1177
1178  // SubExprs - the list of values passed to the __builtin_shufflevector
1179  // function. The first two are vectors, and the rest are constant
1180  // indices.  The number of values in this list is always
1181  // 2+the number of indices in the vector type.
1182  Stmt **SubExprs;
1183  unsigned NumExprs;
1184
1185public:
1186  ShuffleVectorExpr(Expr **args, unsigned nexpr,
1187                    QualType Type, SourceLocation BLoc,
1188                    SourceLocation RP) :
1189    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1190    RParenLoc(RP), NumExprs(nexpr) {
1191
1192    SubExprs = new Stmt*[nexpr];
1193    for (unsigned i = 0; i < nexpr; i++)
1194      SubExprs[i] = args[i];
1195  }
1196
1197  virtual SourceRange getSourceRange() const {
1198    return SourceRange(BuiltinLoc, RParenLoc);
1199  }
1200  static bool classof(const Stmt *T) {
1201    return T->getStmtClass() == ShuffleVectorExprClass;
1202  }
1203  static bool classof(const ShuffleVectorExpr *) { return true; }
1204
1205  ~ShuffleVectorExpr() {
1206    delete [] SubExprs;
1207  }
1208
1209  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1210  /// constant expression, the actual arguments passed in, and the function
1211  /// pointers.
1212  unsigned getNumSubExprs() const { return NumExprs; }
1213
1214  /// getExpr - Return the Expr at the specified index.
1215  Expr *getExpr(unsigned Index) {
1216    assert((Index < NumExprs) && "Arg access out of range!");
1217    return cast<Expr>(SubExprs[Index]);
1218  }
1219  const Expr *getExpr(unsigned Index) const {
1220    assert((Index < NumExprs) && "Arg access out of range!");
1221    return cast<Expr>(SubExprs[Index]);
1222  }
1223
1224  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1225    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1226    return getExpr(N+2)->getIntegerConstantExprValue(Ctx).getZExtValue();
1227  }
1228
1229  // Iterators
1230  virtual child_iterator child_begin();
1231  virtual child_iterator child_end();
1232
1233  virtual void EmitImpl(llvm::Serializer& S) const;
1234  static ShuffleVectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1235};
1236
1237/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1238/// This AST node is similar to the conditional operator (?:) in C, with
1239/// the following exceptions:
1240/// - the test expression much be a constant expression.
1241/// - the expression returned has it's type unaltered by promotion rules.
1242/// - does not evaluate the expression that was not chosen.
1243class ChooseExpr : public Expr {
1244  enum { COND, LHS, RHS, END_EXPR };
1245  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1246  SourceLocation BuiltinLoc, RParenLoc;
1247public:
1248  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1249             SourceLocation RP)
1250    : Expr(ChooseExprClass, t),
1251      BuiltinLoc(BLoc), RParenLoc(RP) {
1252      SubExprs[COND] = cond;
1253      SubExprs[LHS] = lhs;
1254      SubExprs[RHS] = rhs;
1255    }
1256
1257  /// isConditionTrue - Return true if the condition is true.  This is always
1258  /// statically knowable for a well-formed choosexpr.
1259  bool isConditionTrue(ASTContext &C) const;
1260
1261  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1262  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1263  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1264
1265  virtual SourceRange getSourceRange() const {
1266    return SourceRange(BuiltinLoc, RParenLoc);
1267  }
1268  static bool classof(const Stmt *T) {
1269    return T->getStmtClass() == ChooseExprClass;
1270  }
1271  static bool classof(const ChooseExpr *) { return true; }
1272
1273  // Iterators
1274  virtual child_iterator child_begin();
1275  virtual child_iterator child_end();
1276
1277  virtual void EmitImpl(llvm::Serializer& S) const;
1278  static ChooseExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1279};
1280
1281/// OverloadExpr - Clang builtin function __builtin_overload.
1282/// This AST node provides a way to overload functions in C.
1283///
1284/// The first argument is required to be a constant expression, for the number
1285/// of arguments passed to each candidate function.
1286///
1287/// The next N arguments, where N is the value of the constant expression,
1288/// are the values to be passed as arguments.
1289///
1290/// The rest of the arguments are values of pointer to function type, which
1291/// are the candidate functions for overloading.
1292///
1293/// The result is a equivalent to a CallExpr taking N arguments to the
1294/// candidate function whose parameter types match the types of the N arguments.
1295///
1296/// example: float Z = __builtin_overload(2, X, Y, modf, mod, modl);
1297/// If X and Y are long doubles, Z will assigned the result of modl(X, Y);
1298/// If X and Y are floats, Z will be assigned the result of modf(X, Y);
1299class OverloadExpr : public Expr {
1300  // SubExprs - the list of values passed to the __builtin_overload function.
1301  // SubExpr[0] is a constant expression
1302  // SubExpr[1-N] are the parameters to pass to the matching function call
1303  // SubExpr[N-...] are the candidate functions, of type pointer to function.
1304  Stmt **SubExprs;
1305
1306  // NumExprs - the size of the SubExprs array
1307  unsigned NumExprs;
1308
1309  // The index of the matching candidate function
1310  unsigned FnIndex;
1311
1312  SourceLocation BuiltinLoc;
1313  SourceLocation RParenLoc;
1314public:
1315  OverloadExpr(Expr **args, unsigned nexprs, unsigned idx, QualType t,
1316               SourceLocation bloc, SourceLocation rploc)
1317    : Expr(OverloadExprClass, t), NumExprs(nexprs), FnIndex(idx),
1318      BuiltinLoc(bloc), RParenLoc(rploc) {
1319    SubExprs = new Stmt*[nexprs];
1320    for (unsigned i = 0; i != nexprs; ++i)
1321      SubExprs[i] = args[i];
1322  }
1323  ~OverloadExpr() {
1324    delete [] SubExprs;
1325  }
1326
1327  /// arg_begin - Return a pointer to the list of arguments that will be passed
1328  /// to the matching candidate function, skipping over the initial constant
1329  /// expression.
1330  typedef ConstExprIterator const_arg_iterator;
1331  const_arg_iterator arg_begin() const { return &SubExprs[0]+1; }
1332  const_arg_iterator arg_end(ASTContext& Ctx) const {
1333    return &SubExprs[0]+1+getNumArgs(Ctx);
1334  }
1335
1336  /// getNumArgs - Return the number of arguments to pass to the candidate
1337  /// functions.
1338  unsigned getNumArgs(ASTContext &Ctx) const {
1339    return getExpr(0)->getIntegerConstantExprValue(Ctx).getZExtValue();
1340  }
1341
1342  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1343  /// constant expression, the actual arguments passed in, and the function
1344  /// pointers.
1345  unsigned getNumSubExprs() const { return NumExprs; }
1346
1347  /// getExpr - Return the Expr at the specified index.
1348  Expr *getExpr(unsigned Index) const {
1349    assert((Index < NumExprs) && "Arg access out of range!");
1350    return cast<Expr>(SubExprs[Index]);
1351  }
1352
1353  /// getFn - Return the matching candidate function for this OverloadExpr.
1354  Expr *getFn() const { return cast<Expr>(SubExprs[FnIndex]); }
1355
1356  virtual SourceRange getSourceRange() const {
1357    return SourceRange(BuiltinLoc, RParenLoc);
1358  }
1359  static bool classof(const Stmt *T) {
1360    return T->getStmtClass() == OverloadExprClass;
1361  }
1362  static bool classof(const OverloadExpr *) { 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 OverloadExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1370};
1371
1372/// VAArgExpr, used for the builtin function __builtin_va_start.
1373class VAArgExpr : public Expr {
1374  Stmt *Val;
1375  SourceLocation BuiltinLoc, RParenLoc;
1376public:
1377  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1378    : Expr(VAArgExprClass, t),
1379      Val(e),
1380      BuiltinLoc(BLoc),
1381      RParenLoc(RPLoc) { }
1382
1383  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1384  Expr *getSubExpr() { return cast<Expr>(Val); }
1385  virtual SourceRange getSourceRange() const {
1386    return SourceRange(BuiltinLoc, RParenLoc);
1387  }
1388  static bool classof(const Stmt *T) {
1389    return T->getStmtClass() == VAArgExprClass;
1390  }
1391  static bool classof(const VAArgExpr *) { return true; }
1392
1393  // Iterators
1394  virtual child_iterator child_begin();
1395  virtual child_iterator child_end();
1396
1397  virtual void EmitImpl(llvm::Serializer& S) const;
1398  static VAArgExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1399};
1400
1401/// InitListExpr - used for struct and array initializers, such as:
1402///    struct foo x = { 1, { 2, 3 } };
1403///
1404/// Because C is somewhat loose with braces, the AST does not necessarily
1405/// directly model the C source.  Instead, the semantic analyzer aims to make
1406/// the InitListExprs match up with the type of the decl being initialized.  We
1407/// have the following exceptions:
1408///
1409///  1. Elements at the end of the list may be dropped from the initializer.
1410///     These elements are defined to be initialized to zero.  For example:
1411///         int x[20] = { 1 };
1412///  2. Initializers may have excess initializers which are to be ignored by the
1413///     compiler.  For example:
1414///         int x[1] = { 1, 2 };
1415///  3. Redundant InitListExprs may be present around scalar elements.  These
1416///     always have a single element whose type is the same as the InitListExpr.
1417///     this can only happen for Type::isScalarType() types.
1418///         int x = { 1 };  int y[2] = { {1}, {2} };
1419///
1420class InitListExpr : public Expr {
1421  std::vector<Stmt *> InitExprs;
1422  SourceLocation LBraceLoc, RBraceLoc;
1423
1424  /// HadDesignators - Return true if there were any designators in this
1425  /// init list expr.  FIXME: this should be replaced by storing the designators
1426  /// somehow and updating codegen.
1427  bool HadDesignators;
1428public:
1429  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
1430               SourceLocation rbraceloc, bool HadDesignators);
1431
1432  unsigned getNumInits() const { return InitExprs.size(); }
1433  bool hadDesignators() const { return HadDesignators; }
1434
1435  const Expr* getInit(unsigned Init) const {
1436    assert(Init < getNumInits() && "Initializer access out of range!");
1437    return cast<Expr>(InitExprs[Init]);
1438  }
1439
1440  Expr* getInit(unsigned Init) {
1441    assert(Init < getNumInits() && "Initializer access out of range!");
1442    return cast<Expr>(InitExprs[Init]);
1443  }
1444
1445  void setInit(unsigned Init, Expr *expr) {
1446    assert(Init < getNumInits() && "Initializer access out of range!");
1447    InitExprs[Init] = expr;
1448  }
1449
1450  // Dynamic removal/addition (for constructing implicit InitExpr's).
1451  void removeInit(unsigned Init) {
1452    InitExprs.erase(InitExprs.begin()+Init);
1453  }
1454  void addInit(unsigned Init, Expr *expr) {
1455    InitExprs.insert(InitExprs.begin()+Init, expr);
1456  }
1457
1458  // Explicit InitListExpr's originate from source code (and have valid source
1459  // locations). Implicit InitListExpr's are created by the semantic analyzer.
1460  bool isExplicit() {
1461    return LBraceLoc.isValid() && RBraceLoc.isValid();
1462  }
1463
1464  virtual SourceRange getSourceRange() const {
1465    return SourceRange(LBraceLoc, RBraceLoc);
1466  }
1467  static bool classof(const Stmt *T) {
1468    return T->getStmtClass() == InitListExprClass;
1469  }
1470  static bool classof(const InitListExpr *) { return true; }
1471
1472  // Iterators
1473  virtual child_iterator child_begin();
1474  virtual child_iterator child_end();
1475
1476  virtual void EmitImpl(llvm::Serializer& S) const;
1477  static InitListExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1478
1479private:
1480  // Used by serializer.
1481  InitListExpr() : Expr(InitListExprClass, QualType()) {}
1482};
1483
1484//===----------------------------------------------------------------------===//
1485// Clang Extensions
1486//===----------------------------------------------------------------------===//
1487
1488
1489/// ExtVectorElementExpr - This represents access to specific elements of a
1490/// vector, and may occur on the left hand side or right hand side.  For example
1491/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
1492///
1493class ExtVectorElementExpr : public Expr {
1494  Stmt *Base;
1495  IdentifierInfo &Accessor;
1496  SourceLocation AccessorLoc;
1497public:
1498  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
1499                       SourceLocation loc)
1500    : Expr(ExtVectorElementExprClass, ty),
1501      Base(base), Accessor(accessor), AccessorLoc(loc) {}
1502
1503  const Expr *getBase() const { return cast<Expr>(Base); }
1504  Expr *getBase() { return cast<Expr>(Base); }
1505
1506  IdentifierInfo &getAccessor() const { return Accessor; }
1507
1508  /// getNumElements - Get the number of components being selected.
1509  unsigned getNumElements() const;
1510
1511  /// containsDuplicateElements - Return true if any element access is
1512  /// repeated.
1513  bool containsDuplicateElements() const;
1514
1515  /// getEncodedElementAccess - Encode the elements accessed into an llvm
1516  /// aggregate Constant of ConstantInt(s).
1517  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
1518
1519  virtual SourceRange getSourceRange() const {
1520    return SourceRange(getBase()->getLocStart(), AccessorLoc);
1521  }
1522
1523  static bool classof(const Stmt *T) {
1524    return T->getStmtClass() == ExtVectorElementExprClass;
1525  }
1526  static bool classof(const ExtVectorElementExpr *) { return true; }
1527
1528  // Iterators
1529  virtual child_iterator child_begin();
1530  virtual child_iterator child_end();
1531
1532  virtual void EmitImpl(llvm::Serializer& S) const;
1533  static ExtVectorElementExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1534};
1535
1536
1537/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
1538/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1539class BlockExpr : public Expr {
1540protected:
1541  BlockDecl *TheBlock;
1542public:
1543  BlockExpr(BlockDecl *BD, QualType ty) : Expr(BlockExprClass, ty),
1544            TheBlock(BD) {}
1545
1546  BlockDecl *getBlockDecl() { return TheBlock; }
1547
1548  // Convenience functions for probing the underlying BlockDecl.
1549  SourceLocation getCaretLocation() const;
1550  const Stmt *getBody() const;
1551  Stmt *getBody();
1552
1553  virtual SourceRange getSourceRange() const {
1554    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
1555  }
1556
1557  /// getFunctionType - Return the underlying function type for this block.
1558  const FunctionType *getFunctionType() const;
1559
1560  static bool classof(const Stmt *T) {
1561    return T->getStmtClass() == BlockExprClass;
1562  }
1563  static bool classof(const BlockExpr *) { return true; }
1564
1565  // Iterators
1566  virtual child_iterator child_begin();
1567  virtual child_iterator child_end();
1568
1569  virtual void EmitImpl(llvm::Serializer& S) const;
1570  static BlockExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1571};
1572
1573/// BlockDeclRefExpr - A reference to a declared variable, function,
1574/// enum, etc.
1575class BlockDeclRefExpr : public Expr {
1576  ValueDecl *D;
1577  SourceLocation Loc;
1578  bool IsByRef;
1579public:
1580  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef) :
1581       Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef) {}
1582
1583  ValueDecl *getDecl() { return D; }
1584  const ValueDecl *getDecl() const { return D; }
1585  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
1586
1587  bool isByRef() const { return IsByRef; }
1588
1589  static bool classof(const Stmt *T) {
1590    return T->getStmtClass() == BlockDeclRefExprClass;
1591  }
1592  static bool classof(const BlockDeclRefExpr *) { return true; }
1593
1594  // Iterators
1595  virtual child_iterator child_begin();
1596  virtual child_iterator child_end();
1597
1598  virtual void EmitImpl(llvm::Serializer& S) const;
1599  static BlockDeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1600};
1601
1602}  // end namespace clang
1603
1604#endif
1605