Expr.h revision 41b2dcd465f1e438502c420effc9d0c747f9db8f
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 "clang/AST/DeclAccessPair.h"
21#include "clang/AST/ASTVector.h"
22#include "clang/AST/UsuallyTinyPtrVector.h"
23#include "llvm/ADT/APSInt.h"
24#include "llvm/ADT/APFloat.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include <vector>
28
29namespace clang {
30  class ASTContext;
31  class APValue;
32  class Decl;
33  class IdentifierInfo;
34  class ParmVarDecl;
35  class NamedDecl;
36  class ValueDecl;
37  class BlockDecl;
38  class CXXBaseSpecifier;
39  class CXXOperatorCallExpr;
40  class CXXMemberCallExpr;
41  class TemplateArgumentLoc;
42  class TemplateArgumentListInfo;
43
44/// \brief A simple array of base specifiers.
45typedef UsuallyTinyPtrVector<const CXXBaseSpecifier> CXXBaseSpecifierArray;
46
47/// Expr - This represents one expression.  Note that Expr's are subclasses of
48/// Stmt.  This allows an expression to be transparently used any place a Stmt
49/// is required.
50///
51class Expr : public Stmt {
52  QualType TR;
53
54protected:
55  /// TypeDependent - Whether this expression is type-dependent
56  /// (C++ [temp.dep.expr]).
57  bool TypeDependent : 1;
58
59  /// ValueDependent - Whether this expression is value-dependent
60  /// (C++ [temp.dep.constexpr]).
61  bool ValueDependent : 1;
62
63  Expr(StmtClass SC, QualType T, bool TD, bool VD)
64    : Stmt(SC), TypeDependent(TD), ValueDependent(VD) {
65    setType(T);
66  }
67
68  /// \brief Construct an empty expression.
69  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
70
71public:
72  /// \brief Increases the reference count for this expression.
73  ///
74  /// Invoke the Retain() operation when this expression
75  /// is being shared by another owner.
76  Expr *Retain() {
77    Stmt::Retain();
78    return this;
79  }
80
81  QualType getType() const { return TR; }
82  void setType(QualType t) {
83    // In C++, the type of an expression is always adjusted so that it
84    // will not have reference type an expression will never have
85    // reference type (C++ [expr]p6). Use
86    // QualType::getNonReferenceType() to retrieve the non-reference
87    // type. Additionally, inspect Expr::isLvalue to determine whether
88    // an expression that is adjusted in this manner should be
89    // considered an lvalue.
90    assert((t.isNull() || !t->isReferenceType()) &&
91           "Expressions can't have reference type");
92
93    TR = t;
94  }
95
96  /// isValueDependent - Determines whether this expression is
97  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
98  /// array bound of "Chars" in the following example is
99  /// value-dependent.
100  /// @code
101  /// template<int Size, char (&Chars)[Size]> struct meta_string;
102  /// @endcode
103  bool isValueDependent() const { return ValueDependent; }
104
105  /// \brief Set whether this expression is value-dependent or not.
106  void setValueDependent(bool VD) { ValueDependent = VD; }
107
108  /// isTypeDependent - Determines whether this expression is
109  /// type-dependent (C++ [temp.dep.expr]), which means that its type
110  /// could change from one template instantiation to the next. For
111  /// example, the expressions "x" and "x + y" are type-dependent in
112  /// the following code, but "y" is not type-dependent:
113  /// @code
114  /// template<typename T>
115  /// void add(T x, int y) {
116  ///   x + y;
117  /// }
118  /// @endcode
119  bool isTypeDependent() const { return TypeDependent; }
120
121  /// \brief Set whether this expression is type-dependent or not.
122  void setTypeDependent(bool TD) { TypeDependent = TD; }
123
124  /// SourceLocation tokens are not useful in isolation - they are low level
125  /// value objects created/interpreted by SourceManager. We assume AST
126  /// clients will have a pointer to the respective SourceManager.
127  virtual SourceRange getSourceRange() const = 0;
128
129  /// getExprLoc - Return the preferred location for the arrow when diagnosing
130  /// a problem with a generic expression.
131  virtual SourceLocation getExprLoc() const { return getLocStart(); }
132
133  /// isUnusedResultAWarning - Return true if this immediate expression should
134  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
135  /// with location to warn on and the source range[s] to report with the
136  /// warning.
137  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
138                              SourceRange &R2, ASTContext &Ctx) const;
139
140  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
141  /// incomplete type other than void. Nonarray expressions that can be lvalues:
142  ///  - name, where name must be a variable
143  ///  - e[i]
144  ///  - (e), where e must be an lvalue
145  ///  - e.name, where e must be an lvalue
146  ///  - e->name
147  ///  - *e, the type of e cannot be a function type
148  ///  - string-constant
149  ///  - reference type [C++ [expr]]
150  ///  - b ? x : y, where x and y are lvalues of suitable types [C++]
151  ///
152  enum isLvalueResult {
153    LV_Valid,
154    LV_NotObjectType,
155    LV_IncompleteVoidType,
156    LV_DuplicateVectorComponents,
157    LV_InvalidExpression,
158    LV_MemberFunction,
159    LV_SubObjCPropertySetting,
160    LV_ClassTemporary
161  };
162  isLvalueResult isLvalue(ASTContext &Ctx) const;
163
164  // Same as above, but excluding checks for non-object and void types in C
165  isLvalueResult isLvalueInternal(ASTContext &Ctx) const;
166
167  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
168  /// does not have an incomplete type, does not have a const-qualified type,
169  /// and if it is a structure or union, does not have any member (including,
170  /// recursively, any member or element of all contained aggregates or unions)
171  /// with a const-qualified type.
172  ///
173  /// \param Loc [in] [out] - A source location which *may* be filled
174  /// in with the location of the expression making this a
175  /// non-modifiable lvalue, if specified.
176  enum isModifiableLvalueResult {
177    MLV_Valid,
178    MLV_NotObjectType,
179    MLV_IncompleteVoidType,
180    MLV_DuplicateVectorComponents,
181    MLV_InvalidExpression,
182    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
183    MLV_IncompleteType,
184    MLV_ConstQualified,
185    MLV_ArrayType,
186    MLV_NotBlockQualified,
187    MLV_ReadonlyProperty,
188    MLV_NoSetterProperty,
189    MLV_MemberFunction,
190    MLV_SubObjCPropertySetting,
191    MLV_ClassTemporary
192  };
193  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
194                                              SourceLocation *Loc = 0) const;
195
196  /// \brief If this expression refers to a bit-field, retrieve the
197  /// declaration of that bit-field.
198  FieldDecl *getBitField();
199
200  const FieldDecl *getBitField() const {
201    return const_cast<Expr*>(this)->getBitField();
202  }
203
204  /// \brief Returns whether this expression refers to a vector element.
205  bool refersToVectorElement() const;
206
207  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
208  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
209  /// but also int expressions which are produced by things like comparisons in
210  /// C.
211  bool isKnownToHaveBooleanValue() const;
212
213  /// isIntegerConstantExpr - Return true if this expression is a valid integer
214  /// constant expression, and, if so, return its value in Result.  If not a
215  /// valid i-c-e, return false and fill in Loc (if specified) with the location
216  /// of the invalid expression.
217  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
218                             SourceLocation *Loc = 0,
219                             bool isEvaluated = true) const;
220  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
221    llvm::APSInt X;
222    return isIntegerConstantExpr(X, Ctx, Loc);
223  }
224  /// isConstantInitializer - Returns true if this expression is a constant
225  /// initializer, which can be emitted at compile-time.
226  bool isConstantInitializer(ASTContext &Ctx) const;
227
228  /// EvalResult is a struct with detailed info about an evaluated expression.
229  struct EvalResult {
230    /// Val - This is the value the expression can be folded to.
231    APValue Val;
232
233    /// HasSideEffects - Whether the evaluated expression has side effects.
234    /// For example, (f() && 0) can be folded, but it still has side effects.
235    bool HasSideEffects;
236
237    /// Diag - If the expression is unfoldable, then Diag contains a note
238    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
239    /// position for the error, and DiagExpr is the expression that caused
240    /// the error.
241    /// If the expression is foldable, but not an integer constant expression,
242    /// Diag contains a note diagnostic that describes why it isn't an integer
243    /// constant expression. If the expression *is* an integer constant
244    /// expression, then Diag will be zero.
245    unsigned Diag;
246    const Expr *DiagExpr;
247    SourceLocation DiagLoc;
248
249    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
250  };
251
252  /// Evaluate - Return true if this is a constant which we can fold using
253  /// any crazy technique (that has nothing to do with language standards) that
254  /// we want to.  If this function returns true, it returns the folded constant
255  /// in Result.
256  bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
257
258  /// EvaluateAsAny - The same as Evaluate, except that it also succeeds on
259  /// stack based objects.
260  bool EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const;
261
262  /// EvaluateAsBooleanCondition - Return true if this is a constant
263  /// which we we can fold and convert to a boolean condition using
264  /// any crazy technique that we want to.
265  bool EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const;
266
267  /// isEvaluatable - Call Evaluate to see if this expression can be constant
268  /// folded, but discard the result.
269  bool isEvaluatable(ASTContext &Ctx) const;
270
271  /// HasSideEffects - This routine returns true for all those expressions
272  /// which must be evaluated each time and must not be optimization away
273  /// or evaluated at compile time. Example is a function call, volatile
274  /// variable read.
275  bool HasSideEffects(ASTContext &Ctx) const;
276
277  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
278  /// must be called on an expression that constant folds to an integer.
279  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
280
281  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
282  /// with link time known address.
283  bool EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const;
284
285  /// EvaluateAsAnyLValue - The same as EvaluateAsLValue, except that it
286  /// also succeeds on stack based, immutable address lvalues.
287  bool EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const;
288
289  /// \brief Enumeration used to describe how \c isNullPointerConstant()
290  /// should cope with value-dependent expressions.
291  enum NullPointerConstantValueDependence {
292    /// \brief Specifies that the expression should never be value-dependent.
293    NPC_NeverValueDependent = 0,
294
295    /// \brief Specifies that a value-dependent expression of integral or
296    /// dependent type should be considered a null pointer constant.
297    NPC_ValueDependentIsNull,
298
299    /// \brief Specifies that a value-dependent expression should be considered
300    /// to never be a null pointer constant.
301    NPC_ValueDependentIsNotNull
302  };
303
304  /// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
305  /// integer constant expression with the value zero, or if this is one that is
306  /// cast to void*.
307  bool isNullPointerConstant(ASTContext &Ctx,
308                             NullPointerConstantValueDependence NPC) const;
309
310  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
311  /// write barrier.
312  bool isOBJCGCCandidate(ASTContext &Ctx) const;
313
314  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
315  ///  its subexpression.  If that subexpression is also a ParenExpr,
316  ///  then this method recursively returns its subexpression, and so forth.
317  ///  Otherwise, the method returns the current Expr.
318  Expr *IgnoreParens();
319
320  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
321  /// or CastExprs, returning their operand.
322  Expr *IgnoreParenCasts();
323
324  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
325  /// value (including ptr->int casts of the same size).  Strip off any
326  /// ParenExpr or CastExprs, returning their operand.
327  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
328
329  /// \brief Determine whether this expression is a default function argument.
330  ///
331  /// Default arguments are implicitly generated in the abstract syntax tree
332  /// by semantic analysis for function calls, object constructions, etc. in
333  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
334  /// this routine also looks through any implicit casts to determine whether
335  /// the expression is a default argument.
336  bool isDefaultArgument() const;
337
338  /// \brief Determine whether this expression directly creates a
339  /// temporary object (of class type).
340  bool isTemporaryObject() const { return getTemporaryObject() != 0; }
341
342  /// \brief If this expression directly creates a temporary object of
343  /// class type, return the expression that actually constructs that
344  /// temporary object.
345  const Expr *getTemporaryObject() const;
346
347  const Expr *IgnoreParens() const {
348    return const_cast<Expr*>(this)->IgnoreParens();
349  }
350  const Expr *IgnoreParenCasts() const {
351    return const_cast<Expr*>(this)->IgnoreParenCasts();
352  }
353  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
354    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
355  }
356
357  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
358  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
359
360  static bool classof(const Stmt *T) {
361    return T->getStmtClass() >= firstExprConstant &&
362           T->getStmtClass() <= lastExprConstant;
363  }
364  static bool classof(const Expr *) { return true; }
365};
366
367
368//===----------------------------------------------------------------------===//
369// Primary Expressions.
370//===----------------------------------------------------------------------===//
371
372/// \brief Represents the qualifier that may precede a C++ name, e.g., the
373/// "std::" in "std::sort".
374struct NameQualifier {
375  /// \brief The nested name specifier.
376  NestedNameSpecifier *NNS;
377
378  /// \brief The source range covered by the nested name specifier.
379  SourceRange Range;
380};
381
382/// \brief Represents an explicit template argument list in C++, e.g.,
383/// the "<int>" in "sort<int>".
384struct ExplicitTemplateArgumentList {
385  /// \brief The source location of the left angle bracket ('<');
386  SourceLocation LAngleLoc;
387
388  /// \brief The source location of the right angle bracket ('>');
389  SourceLocation RAngleLoc;
390
391  /// \brief The number of template arguments in TemplateArgs.
392  /// The actual template arguments (if any) are stored after the
393  /// ExplicitTemplateArgumentList structure.
394  unsigned NumTemplateArgs;
395
396  /// \brief Retrieve the template arguments
397  TemplateArgumentLoc *getTemplateArgs() {
398    return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
399  }
400
401  /// \brief Retrieve the template arguments
402  const TemplateArgumentLoc *getTemplateArgs() const {
403    return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
404  }
405
406  void initializeFrom(const TemplateArgumentListInfo &List);
407  void copyInto(TemplateArgumentListInfo &List) const;
408  static std::size_t sizeFor(const TemplateArgumentListInfo &List);
409};
410
411/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
412/// enum, etc.
413class DeclRefExpr : public Expr {
414  enum {
415    // Flag on DecoratedD that specifies when this declaration reference
416    // expression has a C++ nested-name-specifier.
417    HasQualifierFlag = 0x01,
418    // Flag on DecoratedD that specifies when this declaration reference
419    // expression has an explicit C++ template argument list.
420    HasExplicitTemplateArgumentListFlag = 0x02
421  };
422
423  // DecoratedD - The declaration that we are referencing, plus two bits to
424  // indicate whether (1) the declaration's name was explicitly qualified and
425  // (2) the declaration's name was followed by an explicit template
426  // argument list.
427  llvm::PointerIntPair<ValueDecl *, 2> DecoratedD;
428
429  // Loc - The location of the declaration name itself.
430  SourceLocation Loc;
431
432  /// \brief Retrieve the qualifier that preceded the declaration name, if any.
433  NameQualifier *getNameQualifier() {
434    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
435      return 0;
436
437    return reinterpret_cast<NameQualifier *> (this + 1);
438  }
439
440  /// \brief Retrieve the qualifier that preceded the member name, if any.
441  const NameQualifier *getNameQualifier() const {
442    return const_cast<DeclRefExpr *>(this)->getNameQualifier();
443  }
444
445  /// \brief Retrieve the explicit template argument list that followed the
446  /// member template name, if any.
447  ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() {
448    if ((DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag) == 0)
449      return 0;
450
451    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
452      return reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
453
454    return reinterpret_cast<ExplicitTemplateArgumentList *>(
455                                                      getNameQualifier() + 1);
456  }
457
458  /// \brief Retrieve the explicit template argument list that followed the
459  /// member template name, if any.
460  const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const {
461    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgumentList();
462  }
463
464  DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange,
465              ValueDecl *D, SourceLocation NameLoc,
466              const TemplateArgumentListInfo *TemplateArgs,
467              QualType T);
468
469protected:
470  /// \brief Computes the type- and value-dependence flags for this
471  /// declaration reference expression.
472  void computeDependence();
473
474  DeclRefExpr(StmtClass SC, ValueDecl *d, QualType t, SourceLocation l) :
475    Expr(SC, t, false, false), DecoratedD(d, 0), Loc(l) {
476    computeDependence();
477  }
478
479public:
480  DeclRefExpr(ValueDecl *d, QualType t, SourceLocation l) :
481    Expr(DeclRefExprClass, t, false, false), DecoratedD(d, 0), Loc(l) {
482    computeDependence();
483  }
484
485  /// \brief Construct an empty declaration reference expression.
486  explicit DeclRefExpr(EmptyShell Empty)
487    : Expr(DeclRefExprClass, Empty) { }
488
489  static DeclRefExpr *Create(ASTContext &Context,
490                             NestedNameSpecifier *Qualifier,
491                             SourceRange QualifierRange,
492                             ValueDecl *D,
493                             SourceLocation NameLoc,
494                             QualType T,
495                             const TemplateArgumentListInfo *TemplateArgs = 0);
496
497  ValueDecl *getDecl() { return DecoratedD.getPointer(); }
498  const ValueDecl *getDecl() const { return DecoratedD.getPointer(); }
499  void setDecl(ValueDecl *NewD) { DecoratedD.setPointer(NewD); }
500
501  SourceLocation getLocation() const { return Loc; }
502  void setLocation(SourceLocation L) { Loc = L; }
503  virtual SourceRange getSourceRange() const;
504
505  /// \brief Determine whether this declaration reference was preceded by a
506  /// C++ nested-name-specifier, e.g., \c N::foo.
507  bool hasQualifier() const { return DecoratedD.getInt() & HasQualifierFlag; }
508
509  /// \brief If the name was qualified, retrieves the source range of
510  /// the nested-name-specifier that precedes the name. Otherwise,
511  /// returns an empty source range.
512  SourceRange getQualifierRange() const {
513    if (!hasQualifier())
514      return SourceRange();
515
516    return getNameQualifier()->Range;
517  }
518
519  /// \brief If the name was qualified, retrieves the nested-name-specifier
520  /// that precedes the name. Otherwise, returns NULL.
521  NestedNameSpecifier *getQualifier() const {
522    if (!hasQualifier())
523      return 0;
524
525    return getNameQualifier()->NNS;
526  }
527
528  /// \brief Determines whether this member expression actually had a C++
529  /// template argument list explicitly specified, e.g., x.f<int>.
530  bool hasExplicitTemplateArgumentList() const {
531    return DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag;
532  }
533
534  /// \brief Copies the template arguments (if present) into the given
535  /// structure.
536  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
537    if (hasExplicitTemplateArgumentList())
538      getExplicitTemplateArgumentList()->copyInto(List);
539  }
540
541  /// \brief Retrieve the location of the left angle bracket following the
542  /// member name ('<'), if any.
543  SourceLocation getLAngleLoc() const {
544    if (!hasExplicitTemplateArgumentList())
545      return SourceLocation();
546
547    return getExplicitTemplateArgumentList()->LAngleLoc;
548  }
549
550  /// \brief Retrieve the template arguments provided as part of this
551  /// template-id.
552  const TemplateArgumentLoc *getTemplateArgs() const {
553    if (!hasExplicitTemplateArgumentList())
554      return 0;
555
556    return getExplicitTemplateArgumentList()->getTemplateArgs();
557  }
558
559  /// \brief Retrieve the number of template arguments provided as part of this
560  /// template-id.
561  unsigned getNumTemplateArgs() const {
562    if (!hasExplicitTemplateArgumentList())
563      return 0;
564
565    return getExplicitTemplateArgumentList()->NumTemplateArgs;
566  }
567
568  /// \brief Retrieve the location of the right angle bracket following the
569  /// template arguments ('>').
570  SourceLocation getRAngleLoc() const {
571    if (!hasExplicitTemplateArgumentList())
572      return SourceLocation();
573
574    return getExplicitTemplateArgumentList()->RAngleLoc;
575  }
576
577  static bool classof(const Stmt *T) {
578    return T->getStmtClass() == DeclRefExprClass;
579  }
580  static bool classof(const DeclRefExpr *) { return true; }
581
582  // Iterators
583  virtual child_iterator child_begin();
584  virtual child_iterator child_end();
585};
586
587/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
588class PredefinedExpr : public Expr {
589public:
590  enum IdentType {
591    Func,
592    Function,
593    PrettyFunction,
594    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
595    /// 'virtual' keyword is omitted for virtual member functions.
596    PrettyFunctionNoVirtual
597  };
598
599private:
600  SourceLocation Loc;
601  IdentType Type;
602public:
603  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
604    : Expr(PredefinedExprClass, type, type->isDependentType(),
605           type->isDependentType()), Loc(l), Type(IT) {}
606
607  /// \brief Construct an empty predefined expression.
608  explicit PredefinedExpr(EmptyShell Empty)
609    : Expr(PredefinedExprClass, Empty) { }
610
611  IdentType getIdentType() const { return Type; }
612  void setIdentType(IdentType IT) { Type = IT; }
613
614  SourceLocation getLocation() const { return Loc; }
615  void setLocation(SourceLocation L) { Loc = L; }
616
617  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
618
619  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
620
621  static bool classof(const Stmt *T) {
622    return T->getStmtClass() == PredefinedExprClass;
623  }
624  static bool classof(const PredefinedExpr *) { return true; }
625
626  // Iterators
627  virtual child_iterator child_begin();
628  virtual child_iterator child_end();
629};
630
631class IntegerLiteral : public Expr {
632  llvm::APInt Value;
633  SourceLocation Loc;
634public:
635  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
636  // or UnsignedLongLongTy
637  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
638    : Expr(IntegerLiteralClass, type, false, false), Value(V), Loc(l) {
639    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
640  }
641
642  /// \brief Construct an empty integer literal.
643  explicit IntegerLiteral(EmptyShell Empty)
644    : Expr(IntegerLiteralClass, Empty) { }
645
646  const llvm::APInt &getValue() const { return Value; }
647  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
648
649  /// \brief Retrieve the location of the literal.
650  SourceLocation getLocation() const { return Loc; }
651
652  void setValue(const llvm::APInt &Val) { Value = Val; }
653  void setLocation(SourceLocation Location) { Loc = Location; }
654
655  static bool classof(const Stmt *T) {
656    return T->getStmtClass() == IntegerLiteralClass;
657  }
658  static bool classof(const IntegerLiteral *) { return true; }
659
660  // Iterators
661  virtual child_iterator child_begin();
662  virtual child_iterator child_end();
663};
664
665class CharacterLiteral : public Expr {
666  unsigned Value;
667  SourceLocation Loc;
668  bool IsWide;
669public:
670  // type should be IntTy
671  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
672    : Expr(CharacterLiteralClass, type, false, false), Value(value), Loc(l),
673      IsWide(iswide) {
674  }
675
676  /// \brief Construct an empty character literal.
677  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
678
679  SourceLocation getLocation() const { return Loc; }
680  bool isWide() const { return IsWide; }
681
682  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
683
684  unsigned getValue() const { return Value; }
685
686  void setLocation(SourceLocation Location) { Loc = Location; }
687  void setWide(bool W) { IsWide = W; }
688  void setValue(unsigned Val) { Value = Val; }
689
690  static bool classof(const Stmt *T) {
691    return T->getStmtClass() == CharacterLiteralClass;
692  }
693  static bool classof(const CharacterLiteral *) { return true; }
694
695  // Iterators
696  virtual child_iterator child_begin();
697  virtual child_iterator child_end();
698};
699
700class FloatingLiteral : public Expr {
701  llvm::APFloat Value;
702  bool IsExact : 1;
703  SourceLocation Loc;
704public:
705  FloatingLiteral(const llvm::APFloat &V, bool isexact,
706                  QualType Type, SourceLocation L)
707    : Expr(FloatingLiteralClass, Type, false, false), Value(V),
708      IsExact(isexact), Loc(L) {}
709
710  /// \brief Construct an empty floating-point literal.
711  explicit FloatingLiteral(EmptyShell Empty)
712    : Expr(FloatingLiteralClass, Empty), Value(0.0) { }
713
714  const llvm::APFloat &getValue() const { return Value; }
715  void setValue(const llvm::APFloat &Val) { Value = Val; }
716
717  bool isExact() const { return IsExact; }
718  void setExact(bool E) { IsExact = E; }
719
720  /// getValueAsApproximateDouble - This returns the value as an inaccurate
721  /// double.  Note that this may cause loss of precision, but is useful for
722  /// debugging dumps, etc.
723  double getValueAsApproximateDouble() const;
724
725  SourceLocation getLocation() const { return Loc; }
726  void setLocation(SourceLocation L) { Loc = L; }
727
728  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
729
730  static bool classof(const Stmt *T) {
731    return T->getStmtClass() == FloatingLiteralClass;
732  }
733  static bool classof(const FloatingLiteral *) { return true; }
734
735  // Iterators
736  virtual child_iterator child_begin();
737  virtual child_iterator child_end();
738};
739
740/// ImaginaryLiteral - We support imaginary integer and floating point literals,
741/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
742/// IntegerLiteral classes.  Instances of this class always have a Complex type
743/// whose element type matches the subexpression.
744///
745class ImaginaryLiteral : public Expr {
746  Stmt *Val;
747public:
748  ImaginaryLiteral(Expr *val, QualType Ty)
749    : Expr(ImaginaryLiteralClass, Ty, false, false), Val(val) {}
750
751  /// \brief Build an empty imaginary literal.
752  explicit ImaginaryLiteral(EmptyShell Empty)
753    : Expr(ImaginaryLiteralClass, Empty) { }
754
755  const Expr *getSubExpr() const { return cast<Expr>(Val); }
756  Expr *getSubExpr() { return cast<Expr>(Val); }
757  void setSubExpr(Expr *E) { Val = E; }
758
759  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
760  static bool classof(const Stmt *T) {
761    return T->getStmtClass() == ImaginaryLiteralClass;
762  }
763  static bool classof(const ImaginaryLiteral *) { return true; }
764
765  // Iterators
766  virtual child_iterator child_begin();
767  virtual child_iterator child_end();
768};
769
770/// StringLiteral - This represents a string literal expression, e.g. "foo"
771/// or L"bar" (wide strings).  The actual string is returned by getStrData()
772/// is NOT null-terminated, and the length of the string is determined by
773/// calling getByteLength().  The C type for a string is always a
774/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
775/// not.
776///
777/// Note that strings in C can be formed by concatenation of multiple string
778/// literal pptokens in translation phase #6.  This keeps track of the locations
779/// of each of these pieces.
780///
781/// Strings in C can also be truncated and extended by assigning into arrays,
782/// e.g. with constructs like:
783///   char X[2] = "foobar";
784/// In this case, getByteLength() will return 6, but the string literal will
785/// have type "char[2]".
786class StringLiteral : public Expr {
787  const char *StrData;
788  unsigned ByteLength;
789  bool IsWide;
790  unsigned NumConcatenated;
791  SourceLocation TokLocs[1];
792
793  StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty, false, false) {}
794
795protected:
796  virtual void DoDestroy(ASTContext &C);
797
798public:
799  /// This is the "fully general" constructor that allows representation of
800  /// strings formed from multiple concatenated tokens.
801  static StringLiteral *Create(ASTContext &C, const char *StrData,
802                               unsigned ByteLength, bool Wide, QualType Ty,
803                               const SourceLocation *Loc, unsigned NumStrs);
804
805  /// Simple constructor for string literals made from one token.
806  static StringLiteral *Create(ASTContext &C, const char *StrData,
807                               unsigned ByteLength,
808                               bool Wide, QualType Ty, SourceLocation Loc) {
809    return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
810  }
811
812  /// \brief Construct an empty string literal.
813  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
814
815  llvm::StringRef getString() const {
816    return llvm::StringRef(StrData, ByteLength);
817  }
818  // FIXME: These are deprecated, replace with StringRef.
819  const char *getStrData() const { return StrData; }
820  unsigned getByteLength() const { return ByteLength; }
821
822  /// \brief Sets the string data to the given string data.
823  void setString(ASTContext &C, llvm::StringRef Str);
824
825  bool isWide() const { return IsWide; }
826  void setWide(bool W) { IsWide = W; }
827
828  bool containsNonAsciiOrNull() const {
829    llvm::StringRef Str = getString();
830    for (unsigned i = 0, e = Str.size(); i != e; ++i)
831      if (!isascii(Str[i]) || !Str[i])
832        return true;
833    return false;
834  }
835  /// getNumConcatenated - Get the number of string literal tokens that were
836  /// concatenated in translation phase #6 to form this string literal.
837  unsigned getNumConcatenated() const { return NumConcatenated; }
838
839  SourceLocation getStrTokenLoc(unsigned TokNum) const {
840    assert(TokNum < NumConcatenated && "Invalid tok number");
841    return TokLocs[TokNum];
842  }
843  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
844    assert(TokNum < NumConcatenated && "Invalid tok number");
845    TokLocs[TokNum] = L;
846  }
847
848  typedef const SourceLocation *tokloc_iterator;
849  tokloc_iterator tokloc_begin() const { return TokLocs; }
850  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
851
852  virtual SourceRange getSourceRange() const {
853    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
854  }
855  static bool classof(const Stmt *T) {
856    return T->getStmtClass() == StringLiteralClass;
857  }
858  static bool classof(const StringLiteral *) { return true; }
859
860  // Iterators
861  virtual child_iterator child_begin();
862  virtual child_iterator child_end();
863};
864
865/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
866/// AST node is only formed if full location information is requested.
867class ParenExpr : public Expr {
868  SourceLocation L, R;
869  Stmt *Val;
870public:
871  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
872    : Expr(ParenExprClass, val->getType(),
873           val->isTypeDependent(), val->isValueDependent()),
874      L(l), R(r), Val(val) {}
875
876  /// \brief Construct an empty parenthesized expression.
877  explicit ParenExpr(EmptyShell Empty)
878    : Expr(ParenExprClass, Empty) { }
879
880  const Expr *getSubExpr() const { return cast<Expr>(Val); }
881  Expr *getSubExpr() { return cast<Expr>(Val); }
882  void setSubExpr(Expr *E) { Val = E; }
883
884  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
885
886  /// \brief Get the location of the left parentheses '('.
887  SourceLocation getLParen() const { return L; }
888  void setLParen(SourceLocation Loc) { L = Loc; }
889
890  /// \brief Get the location of the right parentheses ')'.
891  SourceLocation getRParen() const { return R; }
892  void setRParen(SourceLocation Loc) { R = Loc; }
893
894  static bool classof(const Stmt *T) {
895    return T->getStmtClass() == ParenExprClass;
896  }
897  static bool classof(const ParenExpr *) { return true; }
898
899  // Iterators
900  virtual child_iterator child_begin();
901  virtual child_iterator child_end();
902};
903
904
905/// UnaryOperator - This represents the unary-expression's (except sizeof and
906/// alignof), the postinc/postdec operators from postfix-expression, and various
907/// extensions.
908///
909/// Notes on various nodes:
910///
911/// Real/Imag - These return the real/imag part of a complex operand.  If
912///   applied to a non-complex value, the former returns its operand and the
913///   later returns zero in the type of the operand.
914///
915/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
916///   subexpression is a compound literal with the various MemberExpr and
917///   ArraySubscriptExpr's applied to it.
918///
919class UnaryOperator : public Expr {
920public:
921  // Note that additions to this should also update the StmtVisitor class.
922  enum Opcode {
923    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
924    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
925    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
926    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
927    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
928    Real, Imag,       // "__real expr"/"__imag expr" Extension.
929    Extension,        // __extension__ marker.
930    OffsetOf          // __builtin_offsetof
931  };
932private:
933  Stmt *Val;
934  Opcode Opc;
935  SourceLocation Loc;
936public:
937
938  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
939    : Expr(UnaryOperatorClass, type,
940           input->isTypeDependent() && opc != OffsetOf,
941           input->isValueDependent()),
942      Val(input), Opc(opc), Loc(l) {}
943
944  /// \brief Build an empty unary operator.
945  explicit UnaryOperator(EmptyShell Empty)
946    : Expr(UnaryOperatorClass, Empty), Opc(AddrOf) { }
947
948  Opcode getOpcode() const { return Opc; }
949  void setOpcode(Opcode O) { Opc = O; }
950
951  Expr *getSubExpr() const { return cast<Expr>(Val); }
952  void setSubExpr(Expr *E) { Val = E; }
953
954  /// getOperatorLoc - Return the location of the operator.
955  SourceLocation getOperatorLoc() const { return Loc; }
956  void setOperatorLoc(SourceLocation L) { Loc = L; }
957
958  /// isPostfix - Return true if this is a postfix operation, like x++.
959  static bool isPostfix(Opcode Op) {
960    return Op == PostInc || Op == PostDec;
961  }
962
963  /// isPostfix - Return true if this is a prefix operation, like --x.
964  static bool isPrefix(Opcode Op) {
965    return Op == PreInc || Op == PreDec;
966  }
967
968  bool isPrefix() const { return isPrefix(Opc); }
969  bool isPostfix() const { return isPostfix(Opc); }
970  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
971  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
972  bool isOffsetOfOp() const { return Opc == OffsetOf; }
973  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
974  bool isArithmeticOp() const { return isArithmeticOp(Opc); }
975
976  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
977  /// corresponds to, e.g. "sizeof" or "[pre]++"
978  static const char *getOpcodeStr(Opcode Op);
979
980  /// \brief Retrieve the unary opcode that corresponds to the given
981  /// overloaded operator.
982  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
983
984  /// \brief Retrieve the overloaded operator kind that corresponds to
985  /// the given unary opcode.
986  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
987
988  virtual SourceRange getSourceRange() const {
989    if (isPostfix())
990      return SourceRange(Val->getLocStart(), Loc);
991    else
992      return SourceRange(Loc, Val->getLocEnd());
993  }
994  virtual SourceLocation getExprLoc() const { return Loc; }
995
996  static bool classof(const Stmt *T) {
997    return T->getStmtClass() == UnaryOperatorClass;
998  }
999  static bool classof(const UnaryOperator *) { return true; }
1000
1001  // Iterators
1002  virtual child_iterator child_begin();
1003  virtual child_iterator child_end();
1004};
1005
1006/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
1007/// types and expressions.
1008class SizeOfAlignOfExpr : public Expr {
1009  bool isSizeof : 1;  // true if sizeof, false if alignof.
1010  bool isType : 1;    // true if operand is a type, false if an expression
1011  union {
1012    TypeSourceInfo *Ty;
1013    Stmt *Ex;
1014  } Argument;
1015  SourceLocation OpLoc, RParenLoc;
1016
1017protected:
1018  virtual void DoDestroy(ASTContext& C);
1019
1020public:
1021  SizeOfAlignOfExpr(bool issizeof, TypeSourceInfo *TInfo,
1022                    QualType resultType, SourceLocation op,
1023                    SourceLocation rp) :
1024      Expr(SizeOfAlignOfExprClass, resultType,
1025           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1026           // Value-dependent if the argument is type-dependent.
1027           TInfo->getType()->isDependentType()),
1028      isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) {
1029    Argument.Ty = TInfo;
1030  }
1031
1032  SizeOfAlignOfExpr(bool issizeof, Expr *E,
1033                    QualType resultType, SourceLocation op,
1034                    SourceLocation rp) :
1035      Expr(SizeOfAlignOfExprClass, resultType,
1036           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1037           // Value-dependent if the argument is type-dependent.
1038           E->isTypeDependent()),
1039      isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) {
1040    Argument.Ex = E;
1041  }
1042
1043  /// \brief Construct an empty sizeof/alignof expression.
1044  explicit SizeOfAlignOfExpr(EmptyShell Empty)
1045    : Expr(SizeOfAlignOfExprClass, Empty) { }
1046
1047  bool isSizeOf() const { return isSizeof; }
1048  void setSizeof(bool S) { isSizeof = S; }
1049
1050  bool isArgumentType() const { return isType; }
1051  QualType getArgumentType() const {
1052    return getArgumentTypeInfo()->getType();
1053  }
1054  TypeSourceInfo *getArgumentTypeInfo() const {
1055    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1056    return Argument.Ty;
1057  }
1058  Expr *getArgumentExpr() {
1059    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1060    return static_cast<Expr*>(Argument.Ex);
1061  }
1062  const Expr *getArgumentExpr() const {
1063    return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
1064  }
1065
1066  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1067  void setArgument(TypeSourceInfo *TInfo) {
1068    Argument.Ty = TInfo;
1069    isType = true;
1070  }
1071
1072  /// Gets the argument type, or the type of the argument expression, whichever
1073  /// is appropriate.
1074  QualType getTypeOfArgument() const {
1075    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1076  }
1077
1078  SourceLocation getOperatorLoc() const { return OpLoc; }
1079  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1080
1081  SourceLocation getRParenLoc() const { return RParenLoc; }
1082  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1083
1084  virtual SourceRange getSourceRange() const {
1085    return SourceRange(OpLoc, RParenLoc);
1086  }
1087
1088  static bool classof(const Stmt *T) {
1089    return T->getStmtClass() == SizeOfAlignOfExprClass;
1090  }
1091  static bool classof(const SizeOfAlignOfExpr *) { return true; }
1092
1093  // Iterators
1094  virtual child_iterator child_begin();
1095  virtual child_iterator child_end();
1096};
1097
1098//===----------------------------------------------------------------------===//
1099// Postfix Operators.
1100//===----------------------------------------------------------------------===//
1101
1102/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1103class ArraySubscriptExpr : public Expr {
1104  enum { LHS, RHS, END_EXPR=2 };
1105  Stmt* SubExprs[END_EXPR];
1106  SourceLocation RBracketLoc;
1107public:
1108  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1109                     SourceLocation rbracketloc)
1110  : Expr(ArraySubscriptExprClass, t,
1111         lhs->isTypeDependent() || rhs->isTypeDependent(),
1112         lhs->isValueDependent() || rhs->isValueDependent()),
1113    RBracketLoc(rbracketloc) {
1114    SubExprs[LHS] = lhs;
1115    SubExprs[RHS] = rhs;
1116  }
1117
1118  /// \brief Create an empty array subscript expression.
1119  explicit ArraySubscriptExpr(EmptyShell Shell)
1120    : Expr(ArraySubscriptExprClass, Shell) { }
1121
1122  /// An array access can be written A[4] or 4[A] (both are equivalent).
1123  /// - getBase() and getIdx() always present the normalized view: A[4].
1124  ///    In this case getBase() returns "A" and getIdx() returns "4".
1125  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1126  ///    4[A] getLHS() returns "4".
1127  /// Note: Because vector element access is also written A[4] we must
1128  /// predicate the format conversion in getBase and getIdx only on the
1129  /// the type of the RHS, as it is possible for the LHS to be a vector of
1130  /// integer type
1131  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1132  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1133  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1134
1135  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1136  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1137  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1138
1139  Expr *getBase() {
1140    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1141  }
1142
1143  const Expr *getBase() const {
1144    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1145  }
1146
1147  Expr *getIdx() {
1148    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1149  }
1150
1151  const Expr *getIdx() const {
1152    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1153  }
1154
1155  virtual SourceRange getSourceRange() const {
1156    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1157  }
1158
1159  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1160  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1161
1162  virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1163
1164  static bool classof(const Stmt *T) {
1165    return T->getStmtClass() == ArraySubscriptExprClass;
1166  }
1167  static bool classof(const ArraySubscriptExpr *) { return true; }
1168
1169  // Iterators
1170  virtual child_iterator child_begin();
1171  virtual child_iterator child_end();
1172};
1173
1174
1175/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1176/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1177/// while its subclasses may represent alternative syntax that (semantically)
1178/// results in a function call. For example, CXXOperatorCallExpr is
1179/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1180/// "str1 + str2" to resolve to a function call.
1181class CallExpr : public Expr {
1182  enum { FN=0, ARGS_START=1 };
1183  Stmt **SubExprs;
1184  unsigned NumArgs;
1185  SourceLocation RParenLoc;
1186
1187protected:
1188  // This version of the constructor is for derived classes.
1189  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs,
1190           QualType t, SourceLocation rparenloc);
1191
1192  virtual void DoDestroy(ASTContext& C);
1193
1194public:
1195  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1196           SourceLocation rparenloc);
1197
1198  /// \brief Build an empty call expression.
1199  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1200
1201  ~CallExpr() {}
1202
1203  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1204  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1205  void setCallee(Expr *F) { SubExprs[FN] = F; }
1206
1207  Decl *getCalleeDecl();
1208  const Decl *getCalleeDecl() const {
1209    return const_cast<CallExpr*>(this)->getCalleeDecl();
1210  }
1211
1212  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1213  FunctionDecl *getDirectCallee();
1214  const FunctionDecl *getDirectCallee() const {
1215    return const_cast<CallExpr*>(this)->getDirectCallee();
1216  }
1217
1218  /// getNumArgs - Return the number of actual arguments to this call.
1219  ///
1220  unsigned getNumArgs() const { return NumArgs; }
1221
1222  /// getArg - Return the specified argument.
1223  Expr *getArg(unsigned Arg) {
1224    assert(Arg < NumArgs && "Arg access out of range!");
1225    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1226  }
1227  const Expr *getArg(unsigned Arg) const {
1228    assert(Arg < NumArgs && "Arg access out of range!");
1229    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1230  }
1231
1232  /// setArg - Set the specified argument.
1233  void setArg(unsigned Arg, Expr *ArgExpr) {
1234    assert(Arg < NumArgs && "Arg access out of range!");
1235    SubExprs[Arg+ARGS_START] = ArgExpr;
1236  }
1237
1238  /// setNumArgs - This changes the number of arguments present in this call.
1239  /// Any orphaned expressions are deleted by this, and any new operands are set
1240  /// to null.
1241  void setNumArgs(ASTContext& C, unsigned NumArgs);
1242
1243  typedef ExprIterator arg_iterator;
1244  typedef ConstExprIterator const_arg_iterator;
1245
1246  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
1247  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
1248  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
1249  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
1250
1251  /// getNumCommas - Return the number of commas that must have been present in
1252  /// this function call.
1253  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1254
1255  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1256  /// not, return 0.
1257  unsigned isBuiltinCall(ASTContext &Context) const;
1258
1259  /// getCallReturnType - Get the return type of the call expr. This is not
1260  /// always the type of the expr itself, if the return type is a reference
1261  /// type.
1262  QualType getCallReturnType() const;
1263
1264  SourceLocation getRParenLoc() const { return RParenLoc; }
1265  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1266
1267  virtual SourceRange getSourceRange() const {
1268    return SourceRange(getCallee()->getLocStart(), RParenLoc);
1269  }
1270
1271  static bool classof(const Stmt *T) {
1272    return T->getStmtClass() == CallExprClass ||
1273           T->getStmtClass() == CXXOperatorCallExprClass ||
1274           T->getStmtClass() == CXXMemberCallExprClass;
1275  }
1276  static bool classof(const CallExpr *) { return true; }
1277  static bool classof(const CXXOperatorCallExpr *) { return true; }
1278  static bool classof(const CXXMemberCallExpr *) { return true; }
1279
1280  // Iterators
1281  virtual child_iterator child_begin();
1282  virtual child_iterator child_end();
1283};
1284
1285/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1286///
1287class MemberExpr : public Expr {
1288  /// Extra data stored in some member expressions.
1289  struct MemberNameQualifier : public NameQualifier {
1290    DeclAccessPair FoundDecl;
1291  };
1292
1293  /// Base - the expression for the base pointer or structure references.  In
1294  /// X.F, this is "X".
1295  Stmt *Base;
1296
1297  /// MemberDecl - This is the decl being referenced by the field/member name.
1298  /// In X.F, this is the decl referenced by F.
1299  ValueDecl *MemberDecl;
1300
1301  /// MemberLoc - This is the location of the member name.
1302  SourceLocation MemberLoc;
1303
1304  /// IsArrow - True if this is "X->F", false if this is "X.F".
1305  bool IsArrow : 1;
1306
1307  /// \brief True if this member expression used a nested-name-specifier to
1308  /// refer to the member, e.g., "x->Base::f", or found its member via a using
1309  /// declaration.  When true, a MemberNameQualifier
1310  /// structure is allocated immediately after the MemberExpr.
1311  bool HasQualifierOrFoundDecl : 1;
1312
1313  /// \brief True if this member expression specified a template argument list
1314  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
1315  /// structure (and its TemplateArguments) are allocated immediately after
1316  /// the MemberExpr or, if the member expression also has a qualifier, after
1317  /// the MemberNameQualifier structure.
1318  bool HasExplicitTemplateArgumentList : 1;
1319
1320  /// \brief Retrieve the qualifier that preceded the member name, if any.
1321  MemberNameQualifier *getMemberQualifier() {
1322    assert(HasQualifierOrFoundDecl);
1323    return reinterpret_cast<MemberNameQualifier *> (this + 1);
1324  }
1325
1326  /// \brief Retrieve the qualifier that preceded the member name, if any.
1327  const MemberNameQualifier *getMemberQualifier() const {
1328    return const_cast<MemberExpr *>(this)->getMemberQualifier();
1329  }
1330
1331  /// \brief Retrieve the explicit template argument list that followed the
1332  /// member template name, if any.
1333  ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() {
1334    if (!HasExplicitTemplateArgumentList)
1335      return 0;
1336
1337    if (!HasQualifierOrFoundDecl)
1338      return reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
1339
1340    return reinterpret_cast<ExplicitTemplateArgumentList *>(
1341                                                      getMemberQualifier() + 1);
1342  }
1343
1344  /// \brief Retrieve the explicit template argument list that followed the
1345  /// member template name, if any.
1346  const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const {
1347    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgumentList();
1348  }
1349
1350public:
1351  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1352             SourceLocation l, QualType ty)
1353    : Expr(MemberExprClass, ty,
1354           base->isTypeDependent(), base->isValueDependent()),
1355      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow),
1356      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
1357
1358  /// \brief Build an empty member reference expression.
1359  explicit MemberExpr(EmptyShell Empty)
1360    : Expr(MemberExprClass, Empty), HasQualifierOrFoundDecl(false),
1361      HasExplicitTemplateArgumentList(false) { }
1362
1363  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
1364                            NestedNameSpecifier *qual, SourceRange qualrange,
1365                            ValueDecl *memberdecl, DeclAccessPair founddecl,
1366                            SourceLocation l,
1367                            const TemplateArgumentListInfo *targs,
1368                            QualType ty);
1369
1370  void setBase(Expr *E) { Base = E; }
1371  Expr *getBase() const { return cast<Expr>(Base); }
1372
1373  /// \brief Retrieve the member declaration to which this expression refers.
1374  ///
1375  /// The returned declaration will either be a FieldDecl or (in C++)
1376  /// a CXXMethodDecl.
1377  ValueDecl *getMemberDecl() const { return MemberDecl; }
1378  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
1379
1380  /// \brief Retrieves the declaration found by lookup.
1381  DeclAccessPair getFoundDecl() const {
1382    if (!HasQualifierOrFoundDecl)
1383      return DeclAccessPair::make(getMemberDecl(),
1384                                  getMemberDecl()->getAccess());
1385    return getMemberQualifier()->FoundDecl;
1386  }
1387
1388  /// \brief Determines whether this member expression actually had
1389  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
1390  /// x->Base::foo.
1391  bool hasQualifier() const { return getQualifier() != 0; }
1392
1393  /// \brief If the member name was qualified, retrieves the source range of
1394  /// the nested-name-specifier that precedes the member name. Otherwise,
1395  /// returns an empty source range.
1396  SourceRange getQualifierRange() const {
1397    if (!HasQualifierOrFoundDecl)
1398      return SourceRange();
1399
1400    return getMemberQualifier()->Range;
1401  }
1402
1403  /// \brief If the member name was qualified, retrieves the
1404  /// nested-name-specifier that precedes the member name. Otherwise, returns
1405  /// NULL.
1406  NestedNameSpecifier *getQualifier() const {
1407    if (!HasQualifierOrFoundDecl)
1408      return 0;
1409
1410    return getMemberQualifier()->NNS;
1411  }
1412
1413  /// \brief Determines whether this member expression actually had a C++
1414  /// template argument list explicitly specified, e.g., x.f<int>.
1415  bool hasExplicitTemplateArgumentList() const {
1416    return HasExplicitTemplateArgumentList;
1417  }
1418
1419  /// \brief Copies the template arguments (if present) into the given
1420  /// structure.
1421  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1422    if (hasExplicitTemplateArgumentList())
1423      getExplicitTemplateArgumentList()->copyInto(List);
1424  }
1425
1426  /// \brief Retrieve the location of the left angle bracket following the
1427  /// member name ('<'), if any.
1428  SourceLocation getLAngleLoc() const {
1429    if (!HasExplicitTemplateArgumentList)
1430      return SourceLocation();
1431
1432    return getExplicitTemplateArgumentList()->LAngleLoc;
1433  }
1434
1435  /// \brief Retrieve the template arguments provided as part of this
1436  /// template-id.
1437  const TemplateArgumentLoc *getTemplateArgs() const {
1438    if (!HasExplicitTemplateArgumentList)
1439      return 0;
1440
1441    return getExplicitTemplateArgumentList()->getTemplateArgs();
1442  }
1443
1444  /// \brief Retrieve the number of template arguments provided as part of this
1445  /// template-id.
1446  unsigned getNumTemplateArgs() const {
1447    if (!HasExplicitTemplateArgumentList)
1448      return 0;
1449
1450    return getExplicitTemplateArgumentList()->NumTemplateArgs;
1451  }
1452
1453  /// \brief Retrieve the location of the right angle bracket following the
1454  /// template arguments ('>').
1455  SourceLocation getRAngleLoc() const {
1456    if (!HasExplicitTemplateArgumentList)
1457      return SourceLocation();
1458
1459    return getExplicitTemplateArgumentList()->RAngleLoc;
1460  }
1461
1462  bool isArrow() const { return IsArrow; }
1463  void setArrow(bool A) { IsArrow = A; }
1464
1465  /// getMemberLoc - Return the location of the "member", in X->F, it is the
1466  /// location of 'F'.
1467  SourceLocation getMemberLoc() const { return MemberLoc; }
1468  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
1469
1470  virtual SourceRange getSourceRange() const {
1471    // If we have an implicit base (like a C++ implicit this),
1472    // make sure not to return its location
1473    SourceLocation EndLoc = MemberLoc;
1474    if (HasExplicitTemplateArgumentList)
1475      EndLoc = getRAngleLoc();
1476
1477    SourceLocation BaseLoc = getBase()->getLocStart();
1478    if (BaseLoc.isInvalid())
1479      return SourceRange(MemberLoc, EndLoc);
1480    return SourceRange(BaseLoc, EndLoc);
1481  }
1482
1483  virtual SourceLocation getExprLoc() const { return MemberLoc; }
1484
1485  static bool classof(const Stmt *T) {
1486    return T->getStmtClass() == MemberExprClass;
1487  }
1488  static bool classof(const MemberExpr *) { return true; }
1489
1490  // Iterators
1491  virtual child_iterator child_begin();
1492  virtual child_iterator child_end();
1493};
1494
1495/// CompoundLiteralExpr - [C99 6.5.2.5]
1496///
1497class CompoundLiteralExpr : public Expr {
1498  /// LParenLoc - If non-null, this is the location of the left paren in a
1499  /// compound literal like "(int){4}".  This can be null if this is a
1500  /// synthesized compound expression.
1501  SourceLocation LParenLoc;
1502
1503  /// The type as written.  This can be an incomplete array type, in
1504  /// which case the actual expression type will be different.
1505  TypeSourceInfo *TInfo;
1506  Stmt *Init;
1507  bool FileScope;
1508public:
1509  // FIXME: Can compound literals be value-dependent?
1510  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
1511                      QualType T, Expr *init, bool fileScope)
1512    : Expr(CompoundLiteralExprClass, T,
1513           tinfo->getType()->isDependentType(), false),
1514      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
1515
1516  /// \brief Construct an empty compound literal.
1517  explicit CompoundLiteralExpr(EmptyShell Empty)
1518    : Expr(CompoundLiteralExprClass, Empty) { }
1519
1520  const Expr *getInitializer() const { return cast<Expr>(Init); }
1521  Expr *getInitializer() { return cast<Expr>(Init); }
1522  void setInitializer(Expr *E) { Init = E; }
1523
1524  bool isFileScope() const { return FileScope; }
1525  void setFileScope(bool FS) { FileScope = FS; }
1526
1527  SourceLocation getLParenLoc() const { return LParenLoc; }
1528  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1529
1530  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
1531  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
1532
1533  virtual SourceRange getSourceRange() const {
1534    // FIXME: Init should never be null.
1535    if (!Init)
1536      return SourceRange();
1537    if (LParenLoc.isInvalid())
1538      return Init->getSourceRange();
1539    return SourceRange(LParenLoc, Init->getLocEnd());
1540  }
1541
1542  static bool classof(const Stmt *T) {
1543    return T->getStmtClass() == CompoundLiteralExprClass;
1544  }
1545  static bool classof(const CompoundLiteralExpr *) { return true; }
1546
1547  // Iterators
1548  virtual child_iterator child_begin();
1549  virtual child_iterator child_end();
1550};
1551
1552/// CastExpr - Base class for type casts, including both implicit
1553/// casts (ImplicitCastExpr) and explicit casts that have some
1554/// representation in the source code (ExplicitCastExpr's derived
1555/// classes).
1556class CastExpr : public Expr {
1557public:
1558  /// CastKind - the kind of cast this represents.
1559  enum CastKind {
1560    /// CK_Unknown - Unknown cast kind.
1561    /// FIXME: The goal is to get rid of this and make all casts have a
1562    /// kind so that the AST client doesn't have to try to figure out what's
1563    /// going on.
1564    CK_Unknown,
1565
1566    /// CK_BitCast - Used for reinterpret_cast.
1567    CK_BitCast,
1568
1569    /// CK_NoOp - Used for const_cast.
1570    CK_NoOp,
1571
1572    /// CK_BaseToDerived - Base to derived class casts.
1573    CK_BaseToDerived,
1574
1575    /// CK_DerivedToBase - Derived to base class casts.
1576    CK_DerivedToBase,
1577
1578    /// CK_UncheckedDerivedToBase - Derived to base class casts that
1579    /// assume that the derived pointer is not null.
1580    CK_UncheckedDerivedToBase,
1581
1582    /// CK_Dynamic - Dynamic cast.
1583    CK_Dynamic,
1584
1585    /// CK_ToUnion - Cast to union (GCC extension).
1586    CK_ToUnion,
1587
1588    /// CK_ArrayToPointerDecay - Array to pointer decay.
1589    CK_ArrayToPointerDecay,
1590
1591    // CK_FunctionToPointerDecay - Function to pointer decay.
1592    CK_FunctionToPointerDecay,
1593
1594    /// CK_NullToMemberPointer - Null pointer to member pointer.
1595    CK_NullToMemberPointer,
1596
1597    /// CK_BaseToDerivedMemberPointer - Member pointer in base class to
1598    /// member pointer in derived class.
1599    CK_BaseToDerivedMemberPointer,
1600
1601    /// CK_DerivedToBaseMemberPointer - Member pointer in derived class to
1602    /// member pointer in base class.
1603    CK_DerivedToBaseMemberPointer,
1604
1605    /// CK_UserDefinedConversion - Conversion using a user defined type
1606    /// conversion function.
1607    CK_UserDefinedConversion,
1608
1609    /// CK_ConstructorConversion - Conversion by constructor
1610    CK_ConstructorConversion,
1611
1612    /// CK_IntegralToPointer - Integral to pointer
1613    CK_IntegralToPointer,
1614
1615    /// CK_PointerToIntegral - Pointer to integral
1616    CK_PointerToIntegral,
1617
1618    /// CK_ToVoid - Cast to void.
1619    CK_ToVoid,
1620
1621    /// CK_VectorSplat - Casting from an integer/floating type to an extended
1622    /// vector type with the same element type as the src type. Splats the
1623    /// src expression into the destination expression.
1624    CK_VectorSplat,
1625
1626    /// CK_IntegralCast - Casting between integral types of different size.
1627    CK_IntegralCast,
1628
1629    /// CK_IntegralToFloating - Integral to floating point.
1630    CK_IntegralToFloating,
1631
1632    /// CK_FloatingToIntegral - Floating point to integral.
1633    CK_FloatingToIntegral,
1634
1635    /// CK_FloatingCast - Casting between floating types of different size.
1636    CK_FloatingCast,
1637
1638    /// CK_MemberPointerToBoolean - Member pointer to boolean
1639    CK_MemberPointerToBoolean,
1640
1641    /// CK_AnyPointerToObjCPointerCast - Casting any pointer to objective-c
1642    /// pointer
1643    CK_AnyPointerToObjCPointerCast,
1644    /// CK_AnyPointerToBlockPointerCast - Casting any pointer to block
1645    /// pointer
1646    CK_AnyPointerToBlockPointerCast
1647
1648  };
1649
1650private:
1651  CastKind Kind;
1652  Stmt *Op;
1653
1654  /// BasePath - For derived-to-base and base-to-derived casts, the base array
1655  /// contains the inheritance path.
1656  CXXBaseSpecifierArray BasePath;
1657
1658  void CheckBasePath() const {
1659#ifndef NDEBUG
1660    switch (getCastKind()) {
1661    // FIXME: We should add inheritance paths for these.
1662    case CK_BaseToDerived:
1663    case CK_DerivedToBase:
1664    case CK_UncheckedDerivedToBase:
1665    case CK_BaseToDerivedMemberPointer:
1666    case CK_DerivedToBaseMemberPointer:
1667
1668    // These should not have an inheritance path.
1669    case CK_Unknown:
1670    case CK_BitCast:
1671    case CK_NoOp:
1672    case CK_Dynamic:
1673    case CK_ToUnion:
1674    case CK_ArrayToPointerDecay:
1675    case CK_FunctionToPointerDecay:
1676    case CK_NullToMemberPointer:
1677    case CK_UserDefinedConversion:
1678    case CK_ConstructorConversion:
1679    case CK_IntegralToPointer:
1680    case CK_PointerToIntegral:
1681    case CK_ToVoid:
1682    case CK_VectorSplat:
1683    case CK_IntegralCast:
1684    case CK_IntegralToFloating:
1685    case CK_FloatingToIntegral:
1686    case CK_FloatingCast:
1687    case CK_MemberPointerToBoolean:
1688    case CK_AnyPointerToObjCPointerCast:
1689    case CK_AnyPointerToBlockPointerCast:
1690      assert(BasePath.empty() && "Cast kind shoudl not have a base path!");
1691      break;
1692    }
1693#endif
1694  }
1695
1696protected:
1697  CastExpr(StmtClass SC, QualType ty, const CastKind kind, Expr *op,
1698           CXXBaseSpecifierArray BasePath) :
1699    Expr(SC, ty,
1700         // Cast expressions are type-dependent if the type is
1701         // dependent (C++ [temp.dep.expr]p3).
1702         ty->isDependentType(),
1703         // Cast expressions are value-dependent if the type is
1704         // dependent or if the subexpression is value-dependent.
1705         ty->isDependentType() || (op && op->isValueDependent())),
1706    Kind(kind), Op(op), BasePath(BasePath) {
1707      CheckBasePath();
1708    }
1709
1710  /// \brief Construct an empty cast.
1711  CastExpr(StmtClass SC, EmptyShell Empty)
1712    : Expr(SC, Empty) { }
1713
1714  virtual void DoDestroy(ASTContext &C);
1715
1716public:
1717  CastKind getCastKind() const { return Kind; }
1718  void setCastKind(CastKind K) { Kind = K; }
1719  const char *getCastKindName() const;
1720
1721  Expr *getSubExpr() { return cast<Expr>(Op); }
1722  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1723  void setSubExpr(Expr *E) { Op = E; }
1724
1725  /// \brief Retrieve the cast subexpression as it was written in the source
1726  /// code, looking through any implicit casts or other intermediate nodes
1727  /// introduced by semantic analysis.
1728  Expr *getSubExprAsWritten();
1729  const Expr *getSubExprAsWritten() const {
1730    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
1731  }
1732
1733  const CXXBaseSpecifierArray& getBasePath() { return BasePath; }
1734
1735  static bool classof(const Stmt *T) {
1736    StmtClass SC = T->getStmtClass();
1737    if (SC >= CXXStaticCastExprClass && SC <= CXXFunctionalCastExprClass)
1738      return true;
1739
1740    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
1741      return true;
1742
1743    return false;
1744  }
1745  static bool classof(const CastExpr *) { return true; }
1746
1747  // Iterators
1748  virtual child_iterator child_begin();
1749  virtual child_iterator child_end();
1750};
1751
1752/// ImplicitCastExpr - Allows us to explicitly represent implicit type
1753/// conversions, which have no direct representation in the original
1754/// source code. For example: converting T[]->T*, void f()->void
1755/// (*f)(), float->double, short->int, etc.
1756///
1757/// In C, implicit casts always produce rvalues. However, in C++, an
1758/// implicit cast whose result is being bound to a reference will be
1759/// an lvalue. For example:
1760///
1761/// @code
1762/// class Base { };
1763/// class Derived : public Base { };
1764/// void f(Derived d) {
1765///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
1766/// }
1767/// @endcode
1768class ImplicitCastExpr : public CastExpr {
1769  /// LvalueCast - Whether this cast produces an lvalue.
1770  bool LvalueCast;
1771
1772public:
1773  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
1774                   CXXBaseSpecifierArray BasePath, bool Lvalue)
1775    : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePath),
1776    LvalueCast(Lvalue) { }
1777
1778  /// \brief Construct an empty implicit cast.
1779  explicit ImplicitCastExpr(EmptyShell Shell)
1780    : CastExpr(ImplicitCastExprClass, Shell) { }
1781
1782  virtual SourceRange getSourceRange() const {
1783    return getSubExpr()->getSourceRange();
1784  }
1785
1786  /// isLvalueCast - Whether this cast produces an lvalue.
1787  bool isLvalueCast() const { return LvalueCast; }
1788
1789  /// setLvalueCast - Set whether this cast produces an lvalue.
1790  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1791
1792  static bool classof(const Stmt *T) {
1793    return T->getStmtClass() == ImplicitCastExprClass;
1794  }
1795  static bool classof(const ImplicitCastExpr *) { return true; }
1796};
1797
1798/// ExplicitCastExpr - An explicit cast written in the source
1799/// code.
1800///
1801/// This class is effectively an abstract class, because it provides
1802/// the basic representation of an explicitly-written cast without
1803/// specifying which kind of cast (C cast, functional cast, static
1804/// cast, etc.) was written; specific derived classes represent the
1805/// particular style of cast and its location information.
1806///
1807/// Unlike implicit casts, explicit cast nodes have two different
1808/// types: the type that was written into the source code, and the
1809/// actual type of the expression as determined by semantic
1810/// analysis. These types may differ slightly. For example, in C++ one
1811/// can cast to a reference type, which indicates that the resulting
1812/// expression will be an lvalue. The reference type, however, will
1813/// not be used as the type of the expression.
1814class ExplicitCastExpr : public CastExpr {
1815  /// TInfo - Source type info for the (written) type
1816  /// this expression is casting to.
1817  TypeSourceInfo *TInfo;
1818
1819protected:
1820  ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind,
1821                   Expr *op, CXXBaseSpecifierArray BasePath,
1822                   TypeSourceInfo *writtenTy)
1823    : CastExpr(SC, exprTy, kind, op, BasePath), TInfo(writtenTy) {}
1824
1825  /// \brief Construct an empty explicit cast.
1826  ExplicitCastExpr(StmtClass SC, EmptyShell Shell)
1827    : CastExpr(SC, Shell) { }
1828
1829public:
1830  /// getTypeInfoAsWritten - Returns the type source info for the type
1831  /// that this expression is casting to.
1832  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
1833  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
1834
1835  /// getTypeAsWritten - Returns the type that this expression is
1836  /// casting to, as written in the source code.
1837  QualType getTypeAsWritten() const { return TInfo->getType(); }
1838
1839  static bool classof(const Stmt *T) {
1840    StmtClass SC = T->getStmtClass();
1841    if (SC >= CStyleCastExprClass && SC <= CStyleCastExprClass)
1842      return true;
1843    if (SC >= CXXStaticCastExprClass && SC <= CXXFunctionalCastExprClass)
1844      return true;
1845
1846    return false;
1847  }
1848  static bool classof(const ExplicitCastExpr *) { return true; }
1849};
1850
1851/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1852/// cast in C++ (C++ [expr.cast]), which uses the syntax
1853/// (Type)expr. For example: @c (int)f.
1854class CStyleCastExpr : public ExplicitCastExpr {
1855  SourceLocation LPLoc; // the location of the left paren
1856  SourceLocation RPLoc; // the location of the right paren
1857public:
1858  CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op,
1859                 CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy,
1860                 SourceLocation l, SourceLocation r)
1861    : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, BasePath,
1862                       writtenTy), LPLoc(l), RPLoc(r) {}
1863
1864  /// \brief Construct an empty C-style explicit cast.
1865  explicit CStyleCastExpr(EmptyShell Shell)
1866    : ExplicitCastExpr(CStyleCastExprClass, Shell) { }
1867
1868  SourceLocation getLParenLoc() const { return LPLoc; }
1869  void setLParenLoc(SourceLocation L) { LPLoc = L; }
1870
1871  SourceLocation getRParenLoc() const { return RPLoc; }
1872  void setRParenLoc(SourceLocation L) { RPLoc = L; }
1873
1874  virtual SourceRange getSourceRange() const {
1875    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1876  }
1877  static bool classof(const Stmt *T) {
1878    return T->getStmtClass() == CStyleCastExprClass;
1879  }
1880  static bool classof(const CStyleCastExpr *) { return true; }
1881};
1882
1883/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
1884///
1885/// This expression node kind describes a builtin binary operation,
1886/// such as "x + y" for integer values "x" and "y". The operands will
1887/// already have been converted to appropriate types (e.g., by
1888/// performing promotions or conversions).
1889///
1890/// In C++, where operators may be overloaded, a different kind of
1891/// expression node (CXXOperatorCallExpr) is used to express the
1892/// invocation of an overloaded operator with operator syntax. Within
1893/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
1894/// used to store an expression "x + y" depends on the subexpressions
1895/// for x and y. If neither x or y is type-dependent, and the "+"
1896/// operator resolves to a built-in operation, BinaryOperator will be
1897/// used to express the computation (x and y may still be
1898/// value-dependent). If either x or y is type-dependent, or if the
1899/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
1900/// be used to express the computation.
1901class BinaryOperator : public Expr {
1902public:
1903  enum Opcode {
1904    // Operators listed in order of precedence.
1905    // Note that additions to this should also update the StmtVisitor class.
1906    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
1907    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1908    Add, Sub,         // [C99 6.5.6] Additive operators.
1909    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1910    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1911    EQ, NE,           // [C99 6.5.9] Equality operators.
1912    And,              // [C99 6.5.10] Bitwise AND operator.
1913    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1914    Or,               // [C99 6.5.12] Bitwise OR operator.
1915    LAnd,             // [C99 6.5.13] Logical AND operator.
1916    LOr,              // [C99 6.5.14] Logical OR operator.
1917    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1918    DivAssign, RemAssign,
1919    AddAssign, SubAssign,
1920    ShlAssign, ShrAssign,
1921    AndAssign, XorAssign,
1922    OrAssign,
1923    Comma             // [C99 6.5.17] Comma operator.
1924  };
1925private:
1926  enum { LHS, RHS, END_EXPR };
1927  Stmt* SubExprs[END_EXPR];
1928  Opcode Opc;
1929  SourceLocation OpLoc;
1930public:
1931
1932  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1933                 SourceLocation opLoc)
1934    : Expr(BinaryOperatorClass, ResTy,
1935           lhs->isTypeDependent() || rhs->isTypeDependent(),
1936           lhs->isValueDependent() || rhs->isValueDependent()),
1937      Opc(opc), OpLoc(opLoc) {
1938    SubExprs[LHS] = lhs;
1939    SubExprs[RHS] = rhs;
1940    assert(!isCompoundAssignmentOp() &&
1941           "Use ArithAssignBinaryOperator for compound assignments");
1942  }
1943
1944  /// \brief Construct an empty binary operator.
1945  explicit BinaryOperator(EmptyShell Empty)
1946    : Expr(BinaryOperatorClass, Empty), Opc(Comma) { }
1947
1948  SourceLocation getOperatorLoc() const { return OpLoc; }
1949  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1950
1951  Opcode getOpcode() const { return Opc; }
1952  void setOpcode(Opcode O) { Opc = O; }
1953
1954  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1955  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1956  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1957  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1958
1959  virtual SourceRange getSourceRange() const {
1960    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1961  }
1962
1963  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1964  /// corresponds to, e.g. "<<=".
1965  static const char *getOpcodeStr(Opcode Op);
1966
1967  /// \brief Retrieve the binary opcode that corresponds to the given
1968  /// overloaded operator.
1969  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
1970
1971  /// \brief Retrieve the overloaded operator kind that corresponds to
1972  /// the given binary opcode.
1973  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1974
1975  /// predicates to categorize the respective opcodes.
1976  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1977  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1978  static bool isShiftOp(Opcode Opc) { return Opc == Shl || Opc == Shr; }
1979  bool isShiftOp() const { return isShiftOp(Opc); }
1980
1981  static bool isBitwiseOp(Opcode Opc) { return Opc >= And && Opc <= Or; }
1982  bool isBitwiseOp() const { return isBitwiseOp(Opc); }
1983
1984  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1985  bool isRelationalOp() const { return isRelationalOp(Opc); }
1986
1987  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1988  bool isEqualityOp() const { return isEqualityOp(Opc); }
1989
1990  static bool isComparisonOp(Opcode Opc) { return Opc >= LT && Opc <= NE; }
1991  bool isComparisonOp() const { return isComparisonOp(Opc); }
1992
1993  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1994  bool isLogicalOp() const { return isLogicalOp(Opc); }
1995
1996  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1997  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1998  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
1999
2000  static bool classof(const Stmt *S) {
2001    return S->getStmtClass() == BinaryOperatorClass ||
2002           S->getStmtClass() == CompoundAssignOperatorClass;
2003  }
2004  static bool classof(const BinaryOperator *) { return true; }
2005
2006  // Iterators
2007  virtual child_iterator child_begin();
2008  virtual child_iterator child_end();
2009
2010protected:
2011  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2012                 SourceLocation opLoc, bool dead)
2013    : Expr(CompoundAssignOperatorClass, ResTy,
2014           lhs->isTypeDependent() || rhs->isTypeDependent(),
2015           lhs->isValueDependent() || rhs->isValueDependent()),
2016      Opc(opc), OpLoc(opLoc) {
2017    SubExprs[LHS] = lhs;
2018    SubExprs[RHS] = rhs;
2019  }
2020
2021  BinaryOperator(StmtClass SC, EmptyShell Empty)
2022    : Expr(SC, Empty), Opc(MulAssign) { }
2023};
2024
2025/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2026/// track of the type the operation is performed in.  Due to the semantics of
2027/// these operators, the operands are promoted, the aritmetic performed, an
2028/// implicit conversion back to the result type done, then the assignment takes
2029/// place.  This captures the intermediate type which the computation is done
2030/// in.
2031class CompoundAssignOperator : public BinaryOperator {
2032  QualType ComputationLHSType;
2033  QualType ComputationResultType;
2034public:
2035  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
2036                         QualType ResType, QualType CompLHSType,
2037                         QualType CompResultType,
2038                         SourceLocation OpLoc)
2039    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
2040      ComputationLHSType(CompLHSType),
2041      ComputationResultType(CompResultType) {
2042    assert(isCompoundAssignmentOp() &&
2043           "Only should be used for compound assignments");
2044  }
2045
2046  /// \brief Build an empty compound assignment operator expression.
2047  explicit CompoundAssignOperator(EmptyShell Empty)
2048    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2049
2050  // The two computation types are the type the LHS is converted
2051  // to for the computation and the type of the result; the two are
2052  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2053  QualType getComputationLHSType() const { return ComputationLHSType; }
2054  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2055
2056  QualType getComputationResultType() const { return ComputationResultType; }
2057  void setComputationResultType(QualType T) { ComputationResultType = T; }
2058
2059  static bool classof(const CompoundAssignOperator *) { return true; }
2060  static bool classof(const Stmt *S) {
2061    return S->getStmtClass() == CompoundAssignOperatorClass;
2062  }
2063};
2064
2065/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
2066/// GNU "missing LHS" extension is in use.
2067///
2068class ConditionalOperator : public Expr {
2069  enum { COND, LHS, RHS, END_EXPR };
2070  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2071  SourceLocation QuestionLoc, ColonLoc;
2072public:
2073  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2074                      SourceLocation CLoc, Expr *rhs, QualType t)
2075    : Expr(ConditionalOperatorClass, t,
2076           // FIXME: the type of the conditional operator doesn't
2077           // depend on the type of the conditional, but the standard
2078           // seems to imply that it could. File a bug!
2079           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
2080           (cond->isValueDependent() ||
2081            (lhs && lhs->isValueDependent()) ||
2082            (rhs && rhs->isValueDependent()))),
2083      QuestionLoc(QLoc),
2084      ColonLoc(CLoc) {
2085    SubExprs[COND] = cond;
2086    SubExprs[LHS] = lhs;
2087    SubExprs[RHS] = rhs;
2088  }
2089
2090  /// \brief Build an empty conditional operator.
2091  explicit ConditionalOperator(EmptyShell Empty)
2092    : Expr(ConditionalOperatorClass, Empty) { }
2093
2094  // getCond - Return the expression representing the condition for
2095  //  the ?: operator.
2096  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2097  void setCond(Expr *E) { SubExprs[COND] = E; }
2098
2099  // getTrueExpr - Return the subexpression representing the value of the ?:
2100  //  expression if the condition evaluates to true.  In most cases this value
2101  //  will be the same as getLHS() except a GCC extension allows the left
2102  //  subexpression to be omitted, and instead of the condition be returned.
2103  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
2104  //  is only evaluated once.
2105  Expr *getTrueExpr() const {
2106    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
2107  }
2108
2109  // getTrueExpr - Return the subexpression representing the value of the ?:
2110  // expression if the condition evaluates to false. This is the same as getRHS.
2111  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2112
2113  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
2114  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2115
2116  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2117  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2118
2119  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2120  void setQuestionLoc(SourceLocation L) { QuestionLoc = L; }
2121
2122  SourceLocation getColonLoc() const { return ColonLoc; }
2123  void setColonLoc(SourceLocation L) { ColonLoc = L; }
2124
2125  virtual SourceRange getSourceRange() const {
2126    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2127  }
2128  static bool classof(const Stmt *T) {
2129    return T->getStmtClass() == ConditionalOperatorClass;
2130  }
2131  static bool classof(const ConditionalOperator *) { return true; }
2132
2133  // Iterators
2134  virtual child_iterator child_begin();
2135  virtual child_iterator child_end();
2136};
2137
2138/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2139class AddrLabelExpr : public Expr {
2140  SourceLocation AmpAmpLoc, LabelLoc;
2141  LabelStmt *Label;
2142public:
2143  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
2144                QualType t)
2145    : Expr(AddrLabelExprClass, t, false, false),
2146      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2147
2148  /// \brief Build an empty address of a label expression.
2149  explicit AddrLabelExpr(EmptyShell Empty)
2150    : Expr(AddrLabelExprClass, Empty) { }
2151
2152  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2153  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2154  SourceLocation getLabelLoc() const { return LabelLoc; }
2155  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2156
2157  virtual SourceRange getSourceRange() const {
2158    return SourceRange(AmpAmpLoc, LabelLoc);
2159  }
2160
2161  LabelStmt *getLabel() const { return Label; }
2162  void setLabel(LabelStmt *S) { Label = S; }
2163
2164  static bool classof(const Stmt *T) {
2165    return T->getStmtClass() == AddrLabelExprClass;
2166  }
2167  static bool classof(const AddrLabelExpr *) { return true; }
2168
2169  // Iterators
2170  virtual child_iterator child_begin();
2171  virtual child_iterator child_end();
2172};
2173
2174/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2175/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2176/// takes the value of the last subexpression.
2177class StmtExpr : public Expr {
2178  Stmt *SubStmt;
2179  SourceLocation LParenLoc, RParenLoc;
2180public:
2181  // FIXME: Does type-dependence need to be computed differently?
2182  StmtExpr(CompoundStmt *substmt, QualType T,
2183           SourceLocation lp, SourceLocation rp) :
2184    Expr(StmtExprClass, T, T->isDependentType(), false),
2185    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2186
2187  /// \brief Build an empty statement expression.
2188  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2189
2190  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2191  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2192  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2193
2194  virtual SourceRange getSourceRange() const {
2195    return SourceRange(LParenLoc, RParenLoc);
2196  }
2197
2198  SourceLocation getLParenLoc() const { return LParenLoc; }
2199  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2200  SourceLocation getRParenLoc() const { return RParenLoc; }
2201  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2202
2203  static bool classof(const Stmt *T) {
2204    return T->getStmtClass() == StmtExprClass;
2205  }
2206  static bool classof(const StmtExpr *) { return true; }
2207
2208  // Iterators
2209  virtual child_iterator child_begin();
2210  virtual child_iterator child_end();
2211};
2212
2213/// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
2214/// This AST node represents a function that returns 1 if two *types* (not
2215/// expressions) are compatible. The result of this built-in function can be
2216/// used in integer constant expressions.
2217class TypesCompatibleExpr : public Expr {
2218  QualType Type1;
2219  QualType Type2;
2220  SourceLocation BuiltinLoc, RParenLoc;
2221public:
2222  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
2223                      QualType t1, QualType t2, SourceLocation RP) :
2224    Expr(TypesCompatibleExprClass, ReturnType, false, false),
2225    Type1(t1), Type2(t2), BuiltinLoc(BLoc), RParenLoc(RP) {}
2226
2227  /// \brief Build an empty __builtin_type_compatible_p expression.
2228  explicit TypesCompatibleExpr(EmptyShell Empty)
2229    : Expr(TypesCompatibleExprClass, Empty) { }
2230
2231  QualType getArgType1() const { return Type1; }
2232  void setArgType1(QualType T) { Type1 = T; }
2233  QualType getArgType2() const { return Type2; }
2234  void setArgType2(QualType T) { Type2 = T; }
2235
2236  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2237  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2238
2239  SourceLocation getRParenLoc() const { return RParenLoc; }
2240  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2241
2242  virtual SourceRange getSourceRange() const {
2243    return SourceRange(BuiltinLoc, RParenLoc);
2244  }
2245  static bool classof(const Stmt *T) {
2246    return T->getStmtClass() == TypesCompatibleExprClass;
2247  }
2248  static bool classof(const TypesCompatibleExpr *) { return true; }
2249
2250  // Iterators
2251  virtual child_iterator child_begin();
2252  virtual child_iterator child_end();
2253};
2254
2255/// ShuffleVectorExpr - clang-specific builtin-in function
2256/// __builtin_shufflevector.
2257/// This AST node represents a operator that does a constant
2258/// shuffle, similar to LLVM's shufflevector instruction. It takes
2259/// two vectors and a variable number of constant indices,
2260/// and returns the appropriately shuffled vector.
2261class ShuffleVectorExpr : public Expr {
2262  SourceLocation BuiltinLoc, RParenLoc;
2263
2264  // SubExprs - the list of values passed to the __builtin_shufflevector
2265  // function. The first two are vectors, and the rest are constant
2266  // indices.  The number of values in this list is always
2267  // 2+the number of indices in the vector type.
2268  Stmt **SubExprs;
2269  unsigned NumExprs;
2270
2271protected:
2272  virtual void DoDestroy(ASTContext &C);
2273
2274public:
2275  // FIXME: Can a shufflevector be value-dependent?  Does type-dependence need
2276  // to be computed differently?
2277  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2278                    QualType Type, SourceLocation BLoc,
2279                    SourceLocation RP) :
2280    Expr(ShuffleVectorExprClass, Type, Type->isDependentType(), false),
2281    BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) {
2282
2283    SubExprs = new (C) Stmt*[nexpr];
2284    for (unsigned i = 0; i < nexpr; i++)
2285      SubExprs[i] = args[i];
2286  }
2287
2288  /// \brief Build an empty vector-shuffle expression.
2289  explicit ShuffleVectorExpr(EmptyShell Empty)
2290    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
2291
2292  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2293  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2294
2295  SourceLocation getRParenLoc() const { return RParenLoc; }
2296  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2297
2298  virtual SourceRange getSourceRange() const {
2299    return SourceRange(BuiltinLoc, RParenLoc);
2300  }
2301  static bool classof(const Stmt *T) {
2302    return T->getStmtClass() == ShuffleVectorExprClass;
2303  }
2304  static bool classof(const ShuffleVectorExpr *) { return true; }
2305
2306  ~ShuffleVectorExpr() {}
2307
2308  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
2309  /// constant expression, the actual arguments passed in, and the function
2310  /// pointers.
2311  unsigned getNumSubExprs() const { return NumExprs; }
2312
2313  /// getExpr - Return the Expr at the specified index.
2314  Expr *getExpr(unsigned Index) {
2315    assert((Index < NumExprs) && "Arg access out of range!");
2316    return cast<Expr>(SubExprs[Index]);
2317  }
2318  const Expr *getExpr(unsigned Index) const {
2319    assert((Index < NumExprs) && "Arg access out of range!");
2320    return cast<Expr>(SubExprs[Index]);
2321  }
2322
2323  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
2324
2325  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
2326    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
2327    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
2328  }
2329
2330  // Iterators
2331  virtual child_iterator child_begin();
2332  virtual child_iterator child_end();
2333};
2334
2335/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
2336/// This AST node is similar to the conditional operator (?:) in C, with
2337/// the following exceptions:
2338/// - the test expression must be a integer constant expression.
2339/// - the expression returned acts like the chosen subexpression in every
2340///   visible way: the type is the same as that of the chosen subexpression,
2341///   and all predicates (whether it's an l-value, whether it's an integer
2342///   constant expression, etc.) return the same result as for the chosen
2343///   sub-expression.
2344class ChooseExpr : public Expr {
2345  enum { COND, LHS, RHS, END_EXPR };
2346  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2347  SourceLocation BuiltinLoc, RParenLoc;
2348public:
2349  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
2350             SourceLocation RP, bool TypeDependent, bool ValueDependent)
2351    : Expr(ChooseExprClass, t, TypeDependent, ValueDependent),
2352      BuiltinLoc(BLoc), RParenLoc(RP) {
2353      SubExprs[COND] = cond;
2354      SubExprs[LHS] = lhs;
2355      SubExprs[RHS] = rhs;
2356    }
2357
2358  /// \brief Build an empty __builtin_choose_expr.
2359  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
2360
2361  /// isConditionTrue - Return whether the condition is true (i.e. not
2362  /// equal to zero).
2363  bool isConditionTrue(ASTContext &C) const;
2364
2365  /// getChosenSubExpr - Return the subexpression chosen according to the
2366  /// condition.
2367  Expr *getChosenSubExpr(ASTContext &C) const {
2368    return isConditionTrue(C) ? getLHS() : getRHS();
2369  }
2370
2371  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2372  void setCond(Expr *E) { SubExprs[COND] = E; }
2373  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2374  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2375  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2376  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2377
2378  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2379  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2380
2381  SourceLocation getRParenLoc() const { return RParenLoc; }
2382  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2383
2384  virtual SourceRange getSourceRange() const {
2385    return SourceRange(BuiltinLoc, RParenLoc);
2386  }
2387  static bool classof(const Stmt *T) {
2388    return T->getStmtClass() == ChooseExprClass;
2389  }
2390  static bool classof(const ChooseExpr *) { return true; }
2391
2392  // Iterators
2393  virtual child_iterator child_begin();
2394  virtual child_iterator child_end();
2395};
2396
2397/// GNUNullExpr - Implements the GNU __null extension, which is a name
2398/// for a null pointer constant that has integral type (e.g., int or
2399/// long) and is the same size and alignment as a pointer. The __null
2400/// extension is typically only used by system headers, which define
2401/// NULL as __null in C++ rather than using 0 (which is an integer
2402/// that may not match the size of a pointer).
2403class GNUNullExpr : public Expr {
2404  /// TokenLoc - The location of the __null keyword.
2405  SourceLocation TokenLoc;
2406
2407public:
2408  GNUNullExpr(QualType Ty, SourceLocation Loc)
2409    : Expr(GNUNullExprClass, Ty, false, false), TokenLoc(Loc) { }
2410
2411  /// \brief Build an empty GNU __null expression.
2412  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
2413
2414  /// getTokenLocation - The location of the __null token.
2415  SourceLocation getTokenLocation() const { return TokenLoc; }
2416  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
2417
2418  virtual SourceRange getSourceRange() const {
2419    return SourceRange(TokenLoc);
2420  }
2421  static bool classof(const Stmt *T) {
2422    return T->getStmtClass() == GNUNullExprClass;
2423  }
2424  static bool classof(const GNUNullExpr *) { return true; }
2425
2426  // Iterators
2427  virtual child_iterator child_begin();
2428  virtual child_iterator child_end();
2429};
2430
2431/// VAArgExpr, used for the builtin function __builtin_va_arg.
2432class VAArgExpr : public Expr {
2433  Stmt *Val;
2434  SourceLocation BuiltinLoc, RParenLoc;
2435public:
2436  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
2437    : Expr(VAArgExprClass, t, t->isDependentType(), false),
2438      Val(e),
2439      BuiltinLoc(BLoc),
2440      RParenLoc(RPLoc) { }
2441
2442  /// \brief Create an empty __builtin_va_arg expression.
2443  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
2444
2445  const Expr *getSubExpr() const { return cast<Expr>(Val); }
2446  Expr *getSubExpr() { return cast<Expr>(Val); }
2447  void setSubExpr(Expr *E) { Val = E; }
2448
2449  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2450  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2451
2452  SourceLocation getRParenLoc() const { return RParenLoc; }
2453  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2454
2455  virtual SourceRange getSourceRange() const {
2456    return SourceRange(BuiltinLoc, RParenLoc);
2457  }
2458  static bool classof(const Stmt *T) {
2459    return T->getStmtClass() == VAArgExprClass;
2460  }
2461  static bool classof(const VAArgExpr *) { return true; }
2462
2463  // Iterators
2464  virtual child_iterator child_begin();
2465  virtual child_iterator child_end();
2466};
2467
2468/// @brief Describes an C or C++ initializer list.
2469///
2470/// InitListExpr describes an initializer list, which can be used to
2471/// initialize objects of different types, including
2472/// struct/class/union types, arrays, and vectors. For example:
2473///
2474/// @code
2475/// struct foo x = { 1, { 2, 3 } };
2476/// @endcode
2477///
2478/// Prior to semantic analysis, an initializer list will represent the
2479/// initializer list as written by the user, but will have the
2480/// placeholder type "void". This initializer list is called the
2481/// syntactic form of the initializer, and may contain C99 designated
2482/// initializers (represented as DesignatedInitExprs), initializations
2483/// of subobject members without explicit braces, and so on. Clients
2484/// interested in the original syntax of the initializer list should
2485/// use the syntactic form of the initializer list.
2486///
2487/// After semantic analysis, the initializer list will represent the
2488/// semantic form of the initializer, where the initializations of all
2489/// subobjects are made explicit with nested InitListExpr nodes and
2490/// C99 designators have been eliminated by placing the designated
2491/// initializations into the subobject they initialize. Additionally,
2492/// any "holes" in the initialization, where no initializer has been
2493/// specified for a particular subobject, will be replaced with
2494/// implicitly-generated ImplicitValueInitExpr expressions that
2495/// value-initialize the subobjects. Note, however, that the
2496/// initializer lists may still have fewer initializers than there are
2497/// elements to initialize within the object.
2498///
2499/// Given the semantic form of the initializer list, one can retrieve
2500/// the original syntactic form of that initializer list (if it
2501/// exists) using getSyntacticForm(). Since many initializer lists
2502/// have the same syntactic and semantic forms, getSyntacticForm() may
2503/// return NULL, indicating that the current initializer list also
2504/// serves as its syntactic form.
2505class InitListExpr : public Expr {
2506  // FIXME: Eliminate this vector in favor of ASTContext allocation
2507  typedef ASTVector<Stmt *> InitExprsTy;
2508  InitExprsTy InitExprs;
2509  SourceLocation LBraceLoc, RBraceLoc;
2510
2511  /// Contains the initializer list that describes the syntactic form
2512  /// written in the source code.
2513  InitListExpr *SyntacticForm;
2514
2515  /// If this initializer list initializes a union, specifies which
2516  /// field within the union will be initialized.
2517  FieldDecl *UnionFieldInit;
2518
2519  /// Whether this initializer list originally had a GNU array-range
2520  /// designator in it. This is a temporary marker used by CodeGen.
2521  bool HadArrayRangeDesignator;
2522
2523public:
2524  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
2525               Expr **initexprs, unsigned numinits,
2526               SourceLocation rbraceloc);
2527
2528  /// \brief Build an empty initializer list.
2529  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
2530    : Expr(InitListExprClass, Empty), InitExprs(C) { }
2531
2532  unsigned getNumInits() const { return InitExprs.size(); }
2533
2534  const Expr* getInit(unsigned Init) const {
2535    assert(Init < getNumInits() && "Initializer access out of range!");
2536    return cast_or_null<Expr>(InitExprs[Init]);
2537  }
2538
2539  Expr* getInit(unsigned Init) {
2540    assert(Init < getNumInits() && "Initializer access out of range!");
2541    return cast_or_null<Expr>(InitExprs[Init]);
2542  }
2543
2544  void setInit(unsigned Init, Expr *expr) {
2545    assert(Init < getNumInits() && "Initializer access out of range!");
2546    InitExprs[Init] = expr;
2547  }
2548
2549  /// \brief Reserve space for some number of initializers.
2550  void reserveInits(ASTContext &C, unsigned NumInits);
2551
2552  /// @brief Specify the number of initializers
2553  ///
2554  /// If there are more than @p NumInits initializers, the remaining
2555  /// initializers will be destroyed. If there are fewer than @p
2556  /// NumInits initializers, NULL expressions will be added for the
2557  /// unknown initializers.
2558  void resizeInits(ASTContext &Context, unsigned NumInits);
2559
2560  /// @brief Updates the initializer at index @p Init with the new
2561  /// expression @p expr, and returns the old expression at that
2562  /// location.
2563  ///
2564  /// When @p Init is out of range for this initializer list, the
2565  /// initializer list will be extended with NULL expressions to
2566  /// accomodate the new entry.
2567  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
2568
2569  /// \brief If this initializes a union, specifies which field in the
2570  /// union to initialize.
2571  ///
2572  /// Typically, this field is the first named field within the
2573  /// union. However, a designated initializer can specify the
2574  /// initialization of a different field within the union.
2575  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2576  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2577
2578  // Explicit InitListExpr's originate from source code (and have valid source
2579  // locations). Implicit InitListExpr's are created by the semantic analyzer.
2580  bool isExplicit() {
2581    return LBraceLoc.isValid() && RBraceLoc.isValid();
2582  }
2583
2584  SourceLocation getLBraceLoc() const { return LBraceLoc; }
2585  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2586  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2587  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2588
2589  /// @brief Retrieve the initializer list that describes the
2590  /// syntactic form of the initializer.
2591  ///
2592  ///
2593  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2594  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2595
2596  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2597  void sawArrayRangeDesignator(bool ARD = true) {
2598    HadArrayRangeDesignator = ARD;
2599  }
2600
2601  virtual SourceRange getSourceRange() const {
2602    return SourceRange(LBraceLoc, RBraceLoc);
2603  }
2604  static bool classof(const Stmt *T) {
2605    return T->getStmtClass() == InitListExprClass;
2606  }
2607  static bool classof(const InitListExpr *) { return true; }
2608
2609  // Iterators
2610  virtual child_iterator child_begin();
2611  virtual child_iterator child_end();
2612
2613  typedef InitExprsTy::iterator iterator;
2614  typedef InitExprsTy::reverse_iterator reverse_iterator;
2615
2616  iterator begin() { return InitExprs.begin(); }
2617  iterator end() { return InitExprs.end(); }
2618  reverse_iterator rbegin() { return InitExprs.rbegin(); }
2619  reverse_iterator rend() { return InitExprs.rend(); }
2620};
2621
2622/// @brief Represents a C99 designated initializer expression.
2623///
2624/// A designated initializer expression (C99 6.7.8) contains one or
2625/// more designators (which can be field designators, array
2626/// designators, or GNU array-range designators) followed by an
2627/// expression that initializes the field or element(s) that the
2628/// designators refer to. For example, given:
2629///
2630/// @code
2631/// struct point {
2632///   double x;
2633///   double y;
2634/// };
2635/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2636/// @endcode
2637///
2638/// The InitListExpr contains three DesignatedInitExprs, the first of
2639/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2640/// designators, one array designator for @c [2] followed by one field
2641/// designator for @c .y. The initalization expression will be 1.0.
2642class DesignatedInitExpr : public Expr {
2643public:
2644  /// \brief Forward declaration of the Designator class.
2645  class Designator;
2646
2647private:
2648  /// The location of the '=' or ':' prior to the actual initializer
2649  /// expression.
2650  SourceLocation EqualOrColonLoc;
2651
2652  /// Whether this designated initializer used the GNU deprecated
2653  /// syntax rather than the C99 '=' syntax.
2654  bool GNUSyntax : 1;
2655
2656  /// The number of designators in this initializer expression.
2657  unsigned NumDesignators : 15;
2658
2659  /// \brief The designators in this designated initialization
2660  /// expression.
2661  Designator *Designators;
2662
2663  /// The number of subexpressions of this initializer expression,
2664  /// which contains both the initializer and any additional
2665  /// expressions used by array and array-range designators.
2666  unsigned NumSubExprs : 16;
2667
2668
2669  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
2670                     const Designator *Designators,
2671                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
2672                     Expr **IndexExprs, unsigned NumIndexExprs,
2673                     Expr *Init);
2674
2675  explicit DesignatedInitExpr(unsigned NumSubExprs)
2676    : Expr(DesignatedInitExprClass, EmptyShell()),
2677      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
2678
2679protected:
2680  virtual void DoDestroy(ASTContext &C);
2681
2682  void DestroyDesignators(ASTContext &C);
2683
2684public:
2685  /// A field designator, e.g., ".x".
2686  struct FieldDesignator {
2687    /// Refers to the field that is being initialized. The low bit
2688    /// of this field determines whether this is actually a pointer
2689    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
2690    /// initially constructed, a field designator will store an
2691    /// IdentifierInfo*. After semantic analysis has resolved that
2692    /// name, the field designator will instead store a FieldDecl*.
2693    uintptr_t NameOrField;
2694
2695    /// The location of the '.' in the designated initializer.
2696    unsigned DotLoc;
2697
2698    /// The location of the field name in the designated initializer.
2699    unsigned FieldLoc;
2700  };
2701
2702  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2703  struct ArrayOrRangeDesignator {
2704    /// Location of the first index expression within the designated
2705    /// initializer expression's list of subexpressions.
2706    unsigned Index;
2707    /// The location of the '[' starting the array range designator.
2708    unsigned LBracketLoc;
2709    /// The location of the ellipsis separating the start and end
2710    /// indices. Only valid for GNU array-range designators.
2711    unsigned EllipsisLoc;
2712    /// The location of the ']' terminating the array range designator.
2713    unsigned RBracketLoc;
2714  };
2715
2716  /// @brief Represents a single C99 designator.
2717  ///
2718  /// @todo This class is infuriatingly similar to clang::Designator,
2719  /// but minor differences (storing indices vs. storing pointers)
2720  /// keep us from reusing it. Try harder, later, to rectify these
2721  /// differences.
2722  class Designator {
2723    /// @brief The kind of designator this describes.
2724    enum {
2725      FieldDesignator,
2726      ArrayDesignator,
2727      ArrayRangeDesignator
2728    } Kind;
2729
2730    union {
2731      /// A field designator, e.g., ".x".
2732      struct FieldDesignator Field;
2733      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2734      struct ArrayOrRangeDesignator ArrayOrRange;
2735    };
2736    friend class DesignatedInitExpr;
2737
2738  public:
2739    Designator() {}
2740
2741    /// @brief Initializes a field designator.
2742    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
2743               SourceLocation FieldLoc)
2744      : Kind(FieldDesignator) {
2745      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
2746      Field.DotLoc = DotLoc.getRawEncoding();
2747      Field.FieldLoc = FieldLoc.getRawEncoding();
2748    }
2749
2750    /// @brief Initializes an array designator.
2751    Designator(unsigned Index, SourceLocation LBracketLoc,
2752               SourceLocation RBracketLoc)
2753      : Kind(ArrayDesignator) {
2754      ArrayOrRange.Index = Index;
2755      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2756      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
2757      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2758    }
2759
2760    /// @brief Initializes a GNU array-range designator.
2761    Designator(unsigned Index, SourceLocation LBracketLoc,
2762               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
2763      : Kind(ArrayRangeDesignator) {
2764      ArrayOrRange.Index = Index;
2765      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2766      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
2767      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2768    }
2769
2770    bool isFieldDesignator() const { return Kind == FieldDesignator; }
2771    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
2772    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
2773
2774    IdentifierInfo * getFieldName();
2775
2776    FieldDecl *getField() {
2777      assert(Kind == FieldDesignator && "Only valid on a field designator");
2778      if (Field.NameOrField & 0x01)
2779        return 0;
2780      else
2781        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
2782    }
2783
2784    void setField(FieldDecl *FD) {
2785      assert(Kind == FieldDesignator && "Only valid on a field designator");
2786      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
2787    }
2788
2789    SourceLocation getDotLoc() const {
2790      assert(Kind == FieldDesignator && "Only valid on a field designator");
2791      return SourceLocation::getFromRawEncoding(Field.DotLoc);
2792    }
2793
2794    SourceLocation getFieldLoc() const {
2795      assert(Kind == FieldDesignator && "Only valid on a field designator");
2796      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
2797    }
2798
2799    SourceLocation getLBracketLoc() const {
2800      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2801             "Only valid on an array or array-range designator");
2802      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
2803    }
2804
2805    SourceLocation getRBracketLoc() const {
2806      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2807             "Only valid on an array or array-range designator");
2808      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
2809    }
2810
2811    SourceLocation getEllipsisLoc() const {
2812      assert(Kind == ArrayRangeDesignator &&
2813             "Only valid on an array-range designator");
2814      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
2815    }
2816
2817    unsigned getFirstExprIndex() const {
2818      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2819             "Only valid on an array or array-range designator");
2820      return ArrayOrRange.Index;
2821    }
2822
2823    SourceLocation getStartLocation() const {
2824      if (Kind == FieldDesignator)
2825        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
2826      else
2827        return getLBracketLoc();
2828    }
2829  };
2830
2831  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
2832                                    unsigned NumDesignators,
2833                                    Expr **IndexExprs, unsigned NumIndexExprs,
2834                                    SourceLocation EqualOrColonLoc,
2835                                    bool GNUSyntax, Expr *Init);
2836
2837  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
2838
2839  /// @brief Returns the number of designators in this initializer.
2840  unsigned size() const { return NumDesignators; }
2841
2842  // Iterator access to the designators.
2843  typedef Designator* designators_iterator;
2844  designators_iterator designators_begin() { return Designators; }
2845  designators_iterator designators_end() {
2846    return Designators + NumDesignators;
2847  }
2848
2849  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
2850
2851  void setDesignators(ASTContext &C, const Designator *Desigs,
2852                      unsigned NumDesigs);
2853
2854  Expr *getArrayIndex(const Designator& D);
2855  Expr *getArrayRangeStart(const Designator& D);
2856  Expr *getArrayRangeEnd(const Designator& D);
2857
2858  /// @brief Retrieve the location of the '=' that precedes the
2859  /// initializer value itself, if present.
2860  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
2861  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
2862
2863  /// @brief Determines whether this designated initializer used the
2864  /// deprecated GNU syntax for designated initializers.
2865  bool usesGNUSyntax() const { return GNUSyntax; }
2866  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
2867
2868  /// @brief Retrieve the initializer value.
2869  Expr *getInit() const {
2870    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
2871  }
2872
2873  void setInit(Expr *init) {
2874    *child_begin() = init;
2875  }
2876
2877  /// \brief Retrieve the total number of subexpressions in this
2878  /// designated initializer expression, including the actual
2879  /// initialized value and any expressions that occur within array
2880  /// and array-range designators.
2881  unsigned getNumSubExprs() const { return NumSubExprs; }
2882
2883  Expr *getSubExpr(unsigned Idx) {
2884    assert(Idx < NumSubExprs && "Subscript out of range");
2885    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2886    Ptr += sizeof(DesignatedInitExpr);
2887    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
2888  }
2889
2890  void setSubExpr(unsigned Idx, Expr *E) {
2891    assert(Idx < NumSubExprs && "Subscript out of range");
2892    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2893    Ptr += sizeof(DesignatedInitExpr);
2894    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
2895  }
2896
2897  /// \brief Replaces the designator at index @p Idx with the series
2898  /// of designators in [First, Last).
2899  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
2900                        const Designator *Last);
2901
2902  virtual SourceRange getSourceRange() const;
2903
2904  static bool classof(const Stmt *T) {
2905    return T->getStmtClass() == DesignatedInitExprClass;
2906  }
2907  static bool classof(const DesignatedInitExpr *) { return true; }
2908
2909  // Iterators
2910  virtual child_iterator child_begin();
2911  virtual child_iterator child_end();
2912};
2913
2914/// \brief Represents an implicitly-generated value initialization of
2915/// an object of a given type.
2916///
2917/// Implicit value initializations occur within semantic initializer
2918/// list expressions (InitListExpr) as placeholders for subobject
2919/// initializations not explicitly specified by the user.
2920///
2921/// \see InitListExpr
2922class ImplicitValueInitExpr : public Expr {
2923public:
2924  explicit ImplicitValueInitExpr(QualType ty)
2925    : Expr(ImplicitValueInitExprClass, ty, false, false) { }
2926
2927  /// \brief Construct an empty implicit value initialization.
2928  explicit ImplicitValueInitExpr(EmptyShell Empty)
2929    : Expr(ImplicitValueInitExprClass, Empty) { }
2930
2931  static bool classof(const Stmt *T) {
2932    return T->getStmtClass() == ImplicitValueInitExprClass;
2933  }
2934  static bool classof(const ImplicitValueInitExpr *) { return true; }
2935
2936  virtual SourceRange getSourceRange() const {
2937    return SourceRange();
2938  }
2939
2940  // Iterators
2941  virtual child_iterator child_begin();
2942  virtual child_iterator child_end();
2943};
2944
2945
2946class ParenListExpr : public Expr {
2947  Stmt **Exprs;
2948  unsigned NumExprs;
2949  SourceLocation LParenLoc, RParenLoc;
2950
2951protected:
2952  virtual void DoDestroy(ASTContext& C);
2953
2954public:
2955  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
2956                unsigned numexprs, SourceLocation rparenloc);
2957
2958  ~ParenListExpr() {}
2959
2960  /// \brief Build an empty paren list.
2961  //explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
2962
2963  unsigned getNumExprs() const { return NumExprs; }
2964
2965  const Expr* getExpr(unsigned Init) const {
2966    assert(Init < getNumExprs() && "Initializer access out of range!");
2967    return cast_or_null<Expr>(Exprs[Init]);
2968  }
2969
2970  Expr* getExpr(unsigned Init) {
2971    assert(Init < getNumExprs() && "Initializer access out of range!");
2972    return cast_or_null<Expr>(Exprs[Init]);
2973  }
2974
2975  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
2976
2977  SourceLocation getLParenLoc() const { return LParenLoc; }
2978  SourceLocation getRParenLoc() const { return RParenLoc; }
2979
2980  virtual SourceRange getSourceRange() const {
2981    return SourceRange(LParenLoc, RParenLoc);
2982  }
2983  static bool classof(const Stmt *T) {
2984    return T->getStmtClass() == ParenListExprClass;
2985  }
2986  static bool classof(const ParenListExpr *) { return true; }
2987
2988  // Iterators
2989  virtual child_iterator child_begin();
2990  virtual child_iterator child_end();
2991};
2992
2993
2994//===----------------------------------------------------------------------===//
2995// Clang Extensions
2996//===----------------------------------------------------------------------===//
2997
2998
2999/// ExtVectorElementExpr - This represents access to specific elements of a
3000/// vector, and may occur on the left hand side or right hand side.  For example
3001/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3002///
3003/// Note that the base may have either vector or pointer to vector type, just
3004/// like a struct field reference.
3005///
3006class ExtVectorElementExpr : public Expr {
3007  Stmt *Base;
3008  IdentifierInfo *Accessor;
3009  SourceLocation AccessorLoc;
3010public:
3011  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
3012                       SourceLocation loc)
3013    : Expr(ExtVectorElementExprClass, ty, base->isTypeDependent(),
3014           base->isValueDependent()),
3015      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3016
3017  /// \brief Build an empty vector element expression.
3018  explicit ExtVectorElementExpr(EmptyShell Empty)
3019    : Expr(ExtVectorElementExprClass, Empty) { }
3020
3021  const Expr *getBase() const { return cast<Expr>(Base); }
3022  Expr *getBase() { return cast<Expr>(Base); }
3023  void setBase(Expr *E) { Base = E; }
3024
3025  IdentifierInfo &getAccessor() const { return *Accessor; }
3026  void setAccessor(IdentifierInfo *II) { Accessor = II; }
3027
3028  SourceLocation getAccessorLoc() const { return AccessorLoc; }
3029  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3030
3031  /// getNumElements - Get the number of components being selected.
3032  unsigned getNumElements() const;
3033
3034  /// containsDuplicateElements - Return true if any element access is
3035  /// repeated.
3036  bool containsDuplicateElements() const;
3037
3038  /// getEncodedElementAccess - Encode the elements accessed into an llvm
3039  /// aggregate Constant of ConstantInt(s).
3040  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3041
3042  virtual SourceRange getSourceRange() const {
3043    return SourceRange(getBase()->getLocStart(), AccessorLoc);
3044  }
3045
3046  /// isArrow - Return true if the base expression is a pointer to vector,
3047  /// return false if the base expression is a vector.
3048  bool isArrow() const;
3049
3050  static bool classof(const Stmt *T) {
3051    return T->getStmtClass() == ExtVectorElementExprClass;
3052  }
3053  static bool classof(const ExtVectorElementExpr *) { return true; }
3054
3055  // Iterators
3056  virtual child_iterator child_begin();
3057  virtual child_iterator child_end();
3058};
3059
3060
3061/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3062/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3063class BlockExpr : public Expr {
3064protected:
3065  BlockDecl *TheBlock;
3066  bool HasBlockDeclRefExprs;
3067public:
3068  BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
3069    : Expr(BlockExprClass, ty, ty->isDependentType(), false),
3070      TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
3071
3072  /// \brief Build an empty block expression.
3073  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3074
3075  const BlockDecl *getBlockDecl() const { return TheBlock; }
3076  BlockDecl *getBlockDecl() { return TheBlock; }
3077  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3078
3079  // Convenience functions for probing the underlying BlockDecl.
3080  SourceLocation getCaretLocation() const;
3081  const Stmt *getBody() const;
3082  Stmt *getBody();
3083
3084  virtual SourceRange getSourceRange() const {
3085    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
3086  }
3087
3088  /// getFunctionType - Return the underlying function type for this block.
3089  const FunctionType *getFunctionType() const;
3090
3091  /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
3092  /// inside of the block that reference values outside the block.
3093  bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
3094  void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
3095
3096  static bool classof(const Stmt *T) {
3097    return T->getStmtClass() == BlockExprClass;
3098  }
3099  static bool classof(const BlockExpr *) { return true; }
3100
3101  // Iterators
3102  virtual child_iterator child_begin();
3103  virtual child_iterator child_end();
3104};
3105
3106/// BlockDeclRefExpr - A reference to a declared variable, function,
3107/// enum, etc.
3108class BlockDeclRefExpr : public Expr {
3109  ValueDecl *D;
3110  SourceLocation Loc;
3111  bool IsByRef : 1;
3112  bool ConstQualAdded : 1;
3113public:
3114  // FIXME: Fix type/value dependence!
3115  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
3116                   bool constAdded = false)
3117  : Expr(BlockDeclRefExprClass, t, false, false), D(d), Loc(l), IsByRef(ByRef),
3118    ConstQualAdded(constAdded) {}
3119
3120  // \brief Build an empty reference to a declared variable in a
3121  // block.
3122  explicit BlockDeclRefExpr(EmptyShell Empty)
3123    : Expr(BlockDeclRefExprClass, Empty) { }
3124
3125  ValueDecl *getDecl() { return D; }
3126  const ValueDecl *getDecl() const { return D; }
3127  void setDecl(ValueDecl *VD) { D = VD; }
3128
3129  SourceLocation getLocation() const { return Loc; }
3130  void setLocation(SourceLocation L) { Loc = L; }
3131
3132  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
3133
3134  bool isByRef() const { return IsByRef; }
3135  void setByRef(bool BR) { IsByRef = BR; }
3136
3137  bool isConstQualAdded() const { return ConstQualAdded; }
3138  void setConstQualAdded(bool C) { ConstQualAdded = C; }
3139
3140  static bool classof(const Stmt *T) {
3141    return T->getStmtClass() == BlockDeclRefExprClass;
3142  }
3143  static bool classof(const BlockDeclRefExpr *) { return true; }
3144
3145  // Iterators
3146  virtual child_iterator child_begin();
3147  virtual child_iterator child_end();
3148};
3149
3150}  // end namespace clang
3151
3152#endif
3153