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