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