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