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