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