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