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