Expr.h revision 5cf86ba6b5a724bf91cb52feade1158f1fbeb605
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    case CK_DerivedToBase:
1662      assert(!BasePath.empty() && "Cast kind should have a base path!");
1663      break;
1664
1665    // FIXME: We should add inheritance paths for these.
1666    case CK_BaseToDerived:
1667    case CK_UncheckedDerivedToBase:
1668    case CK_BaseToDerivedMemberPointer:
1669    case CK_DerivedToBaseMemberPointer:
1670
1671    // These should not have an inheritance path.
1672    case CK_Unknown:
1673    case CK_BitCast:
1674    case CK_NoOp:
1675    case CK_Dynamic:
1676    case CK_ToUnion:
1677    case CK_ArrayToPointerDecay:
1678    case CK_FunctionToPointerDecay:
1679    case CK_NullToMemberPointer:
1680    case CK_UserDefinedConversion:
1681    case CK_ConstructorConversion:
1682    case CK_IntegralToPointer:
1683    case CK_PointerToIntegral:
1684    case CK_ToVoid:
1685    case CK_VectorSplat:
1686    case CK_IntegralCast:
1687    case CK_IntegralToFloating:
1688    case CK_FloatingToIntegral:
1689    case CK_FloatingCast:
1690    case CK_MemberPointerToBoolean:
1691    case CK_AnyPointerToObjCPointerCast:
1692    case CK_AnyPointerToBlockPointerCast:
1693      assert(BasePath.empty() && "Cast kind should not have a base path!");
1694      break;
1695    }
1696#endif
1697  }
1698
1699protected:
1700  CastExpr(StmtClass SC, QualType ty, const CastKind kind, Expr *op,
1701           CXXBaseSpecifierArray BasePath) :
1702    Expr(SC, ty,
1703         // Cast expressions are type-dependent if the type is
1704         // dependent (C++ [temp.dep.expr]p3).
1705         ty->isDependentType(),
1706         // Cast expressions are value-dependent if the type is
1707         // dependent or if the subexpression is value-dependent.
1708         ty->isDependentType() || (op && op->isValueDependent())),
1709    Kind(kind), Op(op), BasePath(BasePath) {
1710      CheckBasePath();
1711    }
1712
1713  /// \brief Construct an empty cast.
1714  CastExpr(StmtClass SC, EmptyShell Empty)
1715    : Expr(SC, Empty) { }
1716
1717  virtual void DoDestroy(ASTContext &C);
1718
1719public:
1720  CastKind getCastKind() const { return Kind; }
1721  void setCastKind(CastKind K) { Kind = K; }
1722  const char *getCastKindName() const;
1723
1724  Expr *getSubExpr() { return cast<Expr>(Op); }
1725  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1726  void setSubExpr(Expr *E) { Op = E; }
1727
1728  /// \brief Retrieve the cast subexpression as it was written in the source
1729  /// code, looking through any implicit casts or other intermediate nodes
1730  /// introduced by semantic analysis.
1731  Expr *getSubExprAsWritten();
1732  const Expr *getSubExprAsWritten() const {
1733    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
1734  }
1735
1736  const CXXBaseSpecifierArray& getBasePath() { return BasePath; }
1737
1738  static bool classof(const Stmt *T) {
1739    StmtClass SC = T->getStmtClass();
1740    if (SC >= CXXStaticCastExprClass && SC <= CXXFunctionalCastExprClass)
1741      return true;
1742
1743    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
1744      return true;
1745
1746    return false;
1747  }
1748  static bool classof(const CastExpr *) { return true; }
1749
1750  // Iterators
1751  virtual child_iterator child_begin();
1752  virtual child_iterator child_end();
1753};
1754
1755/// ImplicitCastExpr - Allows us to explicitly represent implicit type
1756/// conversions, which have no direct representation in the original
1757/// source code. For example: converting T[]->T*, void f()->void
1758/// (*f)(), float->double, short->int, etc.
1759///
1760/// In C, implicit casts always produce rvalues. However, in C++, an
1761/// implicit cast whose result is being bound to a reference will be
1762/// an lvalue. For example:
1763///
1764/// @code
1765/// class Base { };
1766/// class Derived : public Base { };
1767/// void f(Derived d) {
1768///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
1769/// }
1770/// @endcode
1771class ImplicitCastExpr : public CastExpr {
1772  /// LvalueCast - Whether this cast produces an lvalue.
1773  bool LvalueCast;
1774
1775public:
1776  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
1777                   CXXBaseSpecifierArray BasePath, bool Lvalue)
1778    : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePath),
1779    LvalueCast(Lvalue) { }
1780
1781  /// \brief Construct an empty implicit cast.
1782  explicit ImplicitCastExpr(EmptyShell Shell)
1783    : CastExpr(ImplicitCastExprClass, Shell) { }
1784
1785  virtual SourceRange getSourceRange() const {
1786    return getSubExpr()->getSourceRange();
1787  }
1788
1789  /// isLvalueCast - Whether this cast produces an lvalue.
1790  bool isLvalueCast() const { return LvalueCast; }
1791
1792  /// setLvalueCast - Set whether this cast produces an lvalue.
1793  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1794
1795  static bool classof(const Stmt *T) {
1796    return T->getStmtClass() == ImplicitCastExprClass;
1797  }
1798  static bool classof(const ImplicitCastExpr *) { return true; }
1799};
1800
1801/// ExplicitCastExpr - An explicit cast written in the source
1802/// code.
1803///
1804/// This class is effectively an abstract class, because it provides
1805/// the basic representation of an explicitly-written cast without
1806/// specifying which kind of cast (C cast, functional cast, static
1807/// cast, etc.) was written; specific derived classes represent the
1808/// particular style of cast and its location information.
1809///
1810/// Unlike implicit casts, explicit cast nodes have two different
1811/// types: the type that was written into the source code, and the
1812/// actual type of the expression as determined by semantic
1813/// analysis. These types may differ slightly. For example, in C++ one
1814/// can cast to a reference type, which indicates that the resulting
1815/// expression will be an lvalue. The reference type, however, will
1816/// not be used as the type of the expression.
1817class ExplicitCastExpr : public CastExpr {
1818  /// TInfo - Source type info for the (written) type
1819  /// this expression is casting to.
1820  TypeSourceInfo *TInfo;
1821
1822protected:
1823  ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind,
1824                   Expr *op, CXXBaseSpecifierArray BasePath,
1825                   TypeSourceInfo *writtenTy)
1826    : CastExpr(SC, exprTy, kind, op, BasePath), TInfo(writtenTy) {}
1827
1828  /// \brief Construct an empty explicit cast.
1829  ExplicitCastExpr(StmtClass SC, EmptyShell Shell)
1830    : CastExpr(SC, Shell) { }
1831
1832public:
1833  /// getTypeInfoAsWritten - Returns the type source info for the type
1834  /// that this expression is casting to.
1835  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
1836  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
1837
1838  /// getTypeAsWritten - Returns the type that this expression is
1839  /// casting to, as written in the source code.
1840  QualType getTypeAsWritten() const { return TInfo->getType(); }
1841
1842  static bool classof(const Stmt *T) {
1843    StmtClass SC = T->getStmtClass();
1844    if (SC >= CStyleCastExprClass && SC <= CStyleCastExprClass)
1845      return true;
1846    if (SC >= CXXStaticCastExprClass && SC <= CXXFunctionalCastExprClass)
1847      return true;
1848
1849    return false;
1850  }
1851  static bool classof(const ExplicitCastExpr *) { return true; }
1852};
1853
1854/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1855/// cast in C++ (C++ [expr.cast]), which uses the syntax
1856/// (Type)expr. For example: @c (int)f.
1857class CStyleCastExpr : public ExplicitCastExpr {
1858  SourceLocation LPLoc; // the location of the left paren
1859  SourceLocation RPLoc; // the location of the right paren
1860public:
1861  CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op,
1862                 CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy,
1863                 SourceLocation l, SourceLocation r)
1864    : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, BasePath,
1865                       writtenTy), LPLoc(l), RPLoc(r) {}
1866
1867  /// \brief Construct an empty C-style explicit cast.
1868  explicit CStyleCastExpr(EmptyShell Shell)
1869    : ExplicitCastExpr(CStyleCastExprClass, Shell) { }
1870
1871  SourceLocation getLParenLoc() const { return LPLoc; }
1872  void setLParenLoc(SourceLocation L) { LPLoc = L; }
1873
1874  SourceLocation getRParenLoc() const { return RPLoc; }
1875  void setRParenLoc(SourceLocation L) { RPLoc = L; }
1876
1877  virtual SourceRange getSourceRange() const {
1878    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1879  }
1880  static bool classof(const Stmt *T) {
1881    return T->getStmtClass() == CStyleCastExprClass;
1882  }
1883  static bool classof(const CStyleCastExpr *) { return true; }
1884};
1885
1886/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
1887///
1888/// This expression node kind describes a builtin binary operation,
1889/// such as "x + y" for integer values "x" and "y". The operands will
1890/// already have been converted to appropriate types (e.g., by
1891/// performing promotions or conversions).
1892///
1893/// In C++, where operators may be overloaded, a different kind of
1894/// expression node (CXXOperatorCallExpr) is used to express the
1895/// invocation of an overloaded operator with operator syntax. Within
1896/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
1897/// used to store an expression "x + y" depends on the subexpressions
1898/// for x and y. If neither x or y is type-dependent, and the "+"
1899/// operator resolves to a built-in operation, BinaryOperator will be
1900/// used to express the computation (x and y may still be
1901/// value-dependent). If either x or y is type-dependent, or if the
1902/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
1903/// be used to express the computation.
1904class BinaryOperator : public Expr {
1905public:
1906  enum Opcode {
1907    // Operators listed in order of precedence.
1908    // Note that additions to this should also update the StmtVisitor class.
1909    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
1910    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1911    Add, Sub,         // [C99 6.5.6] Additive operators.
1912    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1913    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1914    EQ, NE,           // [C99 6.5.9] Equality operators.
1915    And,              // [C99 6.5.10] Bitwise AND operator.
1916    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1917    Or,               // [C99 6.5.12] Bitwise OR operator.
1918    LAnd,             // [C99 6.5.13] Logical AND operator.
1919    LOr,              // [C99 6.5.14] Logical OR operator.
1920    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1921    DivAssign, RemAssign,
1922    AddAssign, SubAssign,
1923    ShlAssign, ShrAssign,
1924    AndAssign, XorAssign,
1925    OrAssign,
1926    Comma             // [C99 6.5.17] Comma operator.
1927  };
1928private:
1929  enum { LHS, RHS, END_EXPR };
1930  Stmt* SubExprs[END_EXPR];
1931  Opcode Opc;
1932  SourceLocation OpLoc;
1933public:
1934
1935  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1936                 SourceLocation opLoc)
1937    : Expr(BinaryOperatorClass, ResTy,
1938           lhs->isTypeDependent() || rhs->isTypeDependent(),
1939           lhs->isValueDependent() || rhs->isValueDependent()),
1940      Opc(opc), OpLoc(opLoc) {
1941    SubExprs[LHS] = lhs;
1942    SubExprs[RHS] = rhs;
1943    assert(!isCompoundAssignmentOp() &&
1944           "Use ArithAssignBinaryOperator for compound assignments");
1945  }
1946
1947  /// \brief Construct an empty binary operator.
1948  explicit BinaryOperator(EmptyShell Empty)
1949    : Expr(BinaryOperatorClass, Empty), Opc(Comma) { }
1950
1951  SourceLocation getOperatorLoc() const { return OpLoc; }
1952  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1953
1954  Opcode getOpcode() const { return Opc; }
1955  void setOpcode(Opcode O) { Opc = O; }
1956
1957  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1958  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1959  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1960  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1961
1962  virtual SourceRange getSourceRange() const {
1963    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1964  }
1965
1966  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1967  /// corresponds to, e.g. "<<=".
1968  static const char *getOpcodeStr(Opcode Op);
1969
1970  /// \brief Retrieve the binary opcode that corresponds to the given
1971  /// overloaded operator.
1972  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
1973
1974  /// \brief Retrieve the overloaded operator kind that corresponds to
1975  /// the given binary opcode.
1976  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1977
1978  /// predicates to categorize the respective opcodes.
1979  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1980  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1981  static bool isShiftOp(Opcode Opc) { return Opc == Shl || Opc == Shr; }
1982  bool isShiftOp() const { return isShiftOp(Opc); }
1983
1984  static bool isBitwiseOp(Opcode Opc) { return Opc >= And && Opc <= Or; }
1985  bool isBitwiseOp() const { return isBitwiseOp(Opc); }
1986
1987  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1988  bool isRelationalOp() const { return isRelationalOp(Opc); }
1989
1990  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1991  bool isEqualityOp() const { return isEqualityOp(Opc); }
1992
1993  static bool isComparisonOp(Opcode Opc) { return Opc >= LT && Opc <= NE; }
1994  bool isComparisonOp() const { return isComparisonOp(Opc); }
1995
1996  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1997  bool isLogicalOp() const { return isLogicalOp(Opc); }
1998
1999  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
2000  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
2001  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
2002
2003  static bool classof(const Stmt *S) {
2004    return S->getStmtClass() == BinaryOperatorClass ||
2005           S->getStmtClass() == CompoundAssignOperatorClass;
2006  }
2007  static bool classof(const BinaryOperator *) { return true; }
2008
2009  // Iterators
2010  virtual child_iterator child_begin();
2011  virtual child_iterator child_end();
2012
2013protected:
2014  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2015                 SourceLocation opLoc, bool dead)
2016    : Expr(CompoundAssignOperatorClass, ResTy,
2017           lhs->isTypeDependent() || rhs->isTypeDependent(),
2018           lhs->isValueDependent() || rhs->isValueDependent()),
2019      Opc(opc), OpLoc(opLoc) {
2020    SubExprs[LHS] = lhs;
2021    SubExprs[RHS] = rhs;
2022  }
2023
2024  BinaryOperator(StmtClass SC, EmptyShell Empty)
2025    : Expr(SC, Empty), Opc(MulAssign) { }
2026};
2027
2028/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2029/// track of the type the operation is performed in.  Due to the semantics of
2030/// these operators, the operands are promoted, the aritmetic performed, an
2031/// implicit conversion back to the result type done, then the assignment takes
2032/// place.  This captures the intermediate type which the computation is done
2033/// in.
2034class CompoundAssignOperator : public BinaryOperator {
2035  QualType ComputationLHSType;
2036  QualType ComputationResultType;
2037public:
2038  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
2039                         QualType ResType, QualType CompLHSType,
2040                         QualType CompResultType,
2041                         SourceLocation OpLoc)
2042    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
2043      ComputationLHSType(CompLHSType),
2044      ComputationResultType(CompResultType) {
2045    assert(isCompoundAssignmentOp() &&
2046           "Only should be used for compound assignments");
2047  }
2048
2049  /// \brief Build an empty compound assignment operator expression.
2050  explicit CompoundAssignOperator(EmptyShell Empty)
2051    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2052
2053  // The two computation types are the type the LHS is converted
2054  // to for the computation and the type of the result; the two are
2055  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2056  QualType getComputationLHSType() const { return ComputationLHSType; }
2057  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2058
2059  QualType getComputationResultType() const { return ComputationResultType; }
2060  void setComputationResultType(QualType T) { ComputationResultType = T; }
2061
2062  static bool classof(const CompoundAssignOperator *) { return true; }
2063  static bool classof(const Stmt *S) {
2064    return S->getStmtClass() == CompoundAssignOperatorClass;
2065  }
2066};
2067
2068/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
2069/// GNU "missing LHS" extension is in use.
2070///
2071class ConditionalOperator : public Expr {
2072  enum { COND, LHS, RHS, END_EXPR };
2073  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2074  SourceLocation QuestionLoc, ColonLoc;
2075public:
2076  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2077                      SourceLocation CLoc, Expr *rhs, QualType t)
2078    : Expr(ConditionalOperatorClass, t,
2079           // FIXME: the type of the conditional operator doesn't
2080           // depend on the type of the conditional, but the standard
2081           // seems to imply that it could. File a bug!
2082           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
2083           (cond->isValueDependent() ||
2084            (lhs && lhs->isValueDependent()) ||
2085            (rhs && rhs->isValueDependent()))),
2086      QuestionLoc(QLoc),
2087      ColonLoc(CLoc) {
2088    SubExprs[COND] = cond;
2089    SubExprs[LHS] = lhs;
2090    SubExprs[RHS] = rhs;
2091  }
2092
2093  /// \brief Build an empty conditional operator.
2094  explicit ConditionalOperator(EmptyShell Empty)
2095    : Expr(ConditionalOperatorClass, Empty) { }
2096
2097  // getCond - Return the expression representing the condition for
2098  //  the ?: operator.
2099  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2100  void setCond(Expr *E) { SubExprs[COND] = E; }
2101
2102  // getTrueExpr - Return the subexpression representing the value of the ?:
2103  //  expression if the condition evaluates to true.  In most cases this value
2104  //  will be the same as getLHS() except a GCC extension allows the left
2105  //  subexpression to be omitted, and instead of the condition be returned.
2106  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
2107  //  is only evaluated once.
2108  Expr *getTrueExpr() const {
2109    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
2110  }
2111
2112  // getTrueExpr - Return the subexpression representing the value of the ?:
2113  // expression if the condition evaluates to false. This is the same as getRHS.
2114  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2115
2116  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
2117  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2118
2119  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2120  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2121
2122  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2123  void setQuestionLoc(SourceLocation L) { QuestionLoc = L; }
2124
2125  SourceLocation getColonLoc() const { return ColonLoc; }
2126  void setColonLoc(SourceLocation L) { ColonLoc = L; }
2127
2128  virtual SourceRange getSourceRange() const {
2129    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2130  }
2131  static bool classof(const Stmt *T) {
2132    return T->getStmtClass() == ConditionalOperatorClass;
2133  }
2134  static bool classof(const ConditionalOperator *) { return true; }
2135
2136  // Iterators
2137  virtual child_iterator child_begin();
2138  virtual child_iterator child_end();
2139};
2140
2141/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2142class AddrLabelExpr : public Expr {
2143  SourceLocation AmpAmpLoc, LabelLoc;
2144  LabelStmt *Label;
2145public:
2146  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
2147                QualType t)
2148    : Expr(AddrLabelExprClass, t, false, false),
2149      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2150
2151  /// \brief Build an empty address of a label expression.
2152  explicit AddrLabelExpr(EmptyShell Empty)
2153    : Expr(AddrLabelExprClass, Empty) { }
2154
2155  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2156  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2157  SourceLocation getLabelLoc() const { return LabelLoc; }
2158  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2159
2160  virtual SourceRange getSourceRange() const {
2161    return SourceRange(AmpAmpLoc, LabelLoc);
2162  }
2163
2164  LabelStmt *getLabel() const { return Label; }
2165  void setLabel(LabelStmt *S) { Label = S; }
2166
2167  static bool classof(const Stmt *T) {
2168    return T->getStmtClass() == AddrLabelExprClass;
2169  }
2170  static bool classof(const AddrLabelExpr *) { return true; }
2171
2172  // Iterators
2173  virtual child_iterator child_begin();
2174  virtual child_iterator child_end();
2175};
2176
2177/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2178/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2179/// takes the value of the last subexpression.
2180class StmtExpr : public Expr {
2181  Stmt *SubStmt;
2182  SourceLocation LParenLoc, RParenLoc;
2183public:
2184  // FIXME: Does type-dependence need to be computed differently?
2185  StmtExpr(CompoundStmt *substmt, QualType T,
2186           SourceLocation lp, SourceLocation rp) :
2187    Expr(StmtExprClass, T, T->isDependentType(), false),
2188    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2189
2190  /// \brief Build an empty statement expression.
2191  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2192
2193  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2194  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2195  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2196
2197  virtual SourceRange getSourceRange() const {
2198    return SourceRange(LParenLoc, RParenLoc);
2199  }
2200
2201  SourceLocation getLParenLoc() const { return LParenLoc; }
2202  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2203  SourceLocation getRParenLoc() const { return RParenLoc; }
2204  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2205
2206  static bool classof(const Stmt *T) {
2207    return T->getStmtClass() == StmtExprClass;
2208  }
2209  static bool classof(const StmtExpr *) { return true; }
2210
2211  // Iterators
2212  virtual child_iterator child_begin();
2213  virtual child_iterator child_end();
2214};
2215
2216/// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
2217/// This AST node represents a function that returns 1 if two *types* (not
2218/// expressions) are compatible. The result of this built-in function can be
2219/// used in integer constant expressions.
2220class TypesCompatibleExpr : public Expr {
2221  QualType Type1;
2222  QualType Type2;
2223  SourceLocation BuiltinLoc, RParenLoc;
2224public:
2225  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
2226                      QualType t1, QualType t2, SourceLocation RP) :
2227    Expr(TypesCompatibleExprClass, ReturnType, false, false),
2228    Type1(t1), Type2(t2), BuiltinLoc(BLoc), RParenLoc(RP) {}
2229
2230  /// \brief Build an empty __builtin_type_compatible_p expression.
2231  explicit TypesCompatibleExpr(EmptyShell Empty)
2232    : Expr(TypesCompatibleExprClass, Empty) { }
2233
2234  QualType getArgType1() const { return Type1; }
2235  void setArgType1(QualType T) { Type1 = T; }
2236  QualType getArgType2() const { return Type2; }
2237  void setArgType2(QualType T) { Type2 = T; }
2238
2239  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2240  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2241
2242  SourceLocation getRParenLoc() const { return RParenLoc; }
2243  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2244
2245  virtual SourceRange getSourceRange() const {
2246    return SourceRange(BuiltinLoc, RParenLoc);
2247  }
2248  static bool classof(const Stmt *T) {
2249    return T->getStmtClass() == TypesCompatibleExprClass;
2250  }
2251  static bool classof(const TypesCompatibleExpr *) { return true; }
2252
2253  // Iterators
2254  virtual child_iterator child_begin();
2255  virtual child_iterator child_end();
2256};
2257
2258/// ShuffleVectorExpr - clang-specific builtin-in function
2259/// __builtin_shufflevector.
2260/// This AST node represents a operator that does a constant
2261/// shuffle, similar to LLVM's shufflevector instruction. It takes
2262/// two vectors and a variable number of constant indices,
2263/// and returns the appropriately shuffled vector.
2264class ShuffleVectorExpr : public Expr {
2265  SourceLocation BuiltinLoc, RParenLoc;
2266
2267  // SubExprs - the list of values passed to the __builtin_shufflevector
2268  // function. The first two are vectors, and the rest are constant
2269  // indices.  The number of values in this list is always
2270  // 2+the number of indices in the vector type.
2271  Stmt **SubExprs;
2272  unsigned NumExprs;
2273
2274protected:
2275  virtual void DoDestroy(ASTContext &C);
2276
2277public:
2278  // FIXME: Can a shufflevector be value-dependent?  Does type-dependence need
2279  // to be computed differently?
2280  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2281                    QualType Type, SourceLocation BLoc,
2282                    SourceLocation RP) :
2283    Expr(ShuffleVectorExprClass, Type, Type->isDependentType(), false),
2284    BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) {
2285
2286    SubExprs = new (C) Stmt*[nexpr];
2287    for (unsigned i = 0; i < nexpr; i++)
2288      SubExprs[i] = args[i];
2289  }
2290
2291  /// \brief Build an empty vector-shuffle expression.
2292  explicit ShuffleVectorExpr(EmptyShell Empty)
2293    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
2294
2295  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2296  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2297
2298  SourceLocation getRParenLoc() const { return RParenLoc; }
2299  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2300
2301  virtual SourceRange getSourceRange() const {
2302    return SourceRange(BuiltinLoc, RParenLoc);
2303  }
2304  static bool classof(const Stmt *T) {
2305    return T->getStmtClass() == ShuffleVectorExprClass;
2306  }
2307  static bool classof(const ShuffleVectorExpr *) { return true; }
2308
2309  ~ShuffleVectorExpr() {}
2310
2311  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
2312  /// constant expression, the actual arguments passed in, and the function
2313  /// pointers.
2314  unsigned getNumSubExprs() const { return NumExprs; }
2315
2316  /// getExpr - Return the Expr at the specified index.
2317  Expr *getExpr(unsigned Index) {
2318    assert((Index < NumExprs) && "Arg access out of range!");
2319    return cast<Expr>(SubExprs[Index]);
2320  }
2321  const Expr *getExpr(unsigned Index) const {
2322    assert((Index < NumExprs) && "Arg access out of range!");
2323    return cast<Expr>(SubExprs[Index]);
2324  }
2325
2326  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
2327
2328  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
2329    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
2330    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
2331  }
2332
2333  // Iterators
2334  virtual child_iterator child_begin();
2335  virtual child_iterator child_end();
2336};
2337
2338/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
2339/// This AST node is similar to the conditional operator (?:) in C, with
2340/// the following exceptions:
2341/// - the test expression must be a integer constant expression.
2342/// - the expression returned acts like the chosen subexpression in every
2343///   visible way: the type is the same as that of the chosen subexpression,
2344///   and all predicates (whether it's an l-value, whether it's an integer
2345///   constant expression, etc.) return the same result as for the chosen
2346///   sub-expression.
2347class ChooseExpr : public Expr {
2348  enum { COND, LHS, RHS, END_EXPR };
2349  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2350  SourceLocation BuiltinLoc, RParenLoc;
2351public:
2352  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
2353             SourceLocation RP, bool TypeDependent, bool ValueDependent)
2354    : Expr(ChooseExprClass, t, TypeDependent, ValueDependent),
2355      BuiltinLoc(BLoc), RParenLoc(RP) {
2356      SubExprs[COND] = cond;
2357      SubExprs[LHS] = lhs;
2358      SubExprs[RHS] = rhs;
2359    }
2360
2361  /// \brief Build an empty __builtin_choose_expr.
2362  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
2363
2364  /// isConditionTrue - Return whether the condition is true (i.e. not
2365  /// equal to zero).
2366  bool isConditionTrue(ASTContext &C) const;
2367
2368  /// getChosenSubExpr - Return the subexpression chosen according to the
2369  /// condition.
2370  Expr *getChosenSubExpr(ASTContext &C) const {
2371    return isConditionTrue(C) ? getLHS() : getRHS();
2372  }
2373
2374  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2375  void setCond(Expr *E) { SubExprs[COND] = E; }
2376  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2377  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2378  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2379  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2380
2381  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2382  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2383
2384  SourceLocation getRParenLoc() const { return RParenLoc; }
2385  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2386
2387  virtual SourceRange getSourceRange() const {
2388    return SourceRange(BuiltinLoc, RParenLoc);
2389  }
2390  static bool classof(const Stmt *T) {
2391    return T->getStmtClass() == ChooseExprClass;
2392  }
2393  static bool classof(const ChooseExpr *) { return true; }
2394
2395  // Iterators
2396  virtual child_iterator child_begin();
2397  virtual child_iterator child_end();
2398};
2399
2400/// GNUNullExpr - Implements the GNU __null extension, which is a name
2401/// for a null pointer constant that has integral type (e.g., int or
2402/// long) and is the same size and alignment as a pointer. The __null
2403/// extension is typically only used by system headers, which define
2404/// NULL as __null in C++ rather than using 0 (which is an integer
2405/// that may not match the size of a pointer).
2406class GNUNullExpr : public Expr {
2407  /// TokenLoc - The location of the __null keyword.
2408  SourceLocation TokenLoc;
2409
2410public:
2411  GNUNullExpr(QualType Ty, SourceLocation Loc)
2412    : Expr(GNUNullExprClass, Ty, false, false), TokenLoc(Loc) { }
2413
2414  /// \brief Build an empty GNU __null expression.
2415  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
2416
2417  /// getTokenLocation - The location of the __null token.
2418  SourceLocation getTokenLocation() const { return TokenLoc; }
2419  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
2420
2421  virtual SourceRange getSourceRange() const {
2422    return SourceRange(TokenLoc);
2423  }
2424  static bool classof(const Stmt *T) {
2425    return T->getStmtClass() == GNUNullExprClass;
2426  }
2427  static bool classof(const GNUNullExpr *) { return true; }
2428
2429  // Iterators
2430  virtual child_iterator child_begin();
2431  virtual child_iterator child_end();
2432};
2433
2434/// VAArgExpr, used for the builtin function __builtin_va_arg.
2435class VAArgExpr : public Expr {
2436  Stmt *Val;
2437  SourceLocation BuiltinLoc, RParenLoc;
2438public:
2439  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
2440    : Expr(VAArgExprClass, t, t->isDependentType(), false),
2441      Val(e),
2442      BuiltinLoc(BLoc),
2443      RParenLoc(RPLoc) { }
2444
2445  /// \brief Create an empty __builtin_va_arg expression.
2446  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
2447
2448  const Expr *getSubExpr() const { return cast<Expr>(Val); }
2449  Expr *getSubExpr() { return cast<Expr>(Val); }
2450  void setSubExpr(Expr *E) { Val = E; }
2451
2452  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2453  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2454
2455  SourceLocation getRParenLoc() const { return RParenLoc; }
2456  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2457
2458  virtual SourceRange getSourceRange() const {
2459    return SourceRange(BuiltinLoc, RParenLoc);
2460  }
2461  static bool classof(const Stmt *T) {
2462    return T->getStmtClass() == VAArgExprClass;
2463  }
2464  static bool classof(const VAArgExpr *) { return true; }
2465
2466  // Iterators
2467  virtual child_iterator child_begin();
2468  virtual child_iterator child_end();
2469};
2470
2471/// @brief Describes an C or C++ initializer list.
2472///
2473/// InitListExpr describes an initializer list, which can be used to
2474/// initialize objects of different types, including
2475/// struct/class/union types, arrays, and vectors. For example:
2476///
2477/// @code
2478/// struct foo x = { 1, { 2, 3 } };
2479/// @endcode
2480///
2481/// Prior to semantic analysis, an initializer list will represent the
2482/// initializer list as written by the user, but will have the
2483/// placeholder type "void". This initializer list is called the
2484/// syntactic form of the initializer, and may contain C99 designated
2485/// initializers (represented as DesignatedInitExprs), initializations
2486/// of subobject members without explicit braces, and so on. Clients
2487/// interested in the original syntax of the initializer list should
2488/// use the syntactic form of the initializer list.
2489///
2490/// After semantic analysis, the initializer list will represent the
2491/// semantic form of the initializer, where the initializations of all
2492/// subobjects are made explicit with nested InitListExpr nodes and
2493/// C99 designators have been eliminated by placing the designated
2494/// initializations into the subobject they initialize. Additionally,
2495/// any "holes" in the initialization, where no initializer has been
2496/// specified for a particular subobject, will be replaced with
2497/// implicitly-generated ImplicitValueInitExpr expressions that
2498/// value-initialize the subobjects. Note, however, that the
2499/// initializer lists may still have fewer initializers than there are
2500/// elements to initialize within the object.
2501///
2502/// Given the semantic form of the initializer list, one can retrieve
2503/// the original syntactic form of that initializer list (if it
2504/// exists) using getSyntacticForm(). Since many initializer lists
2505/// have the same syntactic and semantic forms, getSyntacticForm() may
2506/// return NULL, indicating that the current initializer list also
2507/// serves as its syntactic form.
2508class InitListExpr : public Expr {
2509  // FIXME: Eliminate this vector in favor of ASTContext allocation
2510  typedef ASTVector<Stmt *> InitExprsTy;
2511  InitExprsTy InitExprs;
2512  SourceLocation LBraceLoc, RBraceLoc;
2513
2514  /// Contains the initializer list that describes the syntactic form
2515  /// written in the source code.
2516  InitListExpr *SyntacticForm;
2517
2518  /// If this initializer list initializes a union, specifies which
2519  /// field within the union will be initialized.
2520  FieldDecl *UnionFieldInit;
2521
2522  /// Whether this initializer list originally had a GNU array-range
2523  /// designator in it. This is a temporary marker used by CodeGen.
2524  bool HadArrayRangeDesignator;
2525
2526public:
2527  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
2528               Expr **initexprs, unsigned numinits,
2529               SourceLocation rbraceloc);
2530
2531  /// \brief Build an empty initializer list.
2532  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
2533    : Expr(InitListExprClass, Empty), InitExprs(C) { }
2534
2535  unsigned getNumInits() const { return InitExprs.size(); }
2536
2537  const Expr* getInit(unsigned Init) const {
2538    assert(Init < getNumInits() && "Initializer access out of range!");
2539    return cast_or_null<Expr>(InitExprs[Init]);
2540  }
2541
2542  Expr* getInit(unsigned Init) {
2543    assert(Init < getNumInits() && "Initializer access out of range!");
2544    return cast_or_null<Expr>(InitExprs[Init]);
2545  }
2546
2547  void setInit(unsigned Init, Expr *expr) {
2548    assert(Init < getNumInits() && "Initializer access out of range!");
2549    InitExprs[Init] = expr;
2550  }
2551
2552  /// \brief Reserve space for some number of initializers.
2553  void reserveInits(ASTContext &C, unsigned NumInits);
2554
2555  /// @brief Specify the number of initializers
2556  ///
2557  /// If there are more than @p NumInits initializers, the remaining
2558  /// initializers will be destroyed. If there are fewer than @p
2559  /// NumInits initializers, NULL expressions will be added for the
2560  /// unknown initializers.
2561  void resizeInits(ASTContext &Context, unsigned NumInits);
2562
2563  /// @brief Updates the initializer at index @p Init with the new
2564  /// expression @p expr, and returns the old expression at that
2565  /// location.
2566  ///
2567  /// When @p Init is out of range for this initializer list, the
2568  /// initializer list will be extended with NULL expressions to
2569  /// accomodate the new entry.
2570  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
2571
2572  /// \brief If this initializes a union, specifies which field in the
2573  /// union to initialize.
2574  ///
2575  /// Typically, this field is the first named field within the
2576  /// union. However, a designated initializer can specify the
2577  /// initialization of a different field within the union.
2578  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2579  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2580
2581  // Explicit InitListExpr's originate from source code (and have valid source
2582  // locations). Implicit InitListExpr's are created by the semantic analyzer.
2583  bool isExplicit() {
2584    return LBraceLoc.isValid() && RBraceLoc.isValid();
2585  }
2586
2587  SourceLocation getLBraceLoc() const { return LBraceLoc; }
2588  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2589  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2590  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2591
2592  /// @brief Retrieve the initializer list that describes the
2593  /// syntactic form of the initializer.
2594  ///
2595  ///
2596  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2597  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2598
2599  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2600  void sawArrayRangeDesignator(bool ARD = true) {
2601    HadArrayRangeDesignator = ARD;
2602  }
2603
2604  virtual SourceRange getSourceRange() const {
2605    return SourceRange(LBraceLoc, RBraceLoc);
2606  }
2607  static bool classof(const Stmt *T) {
2608    return T->getStmtClass() == InitListExprClass;
2609  }
2610  static bool classof(const InitListExpr *) { return true; }
2611
2612  // Iterators
2613  virtual child_iterator child_begin();
2614  virtual child_iterator child_end();
2615
2616  typedef InitExprsTy::iterator iterator;
2617  typedef InitExprsTy::reverse_iterator reverse_iterator;
2618
2619  iterator begin() { return InitExprs.begin(); }
2620  iterator end() { return InitExprs.end(); }
2621  reverse_iterator rbegin() { return InitExprs.rbegin(); }
2622  reverse_iterator rend() { return InitExprs.rend(); }
2623};
2624
2625/// @brief Represents a C99 designated initializer expression.
2626///
2627/// A designated initializer expression (C99 6.7.8) contains one or
2628/// more designators (which can be field designators, array
2629/// designators, or GNU array-range designators) followed by an
2630/// expression that initializes the field or element(s) that the
2631/// designators refer to. For example, given:
2632///
2633/// @code
2634/// struct point {
2635///   double x;
2636///   double y;
2637/// };
2638/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2639/// @endcode
2640///
2641/// The InitListExpr contains three DesignatedInitExprs, the first of
2642/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2643/// designators, one array designator for @c [2] followed by one field
2644/// designator for @c .y. The initalization expression will be 1.0.
2645class DesignatedInitExpr : public Expr {
2646public:
2647  /// \brief Forward declaration of the Designator class.
2648  class Designator;
2649
2650private:
2651  /// The location of the '=' or ':' prior to the actual initializer
2652  /// expression.
2653  SourceLocation EqualOrColonLoc;
2654
2655  /// Whether this designated initializer used the GNU deprecated
2656  /// syntax rather than the C99 '=' syntax.
2657  bool GNUSyntax : 1;
2658
2659  /// The number of designators in this initializer expression.
2660  unsigned NumDesignators : 15;
2661
2662  /// \brief The designators in this designated initialization
2663  /// expression.
2664  Designator *Designators;
2665
2666  /// The number of subexpressions of this initializer expression,
2667  /// which contains both the initializer and any additional
2668  /// expressions used by array and array-range designators.
2669  unsigned NumSubExprs : 16;
2670
2671
2672  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
2673                     const Designator *Designators,
2674                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
2675                     Expr **IndexExprs, unsigned NumIndexExprs,
2676                     Expr *Init);
2677
2678  explicit DesignatedInitExpr(unsigned NumSubExprs)
2679    : Expr(DesignatedInitExprClass, EmptyShell()),
2680      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
2681
2682protected:
2683  virtual void DoDestroy(ASTContext &C);
2684
2685  void DestroyDesignators(ASTContext &C);
2686
2687public:
2688  /// A field designator, e.g., ".x".
2689  struct FieldDesignator {
2690    /// Refers to the field that is being initialized. The low bit
2691    /// of this field determines whether this is actually a pointer
2692    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
2693    /// initially constructed, a field designator will store an
2694    /// IdentifierInfo*. After semantic analysis has resolved that
2695    /// name, the field designator will instead store a FieldDecl*.
2696    uintptr_t NameOrField;
2697
2698    /// The location of the '.' in the designated initializer.
2699    unsigned DotLoc;
2700
2701    /// The location of the field name in the designated initializer.
2702    unsigned FieldLoc;
2703  };
2704
2705  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2706  struct ArrayOrRangeDesignator {
2707    /// Location of the first index expression within the designated
2708    /// initializer expression's list of subexpressions.
2709    unsigned Index;
2710    /// The location of the '[' starting the array range designator.
2711    unsigned LBracketLoc;
2712    /// The location of the ellipsis separating the start and end
2713    /// indices. Only valid for GNU array-range designators.
2714    unsigned EllipsisLoc;
2715    /// The location of the ']' terminating the array range designator.
2716    unsigned RBracketLoc;
2717  };
2718
2719  /// @brief Represents a single C99 designator.
2720  ///
2721  /// @todo This class is infuriatingly similar to clang::Designator,
2722  /// but minor differences (storing indices vs. storing pointers)
2723  /// keep us from reusing it. Try harder, later, to rectify these
2724  /// differences.
2725  class Designator {
2726    /// @brief The kind of designator this describes.
2727    enum {
2728      FieldDesignator,
2729      ArrayDesignator,
2730      ArrayRangeDesignator
2731    } Kind;
2732
2733    union {
2734      /// A field designator, e.g., ".x".
2735      struct FieldDesignator Field;
2736      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2737      struct ArrayOrRangeDesignator ArrayOrRange;
2738    };
2739    friend class DesignatedInitExpr;
2740
2741  public:
2742    Designator() {}
2743
2744    /// @brief Initializes a field designator.
2745    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
2746               SourceLocation FieldLoc)
2747      : Kind(FieldDesignator) {
2748      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
2749      Field.DotLoc = DotLoc.getRawEncoding();
2750      Field.FieldLoc = FieldLoc.getRawEncoding();
2751    }
2752
2753    /// @brief Initializes an array designator.
2754    Designator(unsigned Index, SourceLocation LBracketLoc,
2755               SourceLocation RBracketLoc)
2756      : Kind(ArrayDesignator) {
2757      ArrayOrRange.Index = Index;
2758      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2759      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
2760      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2761    }
2762
2763    /// @brief Initializes a GNU array-range designator.
2764    Designator(unsigned Index, SourceLocation LBracketLoc,
2765               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
2766      : Kind(ArrayRangeDesignator) {
2767      ArrayOrRange.Index = Index;
2768      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2769      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
2770      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2771    }
2772
2773    bool isFieldDesignator() const { return Kind == FieldDesignator; }
2774    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
2775    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
2776
2777    IdentifierInfo * getFieldName();
2778
2779    FieldDecl *getField() {
2780      assert(Kind == FieldDesignator && "Only valid on a field designator");
2781      if (Field.NameOrField & 0x01)
2782        return 0;
2783      else
2784        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
2785    }
2786
2787    void setField(FieldDecl *FD) {
2788      assert(Kind == FieldDesignator && "Only valid on a field designator");
2789      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
2790    }
2791
2792    SourceLocation getDotLoc() const {
2793      assert(Kind == FieldDesignator && "Only valid on a field designator");
2794      return SourceLocation::getFromRawEncoding(Field.DotLoc);
2795    }
2796
2797    SourceLocation getFieldLoc() const {
2798      assert(Kind == FieldDesignator && "Only valid on a field designator");
2799      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
2800    }
2801
2802    SourceLocation getLBracketLoc() const {
2803      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2804             "Only valid on an array or array-range designator");
2805      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
2806    }
2807
2808    SourceLocation getRBracketLoc() const {
2809      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2810             "Only valid on an array or array-range designator");
2811      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
2812    }
2813
2814    SourceLocation getEllipsisLoc() const {
2815      assert(Kind == ArrayRangeDesignator &&
2816             "Only valid on an array-range designator");
2817      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
2818    }
2819
2820    unsigned getFirstExprIndex() const {
2821      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2822             "Only valid on an array or array-range designator");
2823      return ArrayOrRange.Index;
2824    }
2825
2826    SourceLocation getStartLocation() const {
2827      if (Kind == FieldDesignator)
2828        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
2829      else
2830        return getLBracketLoc();
2831    }
2832  };
2833
2834  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
2835                                    unsigned NumDesignators,
2836                                    Expr **IndexExprs, unsigned NumIndexExprs,
2837                                    SourceLocation EqualOrColonLoc,
2838                                    bool GNUSyntax, Expr *Init);
2839
2840  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
2841
2842  /// @brief Returns the number of designators in this initializer.
2843  unsigned size() const { return NumDesignators; }
2844
2845  // Iterator access to the designators.
2846  typedef Designator* designators_iterator;
2847  designators_iterator designators_begin() { return Designators; }
2848  designators_iterator designators_end() {
2849    return Designators + NumDesignators;
2850  }
2851
2852  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
2853
2854  void setDesignators(ASTContext &C, const Designator *Desigs,
2855                      unsigned NumDesigs);
2856
2857  Expr *getArrayIndex(const Designator& D);
2858  Expr *getArrayRangeStart(const Designator& D);
2859  Expr *getArrayRangeEnd(const Designator& D);
2860
2861  /// @brief Retrieve the location of the '=' that precedes the
2862  /// initializer value itself, if present.
2863  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
2864  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
2865
2866  /// @brief Determines whether this designated initializer used the
2867  /// deprecated GNU syntax for designated initializers.
2868  bool usesGNUSyntax() const { return GNUSyntax; }
2869  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
2870
2871  /// @brief Retrieve the initializer value.
2872  Expr *getInit() const {
2873    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
2874  }
2875
2876  void setInit(Expr *init) {
2877    *child_begin() = init;
2878  }
2879
2880  /// \brief Retrieve the total number of subexpressions in this
2881  /// designated initializer expression, including the actual
2882  /// initialized value and any expressions that occur within array
2883  /// and array-range designators.
2884  unsigned getNumSubExprs() const { return NumSubExprs; }
2885
2886  Expr *getSubExpr(unsigned Idx) {
2887    assert(Idx < NumSubExprs && "Subscript out of range");
2888    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2889    Ptr += sizeof(DesignatedInitExpr);
2890    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
2891  }
2892
2893  void setSubExpr(unsigned Idx, Expr *E) {
2894    assert(Idx < NumSubExprs && "Subscript out of range");
2895    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2896    Ptr += sizeof(DesignatedInitExpr);
2897    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
2898  }
2899
2900  /// \brief Replaces the designator at index @p Idx with the series
2901  /// of designators in [First, Last).
2902  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
2903                        const Designator *Last);
2904
2905  virtual SourceRange getSourceRange() const;
2906
2907  static bool classof(const Stmt *T) {
2908    return T->getStmtClass() == DesignatedInitExprClass;
2909  }
2910  static bool classof(const DesignatedInitExpr *) { return true; }
2911
2912  // Iterators
2913  virtual child_iterator child_begin();
2914  virtual child_iterator child_end();
2915};
2916
2917/// \brief Represents an implicitly-generated value initialization of
2918/// an object of a given type.
2919///
2920/// Implicit value initializations occur within semantic initializer
2921/// list expressions (InitListExpr) as placeholders for subobject
2922/// initializations not explicitly specified by the user.
2923///
2924/// \see InitListExpr
2925class ImplicitValueInitExpr : public Expr {
2926public:
2927  explicit ImplicitValueInitExpr(QualType ty)
2928    : Expr(ImplicitValueInitExprClass, ty, false, false) { }
2929
2930  /// \brief Construct an empty implicit value initialization.
2931  explicit ImplicitValueInitExpr(EmptyShell Empty)
2932    : Expr(ImplicitValueInitExprClass, Empty) { }
2933
2934  static bool classof(const Stmt *T) {
2935    return T->getStmtClass() == ImplicitValueInitExprClass;
2936  }
2937  static bool classof(const ImplicitValueInitExpr *) { return true; }
2938
2939  virtual SourceRange getSourceRange() const {
2940    return SourceRange();
2941  }
2942
2943  // Iterators
2944  virtual child_iterator child_begin();
2945  virtual child_iterator child_end();
2946};
2947
2948
2949class ParenListExpr : public Expr {
2950  Stmt **Exprs;
2951  unsigned NumExprs;
2952  SourceLocation LParenLoc, RParenLoc;
2953
2954protected:
2955  virtual void DoDestroy(ASTContext& C);
2956
2957public:
2958  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
2959                unsigned numexprs, SourceLocation rparenloc);
2960
2961  ~ParenListExpr() {}
2962
2963  /// \brief Build an empty paren list.
2964  //explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
2965
2966  unsigned getNumExprs() const { return NumExprs; }
2967
2968  const Expr* getExpr(unsigned Init) const {
2969    assert(Init < getNumExprs() && "Initializer access out of range!");
2970    return cast_or_null<Expr>(Exprs[Init]);
2971  }
2972
2973  Expr* getExpr(unsigned Init) {
2974    assert(Init < getNumExprs() && "Initializer access out of range!");
2975    return cast_or_null<Expr>(Exprs[Init]);
2976  }
2977
2978  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
2979
2980  SourceLocation getLParenLoc() const { return LParenLoc; }
2981  SourceLocation getRParenLoc() const { return RParenLoc; }
2982
2983  virtual SourceRange getSourceRange() const {
2984    return SourceRange(LParenLoc, RParenLoc);
2985  }
2986  static bool classof(const Stmt *T) {
2987    return T->getStmtClass() == ParenListExprClass;
2988  }
2989  static bool classof(const ParenListExpr *) { return true; }
2990
2991  // Iterators
2992  virtual child_iterator child_begin();
2993  virtual child_iterator child_end();
2994};
2995
2996
2997//===----------------------------------------------------------------------===//
2998// Clang Extensions
2999//===----------------------------------------------------------------------===//
3000
3001
3002/// ExtVectorElementExpr - This represents access to specific elements of a
3003/// vector, and may occur on the left hand side or right hand side.  For example
3004/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3005///
3006/// Note that the base may have either vector or pointer to vector type, just
3007/// like a struct field reference.
3008///
3009class ExtVectorElementExpr : public Expr {
3010  Stmt *Base;
3011  IdentifierInfo *Accessor;
3012  SourceLocation AccessorLoc;
3013public:
3014  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
3015                       SourceLocation loc)
3016    : Expr(ExtVectorElementExprClass, ty, base->isTypeDependent(),
3017           base->isValueDependent()),
3018      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3019
3020  /// \brief Build an empty vector element expression.
3021  explicit ExtVectorElementExpr(EmptyShell Empty)
3022    : Expr(ExtVectorElementExprClass, Empty) { }
3023
3024  const Expr *getBase() const { return cast<Expr>(Base); }
3025  Expr *getBase() { return cast<Expr>(Base); }
3026  void setBase(Expr *E) { Base = E; }
3027
3028  IdentifierInfo &getAccessor() const { return *Accessor; }
3029  void setAccessor(IdentifierInfo *II) { Accessor = II; }
3030
3031  SourceLocation getAccessorLoc() const { return AccessorLoc; }
3032  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3033
3034  /// getNumElements - Get the number of components being selected.
3035  unsigned getNumElements() const;
3036
3037  /// containsDuplicateElements - Return true if any element access is
3038  /// repeated.
3039  bool containsDuplicateElements() const;
3040
3041  /// getEncodedElementAccess - Encode the elements accessed into an llvm
3042  /// aggregate Constant of ConstantInt(s).
3043  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3044
3045  virtual SourceRange getSourceRange() const {
3046    return SourceRange(getBase()->getLocStart(), AccessorLoc);
3047  }
3048
3049  /// isArrow - Return true if the base expression is a pointer to vector,
3050  /// return false if the base expression is a vector.
3051  bool isArrow() const;
3052
3053  static bool classof(const Stmt *T) {
3054    return T->getStmtClass() == ExtVectorElementExprClass;
3055  }
3056  static bool classof(const ExtVectorElementExpr *) { return true; }
3057
3058  // Iterators
3059  virtual child_iterator child_begin();
3060  virtual child_iterator child_end();
3061};
3062
3063
3064/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3065/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3066class BlockExpr : public Expr {
3067protected:
3068  BlockDecl *TheBlock;
3069  bool HasBlockDeclRefExprs;
3070public:
3071  BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
3072    : Expr(BlockExprClass, ty, ty->isDependentType(), false),
3073      TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
3074
3075  /// \brief Build an empty block expression.
3076  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3077
3078  const BlockDecl *getBlockDecl() const { return TheBlock; }
3079  BlockDecl *getBlockDecl() { return TheBlock; }
3080  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3081
3082  // Convenience functions for probing the underlying BlockDecl.
3083  SourceLocation getCaretLocation() const;
3084  const Stmt *getBody() const;
3085  Stmt *getBody();
3086
3087  virtual SourceRange getSourceRange() const {
3088    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
3089  }
3090
3091  /// getFunctionType - Return the underlying function type for this block.
3092  const FunctionType *getFunctionType() const;
3093
3094  /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
3095  /// inside of the block that reference values outside the block.
3096  bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
3097  void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
3098
3099  static bool classof(const Stmt *T) {
3100    return T->getStmtClass() == BlockExprClass;
3101  }
3102  static bool classof(const BlockExpr *) { return true; }
3103
3104  // Iterators
3105  virtual child_iterator child_begin();
3106  virtual child_iterator child_end();
3107};
3108
3109/// BlockDeclRefExpr - A reference to a declared variable, function,
3110/// enum, etc.
3111class BlockDeclRefExpr : public Expr {
3112  ValueDecl *D;
3113  SourceLocation Loc;
3114  bool IsByRef : 1;
3115  bool ConstQualAdded : 1;
3116public:
3117  // FIXME: Fix type/value dependence!
3118  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
3119                   bool constAdded = false)
3120  : Expr(BlockDeclRefExprClass, t, false, false), D(d), Loc(l), IsByRef(ByRef),
3121    ConstQualAdded(constAdded) {}
3122
3123  // \brief Build an empty reference to a declared variable in a
3124  // block.
3125  explicit BlockDeclRefExpr(EmptyShell Empty)
3126    : Expr(BlockDeclRefExprClass, Empty) { }
3127
3128  ValueDecl *getDecl() { return D; }
3129  const ValueDecl *getDecl() const { return D; }
3130  void setDecl(ValueDecl *VD) { D = VD; }
3131
3132  SourceLocation getLocation() const { return Loc; }
3133  void setLocation(SourceLocation L) { Loc = L; }
3134
3135  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
3136
3137  bool isByRef() const { return IsByRef; }
3138  void setByRef(bool BR) { IsByRef = BR; }
3139
3140  bool isConstQualAdded() const { return ConstQualAdded; }
3141  void setConstQualAdded(bool C) { ConstQualAdded = C; }
3142
3143  static bool classof(const Stmt *T) {
3144    return T->getStmtClass() == BlockDeclRefExprClass;
3145  }
3146  static bool classof(const BlockDeclRefExpr *) { return true; }
3147
3148  // Iterators
3149  virtual child_iterator child_begin();
3150  virtual child_iterator child_end();
3151};
3152
3153}  // end namespace clang
3154
3155#endif
3156