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