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