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