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