Expr.h revision a2338bc4c2887937478d302901fb41a53e14e6d6
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/ASTVector.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/OperationKinds.h"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/CharInfo.h"
26#include "clang/Basic/TypeTraits.h"
27#include "llvm/ADT/APFloat.h"
28#include "llvm/ADT/APSInt.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/Support/Compiler.h"
32
33namespace clang {
34  class APValue;
35  class ASTContext;
36  class BlockDecl;
37  class CXXBaseSpecifier;
38  class CXXMemberCallExpr;
39  class CXXOperatorCallExpr;
40  class CastExpr;
41  class Decl;
42  class IdentifierInfo;
43  class MaterializeTemporaryExpr;
44  class NamedDecl;
45  class ObjCPropertyRefExpr;
46  class OpaqueValueExpr;
47  class ParmVarDecl;
48  class TargetInfo;
49  class ValueDecl;
50
51/// \brief A simple array of base specifiers.
52typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
53
54/// \brief An adjustment to be made to the temporary created when emitting a
55/// reference binding, which accesses a particular subobject of that temporary.
56struct SubobjectAdjustment {
57  enum {
58    DerivedToBaseAdjustment,
59    FieldAdjustment,
60    MemberPointerAdjustment
61  } Kind;
62
63
64  struct DTB {
65    const CastExpr *BasePath;
66    const CXXRecordDecl *DerivedClass;
67  };
68
69  struct P {
70    const MemberPointerType *MPT;
71    Expr *RHS;
72  };
73
74  union {
75    struct DTB DerivedToBase;
76    FieldDecl *Field;
77    struct P Ptr;
78  };
79
80  SubobjectAdjustment(const CastExpr *BasePath,
81                      const CXXRecordDecl *DerivedClass)
82    : Kind(DerivedToBaseAdjustment) {
83    DerivedToBase.BasePath = BasePath;
84    DerivedToBase.DerivedClass = DerivedClass;
85  }
86
87  SubobjectAdjustment(FieldDecl *Field)
88    : Kind(FieldAdjustment) {
89    this->Field = Field;
90  }
91
92  SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
93    : Kind(MemberPointerAdjustment) {
94    this->Ptr.MPT = MPT;
95    this->Ptr.RHS = RHS;
96  }
97};
98
99/// Expr - This represents one expression.  Note that Expr's are subclasses of
100/// Stmt.  This allows an expression to be transparently used any place a Stmt
101/// is required.
102///
103class Expr : public Stmt {
104  QualType TR;
105
106protected:
107  Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
108       bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
109    : Stmt(SC)
110  {
111    ExprBits.TypeDependent = TD;
112    ExprBits.ValueDependent = VD;
113    ExprBits.InstantiationDependent = ID;
114    ExprBits.ValueKind = VK;
115    ExprBits.ObjectKind = OK;
116    ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
117    setType(T);
118  }
119
120  /// \brief Construct an empty expression.
121  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
122
123public:
124  QualType getType() const { return TR; }
125  void setType(QualType t) {
126    // In C++, the type of an expression is always adjusted so that it
127    // will not have reference type an expression will never have
128    // reference type (C++ [expr]p6). Use
129    // QualType::getNonReferenceType() to retrieve the non-reference
130    // type. Additionally, inspect Expr::isLvalue to determine whether
131    // an expression that is adjusted in this manner should be
132    // considered an lvalue.
133    assert((t.isNull() || !t->isReferenceType()) &&
134           "Expressions can't have reference type");
135
136    TR = t;
137  }
138
139  /// isValueDependent - Determines whether this expression is
140  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
141  /// array bound of "Chars" in the following example is
142  /// value-dependent.
143  /// @code
144  /// template<int Size, char (&Chars)[Size]> struct meta_string;
145  /// @endcode
146  bool isValueDependent() const { return ExprBits.ValueDependent; }
147
148  /// \brief Set whether this expression is value-dependent or not.
149  void setValueDependent(bool VD) {
150    ExprBits.ValueDependent = VD;
151    if (VD)
152      ExprBits.InstantiationDependent = true;
153  }
154
155  /// isTypeDependent - Determines whether this expression is
156  /// type-dependent (C++ [temp.dep.expr]), which means that its type
157  /// could change from one template instantiation to the next. For
158  /// example, the expressions "x" and "x + y" are type-dependent in
159  /// the following code, but "y" is not type-dependent:
160  /// @code
161  /// template<typename T>
162  /// void add(T x, int y) {
163  ///   x + y;
164  /// }
165  /// @endcode
166  bool isTypeDependent() const { return ExprBits.TypeDependent; }
167
168  /// \brief Set whether this expression is type-dependent or not.
169  void setTypeDependent(bool TD) {
170    ExprBits.TypeDependent = TD;
171    if (TD)
172      ExprBits.InstantiationDependent = true;
173  }
174
175  /// \brief Whether this expression is instantiation-dependent, meaning that
176  /// it depends in some way on a template parameter, even if neither its type
177  /// nor (constant) value can change due to the template instantiation.
178  ///
179  /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
180  /// instantiation-dependent (since it involves a template parameter \c T), but
181  /// is neither type- nor value-dependent, since the type of the inner
182  /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
183  /// \c sizeof is known.
184  ///
185  /// \code
186  /// template<typename T>
187  /// void f(T x, T y) {
188  ///   sizeof(sizeof(T() + T());
189  /// }
190  /// \endcode
191  ///
192  bool isInstantiationDependent() const {
193    return ExprBits.InstantiationDependent;
194  }
195
196  /// \brief Set whether this expression is instantiation-dependent or not.
197  void setInstantiationDependent(bool ID) {
198    ExprBits.InstantiationDependent = ID;
199  }
200
201  /// \brief Whether this expression contains an unexpanded parameter
202  /// pack (for C++11 variadic templates).
203  ///
204  /// Given the following function template:
205  ///
206  /// \code
207  /// template<typename F, typename ...Types>
208  /// void forward(const F &f, Types &&...args) {
209  ///   f(static_cast<Types&&>(args)...);
210  /// }
211  /// \endcode
212  ///
213  /// The expressions \c args and \c static_cast<Types&&>(args) both
214  /// contain parameter packs.
215  bool containsUnexpandedParameterPack() const {
216    return ExprBits.ContainsUnexpandedParameterPack;
217  }
218
219  /// \brief Set the bit that describes whether this expression
220  /// contains an unexpanded parameter pack.
221  void setContainsUnexpandedParameterPack(bool PP = true) {
222    ExprBits.ContainsUnexpandedParameterPack = PP;
223  }
224
225  /// getExprLoc - Return the preferred location for the arrow when diagnosing
226  /// a problem with a generic expression.
227  SourceLocation getExprLoc() const LLVM_READONLY;
228
229  /// isUnusedResultAWarning - Return true if this immediate expression should
230  /// be warned about if the result is unused.  If so, fill in expr, location,
231  /// and ranges with expr to warn on and source locations/ranges appropriate
232  /// for a warning.
233  bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
234                              SourceRange &R1, SourceRange &R2,
235                              ASTContext &Ctx) const;
236
237  /// isLValue - True if this expression is an "l-value" according to
238  /// the rules of the current language.  C and C++ give somewhat
239  /// different rules for this concept, but in general, the result of
240  /// an l-value expression identifies a specific object whereas the
241  /// result of an r-value expression is a value detached from any
242  /// specific storage.
243  ///
244  /// C++11 divides the concept of "r-value" into pure r-values
245  /// ("pr-values") and so-called expiring values ("x-values"), which
246  /// identify specific objects that can be safely cannibalized for
247  /// their resources.  This is an unfortunate abuse of terminology on
248  /// the part of the C++ committee.  In Clang, when we say "r-value",
249  /// we generally mean a pr-value.
250  bool isLValue() const { return getValueKind() == VK_LValue; }
251  bool isRValue() const { return getValueKind() == VK_RValue; }
252  bool isXValue() const { return getValueKind() == VK_XValue; }
253  bool isGLValue() const { return getValueKind() != VK_RValue; }
254
255  enum LValueClassification {
256    LV_Valid,
257    LV_NotObjectType,
258    LV_IncompleteVoidType,
259    LV_DuplicateVectorComponents,
260    LV_InvalidExpression,
261    LV_InvalidMessageExpression,
262    LV_MemberFunction,
263    LV_SubObjCPropertySetting,
264    LV_ClassTemporary,
265    LV_ArrayTemporary
266  };
267  /// Reasons why an expression might not be an l-value.
268  LValueClassification ClassifyLValue(ASTContext &Ctx) const;
269
270  enum isModifiableLvalueResult {
271    MLV_Valid,
272    MLV_NotObjectType,
273    MLV_IncompleteVoidType,
274    MLV_DuplicateVectorComponents,
275    MLV_InvalidExpression,
276    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
277    MLV_IncompleteType,
278    MLV_ConstQualified,
279    MLV_ArrayType,
280    MLV_ReadonlyProperty,
281    MLV_NoSetterProperty,
282    MLV_MemberFunction,
283    MLV_SubObjCPropertySetting,
284    MLV_InvalidMessageExpression,
285    MLV_ClassTemporary,
286    MLV_ArrayTemporary
287  };
288  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289  /// does not have an incomplete type, does not have a const-qualified type,
290  /// and if it is a structure or union, does not have any member (including,
291  /// recursively, any member or element of all contained aggregates or unions)
292  /// with a const-qualified type.
293  ///
294  /// \param Loc [in,out] - A source location which *may* be filled
295  /// in with the location of the expression making this a
296  /// non-modifiable lvalue, if specified.
297  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
298                                              SourceLocation *Loc = 0) const;
299
300  /// \brief The return type of classify(). Represents the C++11 expression
301  ///        taxonomy.
302  class Classification {
303  public:
304    /// \brief The various classification results. Most of these mean prvalue.
305    enum Kinds {
306      CL_LValue,
307      CL_XValue,
308      CL_Function, // Functions cannot be lvalues in C.
309      CL_Void, // Void cannot be an lvalue in C.
310      CL_AddressableVoid, // Void expression whose address can be taken in C.
311      CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312      CL_MemberFunction, // An expression referring to a member function
313      CL_SubObjCPropertySetting,
314      CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315      CL_ArrayTemporary, // A temporary of array type.
316      CL_ObjCMessageRValue, // ObjC message is an rvalue
317      CL_PRValue // A prvalue for any other reason, of any other type
318    };
319    /// \brief The results of modification testing.
320    enum ModifiableType {
321      CM_Untested, // testModifiable was false.
322      CM_Modifiable,
323      CM_RValue, // Not modifiable because it's an rvalue
324      CM_Function, // Not modifiable because it's a function; C++ only
325      CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326      CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
327      CM_ConstQualified,
328      CM_ArrayType,
329      CM_IncompleteType
330    };
331
332  private:
333    friend class Expr;
334
335    unsigned short Kind;
336    unsigned short Modifiable;
337
338    explicit Classification(Kinds k, ModifiableType m)
339      : Kind(k), Modifiable(m)
340    {}
341
342  public:
343    Classification() {}
344
345    Kinds getKind() const { return static_cast<Kinds>(Kind); }
346    ModifiableType getModifiable() const {
347      assert(Modifiable != CM_Untested && "Did not test for modifiability.");
348      return static_cast<ModifiableType>(Modifiable);
349    }
350    bool isLValue() const { return Kind == CL_LValue; }
351    bool isXValue() const { return Kind == CL_XValue; }
352    bool isGLValue() const { return Kind <= CL_XValue; }
353    bool isPRValue() const { return Kind >= CL_Function; }
354    bool isRValue() const { return Kind >= CL_XValue; }
355    bool isModifiable() const { return getModifiable() == CM_Modifiable; }
356
357    /// \brief Create a simple, modifiably lvalue
358    static Classification makeSimpleLValue() {
359      return Classification(CL_LValue, CM_Modifiable);
360    }
361
362  };
363  /// \brief Classify - Classify this expression according to the C++11
364  ///        expression taxonomy.
365  ///
366  /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
367  /// old lvalue vs rvalue. This function determines the type of expression this
368  /// is. There are three expression types:
369  /// - lvalues are classical lvalues as in C++03.
370  /// - prvalues are equivalent to rvalues in C++03.
371  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
372  ///   function returning an rvalue reference.
373  /// lvalues and xvalues are collectively referred to as glvalues, while
374  /// prvalues and xvalues together form rvalues.
375  Classification Classify(ASTContext &Ctx) const {
376    return ClassifyImpl(Ctx, 0);
377  }
378
379  /// \brief ClassifyModifiable - Classify this expression according to the
380  ///        C++11 expression taxonomy, and see if it is valid on the left side
381  ///        of an assignment.
382  ///
383  /// This function extends classify in that it also tests whether the
384  /// expression is modifiable (C99 6.3.2.1p1).
385  /// \param Loc A source location that might be filled with a relevant location
386  ///            if the expression is not modifiable.
387  Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
388    return ClassifyImpl(Ctx, &Loc);
389  }
390
391  /// getValueKindForType - Given a formal return or parameter type,
392  /// give its value kind.
393  static ExprValueKind getValueKindForType(QualType T) {
394    if (const ReferenceType *RT = T->getAs<ReferenceType>())
395      return (isa<LValueReferenceType>(RT)
396                ? VK_LValue
397                : (RT->getPointeeType()->isFunctionType()
398                     ? VK_LValue : VK_XValue));
399    return VK_RValue;
400  }
401
402  /// getValueKind - The value kind that this expression produces.
403  ExprValueKind getValueKind() const {
404    return static_cast<ExprValueKind>(ExprBits.ValueKind);
405  }
406
407  /// getObjectKind - The object kind that this expression produces.
408  /// Object kinds are meaningful only for expressions that yield an
409  /// l-value or x-value.
410  ExprObjectKind getObjectKind() const {
411    return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
412  }
413
414  bool isOrdinaryOrBitFieldObject() const {
415    ExprObjectKind OK = getObjectKind();
416    return (OK == OK_Ordinary || OK == OK_BitField);
417  }
418
419  /// setValueKind - Set the value kind produced by this expression.
420  void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
421
422  /// setObjectKind - Set the object kind produced by this expression.
423  void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
424
425private:
426  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
427
428public:
429
430  /// \brief If this expression refers to a bit-field, retrieve the
431  /// declaration of that bit-field.
432  FieldDecl *getBitField();
433
434  const FieldDecl *getBitField() const {
435    return const_cast<Expr*>(this)->getBitField();
436  }
437
438  /// \brief If this expression is an l-value for an Objective C
439  /// property, find the underlying property reference expression.
440  const ObjCPropertyRefExpr *getObjCProperty() const;
441
442  /// \brief Check if this expression is the ObjC 'self' implicit parameter.
443  bool isObjCSelfExpr() const;
444
445  /// \brief Returns whether this expression refers to a vector element.
446  bool refersToVectorElement() const;
447
448  /// \brief Returns whether this expression has a placeholder type.
449  bool hasPlaceholderType() const {
450    return getType()->isPlaceholderType();
451  }
452
453  /// \brief Returns whether this expression has a specific placeholder type.
454  bool hasPlaceholderType(BuiltinType::Kind K) const {
455    assert(BuiltinType::isPlaceholderTypeKind(K));
456    if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
457      return BT->getKind() == K;
458    return false;
459  }
460
461  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
462  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
463  /// but also int expressions which are produced by things like comparisons in
464  /// C.
465  bool isKnownToHaveBooleanValue() const;
466
467  /// isIntegerConstantExpr - Return true if this expression is a valid integer
468  /// constant expression, and, if so, return its value in Result.  If not a
469  /// valid i-c-e, return false and fill in Loc (if specified) with the location
470  /// of the invalid expression.
471  ///
472  /// Note: This does not perform the implicit conversions required by C++11
473  /// [expr.const]p5.
474  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
475                             SourceLocation *Loc = 0,
476                             bool isEvaluated = true) const;
477  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const;
478
479  /// isCXX98IntegralConstantExpr - Return true if this expression is an
480  /// integral constant expression in C++98. Can only be used in C++.
481  bool isCXX98IntegralConstantExpr(ASTContext &Ctx) const;
482
483  /// isCXX11ConstantExpr - Return true if this expression is a constant
484  /// expression in C++11. Can only be used in C++.
485  ///
486  /// Note: This does not perform the implicit conversions required by C++11
487  /// [expr.const]p5.
488  bool isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result = 0,
489                           SourceLocation *Loc = 0) const;
490
491  /// isPotentialConstantExpr - Return true if this function's definition
492  /// might be usable in a constant expression in C++11, if it were marked
493  /// constexpr. Return false if the function can never produce a constant
494  /// expression, along with diagnostics describing why not.
495  static bool isPotentialConstantExpr(const FunctionDecl *FD,
496                                      SmallVectorImpl<
497                                        PartialDiagnosticAt> &Diags);
498
499  /// isConstantInitializer - Returns true if this expression can be emitted to
500  /// IR as a constant, and thus can be used as a constant initializer in C.
501  bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
502
503  /// EvalStatus is a struct with detailed info about an evaluation in progress.
504  struct EvalStatus {
505    /// HasSideEffects - Whether the evaluated expression has side effects.
506    /// For example, (f() && 0) can be folded, but it still has side effects.
507    bool HasSideEffects;
508
509    /// Diag - If this is non-null, it will be filled in with a stack of notes
510    /// indicating why evaluation failed (or why it failed to produce a constant
511    /// expression).
512    /// If the expression is unfoldable, the notes will indicate why it's not
513    /// foldable. If the expression is foldable, but not a constant expression,
514    /// the notes will describes why it isn't a constant expression. If the
515    /// expression *is* a constant expression, no notes will be produced.
516    SmallVectorImpl<PartialDiagnosticAt> *Diag;
517
518    EvalStatus() : HasSideEffects(false), Diag(0) {}
519
520    // hasSideEffects - Return true if the evaluated expression has
521    // side effects.
522    bool hasSideEffects() const {
523      return HasSideEffects;
524    }
525  };
526
527  /// EvalResult is a struct with detailed info about an evaluated expression.
528  struct EvalResult : EvalStatus {
529    /// Val - This is the value the expression can be folded to.
530    APValue Val;
531
532    // isGlobalLValue - Return true if the evaluated lvalue expression
533    // is global.
534    bool isGlobalLValue() const;
535  };
536
537  /// EvaluateAsRValue - Return true if this is a constant which we can fold to
538  /// an rvalue using any crazy technique (that has nothing to do with language
539  /// standards) that we want to, even if the expression has side-effects. If
540  /// this function returns true, it returns the folded constant in Result. If
541  /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
542  /// applied.
543  bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
544
545  /// EvaluateAsBooleanCondition - Return true if this is a constant
546  /// which we we can fold and convert to a boolean condition using
547  /// any crazy technique that we want to, even if the expression has
548  /// side-effects.
549  bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
550
551  enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects };
552
553  /// EvaluateAsInt - Return true if this is a constant which we can fold and
554  /// convert to an integer, using any crazy technique that we want to.
555  bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
556                     SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
557
558  /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
559  /// constant folded without side-effects, but discard the result.
560  bool isEvaluatable(const ASTContext &Ctx) const;
561
562  /// HasSideEffects - This routine returns true for all those expressions
563  /// which have any effect other than producing a value. Example is a function
564  /// call, volatile variable read, or throwing an exception.
565  bool HasSideEffects(const ASTContext &Ctx) const;
566
567  /// \brief Determine whether this expression involves a call to any function
568  /// that is not trivial.
569  bool hasNonTrivialCall(ASTContext &Ctx);
570
571  /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
572  /// integer. This must be called on an expression that constant folds to an
573  /// integer.
574  llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
575                          SmallVectorImpl<PartialDiagnosticAt> *Diag=0) const;
576
577  void EvaluateForOverflow(const ASTContext &Ctx,
578                           SmallVectorImpl<PartialDiagnosticAt> *Diag) const;
579
580  /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
581  /// lvalue with link time known address, with no side-effects.
582  bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
583
584  /// EvaluateAsInitializer - Evaluate an expression as if it were the
585  /// initializer of the given declaration. Returns true if the initializer
586  /// can be folded to a constant, and produces any relevant notes. In C++11,
587  /// notes will be produced if the expression is not a constant expression.
588  bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
589                             const VarDecl *VD,
590                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
591
592  /// \brief Enumeration used to describe the kind of Null pointer constant
593  /// returned from \c isNullPointerConstant().
594  enum NullPointerConstantKind {
595    /// \brief Expression is not a Null pointer constant.
596    NPCK_NotNull = 0,
597
598    /// \brief Expression is a Null pointer constant built from a zero integer
599    /// expression that is not a simple, possibly parenthesized, zero literal.
600    /// C++ Core Issue 903 will classify these expressions as "not pointers"
601    /// once it is adopted.
602    /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
603    NPCK_ZeroExpression,
604
605    /// \brief Expression is a Null pointer constant built from a literal zero.
606    NPCK_ZeroLiteral,
607
608    /// \brief Expression is a C++11 nullptr.
609    NPCK_CXX11_nullptr,
610
611    /// \brief Expression is a GNU-style __null constant.
612    NPCK_GNUNull
613  };
614
615  /// \brief Enumeration used to describe how \c isNullPointerConstant()
616  /// should cope with value-dependent expressions.
617  enum NullPointerConstantValueDependence {
618    /// \brief Specifies that the expression should never be value-dependent.
619    NPC_NeverValueDependent = 0,
620
621    /// \brief Specifies that a value-dependent expression of integral or
622    /// dependent type should be considered a null pointer constant.
623    NPC_ValueDependentIsNull,
624
625    /// \brief Specifies that a value-dependent expression should be considered
626    /// to never be a null pointer constant.
627    NPC_ValueDependentIsNotNull
628  };
629
630  /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
631  /// a Null pointer constant. The return value can further distinguish the
632  /// kind of NULL pointer constant that was detected.
633  NullPointerConstantKind isNullPointerConstant(
634      ASTContext &Ctx,
635      NullPointerConstantValueDependence NPC) const;
636
637  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
638  /// write barrier.
639  bool isOBJCGCCandidate(ASTContext &Ctx) const;
640
641  /// \brief Returns true if this expression is a bound member function.
642  bool isBoundMemberFunction(ASTContext &Ctx) const;
643
644  /// \brief Given an expression of bound-member type, find the type
645  /// of the member.  Returns null if this is an *overloaded* bound
646  /// member expression.
647  static QualType findBoundMemberType(const Expr *expr);
648
649  /// IgnoreImpCasts - Skip past any implicit casts which might
650  /// surround this expression.  Only skips ImplicitCastExprs.
651  Expr *IgnoreImpCasts() LLVM_READONLY;
652
653  /// IgnoreImplicit - Skip past any implicit AST nodes which might
654  /// surround this expression.
655  Expr *IgnoreImplicit() LLVM_READONLY {
656    return cast<Expr>(Stmt::IgnoreImplicit());
657  }
658
659  const Expr *IgnoreImplicit() const LLVM_READONLY {
660    return const_cast<Expr*>(this)->IgnoreImplicit();
661  }
662
663  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
664  ///  its subexpression.  If that subexpression is also a ParenExpr,
665  ///  then this method recursively returns its subexpression, and so forth.
666  ///  Otherwise, the method returns the current Expr.
667  Expr *IgnoreParens() LLVM_READONLY;
668
669  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
670  /// or CastExprs, returning their operand.
671  Expr *IgnoreParenCasts() LLVM_READONLY;
672
673  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip off
674  /// any ParenExpr or ImplicitCastExprs, returning their operand.
675  Expr *IgnoreParenImpCasts() LLVM_READONLY;
676
677  /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
678  /// call to a conversion operator, return the argument.
679  Expr *IgnoreConversionOperator() LLVM_READONLY;
680
681  const Expr *IgnoreConversionOperator() const LLVM_READONLY {
682    return const_cast<Expr*>(this)->IgnoreConversionOperator();
683  }
684
685  const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
686    return const_cast<Expr*>(this)->IgnoreParenImpCasts();
687  }
688
689  /// Ignore parentheses and lvalue casts.  Strip off any ParenExpr and
690  /// CastExprs that represent lvalue casts, returning their operand.
691  Expr *IgnoreParenLValueCasts() LLVM_READONLY;
692
693  const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
694    return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
695  }
696
697  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
698  /// value (including ptr->int casts of the same size).  Strip off any
699  /// ParenExpr or CastExprs, returning their operand.
700  Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
701
702  /// Ignore parentheses and derived-to-base casts.
703  Expr *ignoreParenBaseCasts() LLVM_READONLY;
704
705  const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
706    return const_cast<Expr*>(this)->ignoreParenBaseCasts();
707  }
708
709  /// \brief Determine whether this expression is a default function argument.
710  ///
711  /// Default arguments are implicitly generated in the abstract syntax tree
712  /// by semantic analysis for function calls, object constructions, etc. in
713  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
714  /// this routine also looks through any implicit casts to determine whether
715  /// the expression is a default argument.
716  bool isDefaultArgument() const;
717
718  /// \brief Determine whether the result of this expression is a
719  /// temporary object of the given class type.
720  bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
721
722  /// \brief Whether this expression is an implicit reference to 'this' in C++.
723  bool isImplicitCXXThis() const;
724
725  const Expr *IgnoreImpCasts() const LLVM_READONLY {
726    return const_cast<Expr*>(this)->IgnoreImpCasts();
727  }
728  const Expr *IgnoreParens() const LLVM_READONLY {
729    return const_cast<Expr*>(this)->IgnoreParens();
730  }
731  const Expr *IgnoreParenCasts() const LLVM_READONLY {
732    return const_cast<Expr*>(this)->IgnoreParenCasts();
733  }
734  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
735    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
736  }
737
738  static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
739
740  /// \brief For an expression of class type or pointer to class type,
741  /// return the most derived class decl the expression is known to refer to.
742  ///
743  /// If this expression is a cast, this method looks through it to find the
744  /// most derived decl that can be inferred from the expression.
745  /// This is valid because derived-to-base conversions have undefined
746  /// behavior if the object isn't dynamically of the derived type.
747  const CXXRecordDecl *getBestDynamicClassType() const;
748
749  /// Walk outwards from an expression we want to bind a reference to and
750  /// find the expression whose lifetime needs to be extended. Record
751  /// the adjustments needed along the path.
752  const Expr *
753  skipRValueSubobjectAdjustments(
754                       SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
755
756  /// Skip irrelevant expressions to find what should be materialize for
757  /// binding with a reference.
758  const Expr *
759  findMaterializedTemporary(const MaterializeTemporaryExpr *&MTE) const;
760
761  static bool classof(const Stmt *T) {
762    return T->getStmtClass() >= firstExprConstant &&
763           T->getStmtClass() <= lastExprConstant;
764  }
765};
766
767
768//===----------------------------------------------------------------------===//
769// Primary Expressions.
770//===----------------------------------------------------------------------===//
771
772/// OpaqueValueExpr - An expression referring to an opaque object of a
773/// fixed type and value class.  These don't correspond to concrete
774/// syntax; instead they're used to express operations (usually copy
775/// operations) on values whose source is generally obvious from
776/// context.
777class OpaqueValueExpr : public Expr {
778  friend class ASTStmtReader;
779  Expr *SourceExpr;
780  SourceLocation Loc;
781
782public:
783  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
784                  ExprObjectKind OK = OK_Ordinary,
785                  Expr *SourceExpr = 0)
786    : Expr(OpaqueValueExprClass, T, VK, OK,
787           T->isDependentType(),
788           T->isDependentType() ||
789           (SourceExpr && SourceExpr->isValueDependent()),
790           T->isInstantiationDependentType(),
791           false),
792      SourceExpr(SourceExpr), Loc(Loc) {
793  }
794
795  /// Given an expression which invokes a copy constructor --- i.e.  a
796  /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
797  /// find the OpaqueValueExpr that's the source of the construction.
798  static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
799
800  explicit OpaqueValueExpr(EmptyShell Empty)
801    : Expr(OpaqueValueExprClass, Empty) { }
802
803  /// \brief Retrieve the location of this expression.
804  SourceLocation getLocation() const { return Loc; }
805
806  SourceLocation getLocStart() const LLVM_READONLY {
807    return SourceExpr ? SourceExpr->getLocStart() : Loc;
808  }
809  SourceLocation getLocEnd() const LLVM_READONLY {
810    return SourceExpr ? SourceExpr->getLocEnd() : Loc;
811  }
812  SourceLocation getExprLoc() const LLVM_READONLY {
813    if (SourceExpr) return SourceExpr->getExprLoc();
814    return Loc;
815  }
816
817  child_range children() { return child_range(); }
818
819  /// The source expression of an opaque value expression is the
820  /// expression which originally generated the value.  This is
821  /// provided as a convenience for analyses that don't wish to
822  /// precisely model the execution behavior of the program.
823  ///
824  /// The source expression is typically set when building the
825  /// expression which binds the opaque value expression in the first
826  /// place.
827  Expr *getSourceExpr() const { return SourceExpr; }
828
829  static bool classof(const Stmt *T) {
830    return T->getStmtClass() == OpaqueValueExprClass;
831  }
832};
833
834/// \brief A reference to a declared variable, function, enum, etc.
835/// [C99 6.5.1p2]
836///
837/// This encodes all the information about how a declaration is referenced
838/// within an expression.
839///
840/// There are several optional constructs attached to DeclRefExprs only when
841/// they apply in order to conserve memory. These are laid out past the end of
842/// the object, and flags in the DeclRefExprBitfield track whether they exist:
843///
844///   DeclRefExprBits.HasQualifier:
845///       Specifies when this declaration reference expression has a C++
846///       nested-name-specifier.
847///   DeclRefExprBits.HasFoundDecl:
848///       Specifies when this declaration reference expression has a record of
849///       a NamedDecl (different from the referenced ValueDecl) which was found
850///       during name lookup and/or overload resolution.
851///   DeclRefExprBits.HasTemplateKWAndArgsInfo:
852///       Specifies when this declaration reference expression has an explicit
853///       C++ template keyword and/or template argument list.
854///   DeclRefExprBits.RefersToEnclosingLocal
855///       Specifies when this declaration reference expression (validly)
856///       refers to a local variable from a different function.
857class DeclRefExpr : public Expr {
858  /// \brief The declaration that we are referencing.
859  ValueDecl *D;
860
861  /// \brief The location of the declaration name itself.
862  SourceLocation Loc;
863
864  /// \brief Provides source/type location info for the declaration name
865  /// embedded in D.
866  DeclarationNameLoc DNLoc;
867
868  /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
869  NestedNameSpecifierLoc &getInternalQualifierLoc() {
870    assert(hasQualifier());
871    return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
872  }
873
874  /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
875  const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
876    return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
877  }
878
879  /// \brief Test whether there is a distinct FoundDecl attached to the end of
880  /// this DRE.
881  bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
882
883  /// \brief Helper to retrieve the optional NamedDecl through which this
884  /// reference occured.
885  NamedDecl *&getInternalFoundDecl() {
886    assert(hasFoundDecl());
887    if (hasQualifier())
888      return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
889    return *reinterpret_cast<NamedDecl **>(this + 1);
890  }
891
892  /// \brief Helper to retrieve the optional NamedDecl through which this
893  /// reference occured.
894  NamedDecl *getInternalFoundDecl() const {
895    return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
896  }
897
898  DeclRefExpr(ASTContext &Ctx,
899              NestedNameSpecifierLoc QualifierLoc,
900              SourceLocation TemplateKWLoc,
901              ValueDecl *D, bool refersToEnclosingLocal,
902              const DeclarationNameInfo &NameInfo,
903              NamedDecl *FoundD,
904              const TemplateArgumentListInfo *TemplateArgs,
905              QualType T, ExprValueKind VK);
906
907  /// \brief Construct an empty declaration reference expression.
908  explicit DeclRefExpr(EmptyShell Empty)
909    : Expr(DeclRefExprClass, Empty) { }
910
911  /// \brief Computes the type- and value-dependence flags for this
912  /// declaration reference expression.
913  void computeDependence(ASTContext &C);
914
915public:
916  DeclRefExpr(ValueDecl *D, bool refersToEnclosingLocal, QualType T,
917              ExprValueKind VK, SourceLocation L,
918              const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
919    : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
920      D(D), Loc(L), DNLoc(LocInfo) {
921    DeclRefExprBits.HasQualifier = 0;
922    DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
923    DeclRefExprBits.HasFoundDecl = 0;
924    DeclRefExprBits.HadMultipleCandidates = 0;
925    DeclRefExprBits.RefersToEnclosingLocal = refersToEnclosingLocal;
926    computeDependence(D->getASTContext());
927  }
928
929  static DeclRefExpr *Create(ASTContext &Context,
930                             NestedNameSpecifierLoc QualifierLoc,
931                             SourceLocation TemplateKWLoc,
932                             ValueDecl *D,
933                             bool isEnclosingLocal,
934                             SourceLocation NameLoc,
935                             QualType T, ExprValueKind VK,
936                             NamedDecl *FoundD = 0,
937                             const TemplateArgumentListInfo *TemplateArgs = 0);
938
939  static DeclRefExpr *Create(ASTContext &Context,
940                             NestedNameSpecifierLoc QualifierLoc,
941                             SourceLocation TemplateKWLoc,
942                             ValueDecl *D,
943                             bool isEnclosingLocal,
944                             const DeclarationNameInfo &NameInfo,
945                             QualType T, ExprValueKind VK,
946                             NamedDecl *FoundD = 0,
947                             const TemplateArgumentListInfo *TemplateArgs = 0);
948
949  /// \brief Construct an empty declaration reference expression.
950  static DeclRefExpr *CreateEmpty(ASTContext &Context,
951                                  bool HasQualifier,
952                                  bool HasFoundDecl,
953                                  bool HasTemplateKWAndArgsInfo,
954                                  unsigned NumTemplateArgs);
955
956  ValueDecl *getDecl() { return D; }
957  const ValueDecl *getDecl() const { return D; }
958  void setDecl(ValueDecl *NewD) { D = NewD; }
959
960  DeclarationNameInfo getNameInfo() const {
961    return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
962  }
963
964  SourceLocation getLocation() const { return Loc; }
965  void setLocation(SourceLocation L) { Loc = L; }
966  SourceLocation getLocStart() const LLVM_READONLY;
967  SourceLocation getLocEnd() const LLVM_READONLY;
968
969  /// \brief Determine whether this declaration reference was preceded by a
970  /// C++ nested-name-specifier, e.g., \c N::foo.
971  bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
972
973  /// \brief If the name was qualified, retrieves the nested-name-specifier
974  /// that precedes the name. Otherwise, returns NULL.
975  NestedNameSpecifier *getQualifier() const {
976    if (!hasQualifier())
977      return 0;
978
979    return getInternalQualifierLoc().getNestedNameSpecifier();
980  }
981
982  /// \brief If the name was qualified, retrieves the nested-name-specifier
983  /// that precedes the name, with source-location information.
984  NestedNameSpecifierLoc getQualifierLoc() const {
985    if (!hasQualifier())
986      return NestedNameSpecifierLoc();
987
988    return getInternalQualifierLoc();
989  }
990
991  /// \brief Get the NamedDecl through which this reference occured.
992  ///
993  /// This Decl may be different from the ValueDecl actually referred to in the
994  /// presence of using declarations, etc. It always returns non-NULL, and may
995  /// simple return the ValueDecl when appropriate.
996  NamedDecl *getFoundDecl() {
997    return hasFoundDecl() ? getInternalFoundDecl() : D;
998  }
999
1000  /// \brief Get the NamedDecl through which this reference occurred.
1001  /// See non-const variant.
1002  const NamedDecl *getFoundDecl() const {
1003    return hasFoundDecl() ? getInternalFoundDecl() : D;
1004  }
1005
1006  bool hasTemplateKWAndArgsInfo() const {
1007    return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1008  }
1009
1010  /// \brief Return the optional template keyword and arguments info.
1011  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
1012    if (!hasTemplateKWAndArgsInfo())
1013      return 0;
1014
1015    if (hasFoundDecl())
1016      return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1017        &getInternalFoundDecl() + 1);
1018
1019    if (hasQualifier())
1020      return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1021        &getInternalQualifierLoc() + 1);
1022
1023    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
1024  }
1025
1026  /// \brief Return the optional template keyword and arguments info.
1027  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
1028    return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo();
1029  }
1030
1031  /// \brief Retrieve the location of the template keyword preceding
1032  /// this name, if any.
1033  SourceLocation getTemplateKeywordLoc() const {
1034    if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1035    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
1036  }
1037
1038  /// \brief Retrieve the location of the left angle bracket starting the
1039  /// explicit template argument list following the name, if any.
1040  SourceLocation getLAngleLoc() const {
1041    if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1042    return getTemplateKWAndArgsInfo()->LAngleLoc;
1043  }
1044
1045  /// \brief Retrieve the location of the right angle bracket ending the
1046  /// explicit template argument list following the name, if any.
1047  SourceLocation getRAngleLoc() const {
1048    if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1049    return getTemplateKWAndArgsInfo()->RAngleLoc;
1050  }
1051
1052  /// \brief Determines whether the name in this declaration reference
1053  /// was preceded by the template keyword.
1054  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1055
1056  /// \brief Determines whether this declaration reference was followed by an
1057  /// explicit template argument list.
1058  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1059
1060  /// \brief Retrieve the explicit template argument list that followed the
1061  /// member template name.
1062  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
1063    assert(hasExplicitTemplateArgs());
1064    return *getTemplateKWAndArgsInfo();
1065  }
1066
1067  /// \brief Retrieve the explicit template argument list that followed the
1068  /// member template name.
1069  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
1070    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
1071  }
1072
1073  /// \brief Retrieves the optional explicit template arguments.
1074  /// This points to the same data as getExplicitTemplateArgs(), but
1075  /// returns null if there are no explicit template arguments.
1076  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
1077    if (!hasExplicitTemplateArgs()) return 0;
1078    return &getExplicitTemplateArgs();
1079  }
1080
1081  /// \brief Copies the template arguments (if present) into the given
1082  /// structure.
1083  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1084    if (hasExplicitTemplateArgs())
1085      getExplicitTemplateArgs().copyInto(List);
1086  }
1087
1088  /// \brief Retrieve the template arguments provided as part of this
1089  /// template-id.
1090  const TemplateArgumentLoc *getTemplateArgs() const {
1091    if (!hasExplicitTemplateArgs())
1092      return 0;
1093
1094    return getExplicitTemplateArgs().getTemplateArgs();
1095  }
1096
1097  /// \brief Retrieve the number of template arguments provided as part of this
1098  /// template-id.
1099  unsigned getNumTemplateArgs() const {
1100    if (!hasExplicitTemplateArgs())
1101      return 0;
1102
1103    return getExplicitTemplateArgs().NumTemplateArgs;
1104  }
1105
1106  /// \brief Returns true if this expression refers to a function that
1107  /// was resolved from an overloaded set having size greater than 1.
1108  bool hadMultipleCandidates() const {
1109    return DeclRefExprBits.HadMultipleCandidates;
1110  }
1111  /// \brief Sets the flag telling whether this expression refers to
1112  /// a function that was resolved from an overloaded set having size
1113  /// greater than 1.
1114  void setHadMultipleCandidates(bool V = true) {
1115    DeclRefExprBits.HadMultipleCandidates = V;
1116  }
1117
1118  /// Does this DeclRefExpr refer to a local declaration from an
1119  /// enclosing function scope?
1120  bool refersToEnclosingLocal() const {
1121    return DeclRefExprBits.RefersToEnclosingLocal;
1122  }
1123
1124  static bool classof(const Stmt *T) {
1125    return T->getStmtClass() == DeclRefExprClass;
1126  }
1127
1128  // Iterators
1129  child_range children() { return child_range(); }
1130
1131  friend class ASTStmtReader;
1132  friend class ASTStmtWriter;
1133};
1134
1135/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
1136class PredefinedExpr : public Expr {
1137public:
1138  enum IdentType {
1139    Func,
1140    Function,
1141    LFunction,  // Same as Function, but as wide string.
1142    PrettyFunction,
1143    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
1144    /// 'virtual' keyword is omitted for virtual member functions.
1145    PrettyFunctionNoVirtual
1146  };
1147
1148private:
1149  SourceLocation Loc;
1150  IdentType Type;
1151public:
1152  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
1153    : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
1154           type->isDependentType(), type->isDependentType(),
1155           type->isInstantiationDependentType(),
1156           /*ContainsUnexpandedParameterPack=*/false),
1157      Loc(l), Type(IT) {}
1158
1159  /// \brief Construct an empty predefined expression.
1160  explicit PredefinedExpr(EmptyShell Empty)
1161    : Expr(PredefinedExprClass, Empty) { }
1162
1163  IdentType getIdentType() const { return Type; }
1164  void setIdentType(IdentType IT) { Type = IT; }
1165
1166  SourceLocation getLocation() const { return Loc; }
1167  void setLocation(SourceLocation L) { Loc = L; }
1168
1169  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1170
1171  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1172  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1173
1174  static bool classof(const Stmt *T) {
1175    return T->getStmtClass() == PredefinedExprClass;
1176  }
1177
1178  // Iterators
1179  child_range children() { return child_range(); }
1180};
1181
1182/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1183/// leaking memory.
1184///
1185/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1186/// to represent these numbers.  Unfortunately, when we use a BumpPtrAllocator
1187/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1188/// the APFloat/APInt values will never get freed. APNumericStorage uses
1189/// ASTContext's allocator for memory allocation.
1190class APNumericStorage {
1191  union {
1192    uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
1193    uint64_t *pVal;  ///< Used to store the >64 bits integer value.
1194  };
1195  unsigned BitWidth;
1196
1197  bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1198
1199  APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1200  void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1201
1202protected:
1203  APNumericStorage() : VAL(0), BitWidth(0) { }
1204
1205  llvm::APInt getIntValue() const {
1206    unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1207    if (NumWords > 1)
1208      return llvm::APInt(BitWidth, NumWords, pVal);
1209    else
1210      return llvm::APInt(BitWidth, VAL);
1211  }
1212  void setIntValue(ASTContext &C, const llvm::APInt &Val);
1213};
1214
1215class APIntStorage : private APNumericStorage {
1216public:
1217  llvm::APInt getValue() const { return getIntValue(); }
1218  void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); }
1219};
1220
1221class APFloatStorage : private APNumericStorage {
1222public:
1223  llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1224    return llvm::APFloat(Semantics, getIntValue());
1225  }
1226  void setValue(ASTContext &C, const llvm::APFloat &Val) {
1227    setIntValue(C, Val.bitcastToAPInt());
1228  }
1229};
1230
1231class IntegerLiteral : public Expr, public APIntStorage {
1232  SourceLocation Loc;
1233
1234  /// \brief Construct an empty integer literal.
1235  explicit IntegerLiteral(EmptyShell Empty)
1236    : Expr(IntegerLiteralClass, Empty) { }
1237
1238public:
1239  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1240  // or UnsignedLongLongTy
1241  IntegerLiteral(ASTContext &C, const llvm::APInt &V, QualType type,
1242                 SourceLocation l);
1243
1244  /// \brief Returns a new integer literal with value 'V' and type 'type'.
1245  /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1246  /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1247  /// \param V - the value that the returned integer literal contains.
1248  static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V,
1249                                QualType type, SourceLocation l);
1250  /// \brief Returns a new empty integer literal.
1251  static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty);
1252
1253  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1254  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1255
1256  /// \brief Retrieve the location of the literal.
1257  SourceLocation getLocation() const { return Loc; }
1258
1259  void setLocation(SourceLocation Location) { Loc = Location; }
1260
1261  static bool classof(const Stmt *T) {
1262    return T->getStmtClass() == IntegerLiteralClass;
1263  }
1264
1265  // Iterators
1266  child_range children() { return child_range(); }
1267};
1268
1269class CharacterLiteral : public Expr {
1270public:
1271  enum CharacterKind {
1272    Ascii,
1273    Wide,
1274    UTF16,
1275    UTF32
1276  };
1277
1278private:
1279  unsigned Value;
1280  SourceLocation Loc;
1281public:
1282  // type should be IntTy
1283  CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1284                   SourceLocation l)
1285    : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1286           false, false),
1287      Value(value), Loc(l) {
1288    CharacterLiteralBits.Kind = kind;
1289  }
1290
1291  /// \brief Construct an empty character literal.
1292  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1293
1294  SourceLocation getLocation() const { return Loc; }
1295  CharacterKind getKind() const {
1296    return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1297  }
1298
1299  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1300  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1301
1302  unsigned getValue() const { return Value; }
1303
1304  void setLocation(SourceLocation Location) { Loc = Location; }
1305  void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1306  void setValue(unsigned Val) { Value = Val; }
1307
1308  static bool classof(const Stmt *T) {
1309    return T->getStmtClass() == CharacterLiteralClass;
1310  }
1311
1312  // Iterators
1313  child_range children() { return child_range(); }
1314};
1315
1316class FloatingLiteral : public Expr, private APFloatStorage {
1317  SourceLocation Loc;
1318
1319  FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact,
1320                  QualType Type, SourceLocation L);
1321
1322  /// \brief Construct an empty floating-point literal.
1323  explicit FloatingLiteral(ASTContext &C, EmptyShell Empty);
1324
1325public:
1326  static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V,
1327                                 bool isexact, QualType Type, SourceLocation L);
1328  static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty);
1329
1330  llvm::APFloat getValue() const {
1331    return APFloatStorage::getValue(getSemantics());
1332  }
1333  void setValue(ASTContext &C, const llvm::APFloat &Val) {
1334    assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1335    APFloatStorage::setValue(C, Val);
1336  }
1337
1338  /// Get a raw enumeration value representing the floating-point semantics of
1339  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1340  APFloatSemantics getRawSemantics() const {
1341    return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1342  }
1343
1344  /// Set the raw enumeration value representing the floating-point semantics of
1345  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1346  void setRawSemantics(APFloatSemantics Sem) {
1347    FloatingLiteralBits.Semantics = Sem;
1348  }
1349
1350  /// Return the APFloat semantics this literal uses.
1351  const llvm::fltSemantics &getSemantics() const;
1352
1353  /// Set the APFloat semantics this literal uses.
1354  void setSemantics(const llvm::fltSemantics &Sem);
1355
1356  bool isExact() const { return FloatingLiteralBits.IsExact; }
1357  void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1358
1359  /// getValueAsApproximateDouble - This returns the value as an inaccurate
1360  /// double.  Note that this may cause loss of precision, but is useful for
1361  /// debugging dumps, etc.
1362  double getValueAsApproximateDouble() const;
1363
1364  SourceLocation getLocation() const { return Loc; }
1365  void setLocation(SourceLocation L) { Loc = L; }
1366
1367  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1368  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1369
1370  static bool classof(const Stmt *T) {
1371    return T->getStmtClass() == FloatingLiteralClass;
1372  }
1373
1374  // Iterators
1375  child_range children() { return child_range(); }
1376};
1377
1378/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1379/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
1380/// IntegerLiteral classes.  Instances of this class always have a Complex type
1381/// whose element type matches the subexpression.
1382///
1383class ImaginaryLiteral : public Expr {
1384  Stmt *Val;
1385public:
1386  ImaginaryLiteral(Expr *val, QualType Ty)
1387    : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1388           false, false),
1389      Val(val) {}
1390
1391  /// \brief Build an empty imaginary literal.
1392  explicit ImaginaryLiteral(EmptyShell Empty)
1393    : Expr(ImaginaryLiteralClass, Empty) { }
1394
1395  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1396  Expr *getSubExpr() { return cast<Expr>(Val); }
1397  void setSubExpr(Expr *E) { Val = E; }
1398
1399  SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1400  SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1401
1402  static bool classof(const Stmt *T) {
1403    return T->getStmtClass() == ImaginaryLiteralClass;
1404  }
1405
1406  // Iterators
1407  child_range children() { return child_range(&Val, &Val+1); }
1408};
1409
1410/// StringLiteral - This represents a string literal expression, e.g. "foo"
1411/// or L"bar" (wide strings).  The actual string is returned by getStrData()
1412/// is NOT null-terminated, and the length of the string is determined by
1413/// calling getByteLength().  The C type for a string is always a
1414/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
1415/// not.
1416///
1417/// Note that strings in C can be formed by concatenation of multiple string
1418/// literal pptokens in translation phase #6.  This keeps track of the locations
1419/// of each of these pieces.
1420///
1421/// Strings in C can also be truncated and extended by assigning into arrays,
1422/// e.g. with constructs like:
1423///   char X[2] = "foobar";
1424/// In this case, getByteLength() will return 6, but the string literal will
1425/// have type "char[2]".
1426class StringLiteral : public Expr {
1427public:
1428  enum StringKind {
1429    Ascii,
1430    Wide,
1431    UTF8,
1432    UTF16,
1433    UTF32
1434  };
1435
1436private:
1437  friend class ASTStmtReader;
1438
1439  union {
1440    const char *asChar;
1441    const uint16_t *asUInt16;
1442    const uint32_t *asUInt32;
1443  } StrData;
1444  unsigned Length;
1445  unsigned CharByteWidth : 4;
1446  unsigned Kind : 3;
1447  unsigned IsPascal : 1;
1448  unsigned NumConcatenated;
1449  SourceLocation TokLocs[1];
1450
1451  StringLiteral(QualType Ty) :
1452    Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1453         false) {}
1454
1455  static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1456
1457public:
1458  /// This is the "fully general" constructor that allows representation of
1459  /// strings formed from multiple concatenated tokens.
1460  static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1461                               bool Pascal, QualType Ty,
1462                               const SourceLocation *Loc, unsigned NumStrs);
1463
1464  /// Simple constructor for string literals made from one token.
1465  static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1466                               bool Pascal, QualType Ty,
1467                               SourceLocation Loc) {
1468    return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1469  }
1470
1471  /// \brief Construct an empty string literal.
1472  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1473
1474  StringRef getString() const {
1475    assert(CharByteWidth==1
1476           && "This function is used in places that assume strings use char");
1477    return StringRef(StrData.asChar, getByteLength());
1478  }
1479
1480  /// Allow access to clients that need the byte representation, such as
1481  /// ASTWriterStmt::VisitStringLiteral().
1482  StringRef getBytes() const {
1483    // FIXME: StringRef may not be the right type to use as a result for this.
1484    if (CharByteWidth == 1)
1485      return StringRef(StrData.asChar, getByteLength());
1486    if (CharByteWidth == 4)
1487      return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1488                       getByteLength());
1489    assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1490    return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1491                     getByteLength());
1492  }
1493
1494  void outputString(raw_ostream &OS) const;
1495
1496  uint32_t getCodeUnit(size_t i) const {
1497    assert(i < Length && "out of bounds access");
1498    if (CharByteWidth == 1)
1499      return static_cast<unsigned char>(StrData.asChar[i]);
1500    if (CharByteWidth == 4)
1501      return StrData.asUInt32[i];
1502    assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1503    return StrData.asUInt16[i];
1504  }
1505
1506  unsigned getByteLength() const { return CharByteWidth*Length; }
1507  unsigned getLength() const { return Length; }
1508  unsigned getCharByteWidth() const { return CharByteWidth; }
1509
1510  /// \brief Sets the string data to the given string data.
1511  void setString(ASTContext &C, StringRef Str,
1512                 StringKind Kind, bool IsPascal);
1513
1514  StringKind getKind() const { return static_cast<StringKind>(Kind); }
1515
1516
1517  bool isAscii() const { return Kind == Ascii; }
1518  bool isWide() const { return Kind == Wide; }
1519  bool isUTF8() const { return Kind == UTF8; }
1520  bool isUTF16() const { return Kind == UTF16; }
1521  bool isUTF32() const { return Kind == UTF32; }
1522  bool isPascal() const { return IsPascal; }
1523
1524  bool containsNonAsciiOrNull() const {
1525    StringRef Str = getString();
1526    for (unsigned i = 0, e = Str.size(); i != e; ++i)
1527      if (!isASCII(Str[i]) || !Str[i])
1528        return true;
1529    return false;
1530  }
1531
1532  /// getNumConcatenated - Get the number of string literal tokens that were
1533  /// concatenated in translation phase #6 to form this string literal.
1534  unsigned getNumConcatenated() const { return NumConcatenated; }
1535
1536  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1537    assert(TokNum < NumConcatenated && "Invalid tok number");
1538    return TokLocs[TokNum];
1539  }
1540  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1541    assert(TokNum < NumConcatenated && "Invalid tok number");
1542    TokLocs[TokNum] = L;
1543  }
1544
1545  /// getLocationOfByte - Return a source location that points to the specified
1546  /// byte of this string literal.
1547  ///
1548  /// Strings are amazingly complex.  They can be formed from multiple tokens
1549  /// and can have escape sequences in them in addition to the usual trigraph
1550  /// and escaped newline business.  This routine handles this complexity.
1551  ///
1552  SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1553                                   const LangOptions &Features,
1554                                   const TargetInfo &Target) const;
1555
1556  typedef const SourceLocation *tokloc_iterator;
1557  tokloc_iterator tokloc_begin() const { return TokLocs; }
1558  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1559
1560  SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1561  SourceLocation getLocEnd() const LLVM_READONLY {
1562    return TokLocs[NumConcatenated - 1];
1563  }
1564
1565  static bool classof(const Stmt *T) {
1566    return T->getStmtClass() == StringLiteralClass;
1567  }
1568
1569  // Iterators
1570  child_range children() { return child_range(); }
1571};
1572
1573/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
1574/// AST node is only formed if full location information is requested.
1575class ParenExpr : public Expr {
1576  SourceLocation L, R;
1577  Stmt *Val;
1578public:
1579  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1580    : Expr(ParenExprClass, val->getType(),
1581           val->getValueKind(), val->getObjectKind(),
1582           val->isTypeDependent(), val->isValueDependent(),
1583           val->isInstantiationDependent(),
1584           val->containsUnexpandedParameterPack()),
1585      L(l), R(r), Val(val) {}
1586
1587  /// \brief Construct an empty parenthesized expression.
1588  explicit ParenExpr(EmptyShell Empty)
1589    : Expr(ParenExprClass, Empty) { }
1590
1591  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1592  Expr *getSubExpr() { return cast<Expr>(Val); }
1593  void setSubExpr(Expr *E) { Val = E; }
1594
1595  SourceLocation getLocStart() const LLVM_READONLY { return L; }
1596  SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1597
1598  /// \brief Get the location of the left parentheses '('.
1599  SourceLocation getLParen() const { return L; }
1600  void setLParen(SourceLocation Loc) { L = Loc; }
1601
1602  /// \brief Get the location of the right parentheses ')'.
1603  SourceLocation getRParen() const { return R; }
1604  void setRParen(SourceLocation Loc) { R = Loc; }
1605
1606  static bool classof(const Stmt *T) {
1607    return T->getStmtClass() == ParenExprClass;
1608  }
1609
1610  // Iterators
1611  child_range children() { return child_range(&Val, &Val+1); }
1612};
1613
1614
1615/// UnaryOperator - This represents the unary-expression's (except sizeof and
1616/// alignof), the postinc/postdec operators from postfix-expression, and various
1617/// extensions.
1618///
1619/// Notes on various nodes:
1620///
1621/// Real/Imag - These return the real/imag part of a complex operand.  If
1622///   applied to a non-complex value, the former returns its operand and the
1623///   later returns zero in the type of the operand.
1624///
1625class UnaryOperator : public Expr {
1626public:
1627  typedef UnaryOperatorKind Opcode;
1628
1629private:
1630  unsigned Opc : 5;
1631  SourceLocation Loc;
1632  Stmt *Val;
1633public:
1634
1635  UnaryOperator(Expr *input, Opcode opc, QualType type,
1636                ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1637    : Expr(UnaryOperatorClass, type, VK, OK,
1638           input->isTypeDependent() || type->isDependentType(),
1639           input->isValueDependent(),
1640           (input->isInstantiationDependent() ||
1641            type->isInstantiationDependentType()),
1642           input->containsUnexpandedParameterPack()),
1643      Opc(opc), Loc(l), Val(input) {}
1644
1645  /// \brief Build an empty unary operator.
1646  explicit UnaryOperator(EmptyShell Empty)
1647    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1648
1649  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1650  void setOpcode(Opcode O) { Opc = O; }
1651
1652  Expr *getSubExpr() const { return cast<Expr>(Val); }
1653  void setSubExpr(Expr *E) { Val = E; }
1654
1655  /// getOperatorLoc - Return the location of the operator.
1656  SourceLocation getOperatorLoc() const { return Loc; }
1657  void setOperatorLoc(SourceLocation L) { Loc = L; }
1658
1659  /// isPostfix - Return true if this is a postfix operation, like x++.
1660  static bool isPostfix(Opcode Op) {
1661    return Op == UO_PostInc || Op == UO_PostDec;
1662  }
1663
1664  /// isPrefix - Return true if this is a prefix operation, like --x.
1665  static bool isPrefix(Opcode Op) {
1666    return Op == UO_PreInc || Op == UO_PreDec;
1667  }
1668
1669  bool isPrefix() const { return isPrefix(getOpcode()); }
1670  bool isPostfix() const { return isPostfix(getOpcode()); }
1671
1672  static bool isIncrementOp(Opcode Op) {
1673    return Op == UO_PreInc || Op == UO_PostInc;
1674  }
1675  bool isIncrementOp() const {
1676    return isIncrementOp(getOpcode());
1677  }
1678
1679  static bool isDecrementOp(Opcode Op) {
1680    return Op == UO_PreDec || Op == UO_PostDec;
1681  }
1682  bool isDecrementOp() const {
1683    return isDecrementOp(getOpcode());
1684  }
1685
1686  static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1687  bool isIncrementDecrementOp() const {
1688    return isIncrementDecrementOp(getOpcode());
1689  }
1690
1691  static bool isArithmeticOp(Opcode Op) {
1692    return Op >= UO_Plus && Op <= UO_LNot;
1693  }
1694  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1695
1696  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1697  /// corresponds to, e.g. "sizeof" or "[pre]++"
1698  static StringRef getOpcodeStr(Opcode Op);
1699
1700  /// \brief Retrieve the unary opcode that corresponds to the given
1701  /// overloaded operator.
1702  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1703
1704  /// \brief Retrieve the overloaded operator kind that corresponds to
1705  /// the given unary opcode.
1706  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1707
1708  SourceLocation getLocStart() const LLVM_READONLY {
1709    return isPostfix() ? Val->getLocStart() : Loc;
1710  }
1711  SourceLocation getLocEnd() const LLVM_READONLY {
1712    return isPostfix() ? Loc : Val->getLocEnd();
1713  }
1714  SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1715
1716  static bool classof(const Stmt *T) {
1717    return T->getStmtClass() == UnaryOperatorClass;
1718  }
1719
1720  // Iterators
1721  child_range children() { return child_range(&Val, &Val+1); }
1722};
1723
1724/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1725/// offsetof(record-type, member-designator). For example, given:
1726/// @code
1727/// struct S {
1728///   float f;
1729///   double d;
1730/// };
1731/// struct T {
1732///   int i;
1733///   struct S s[10];
1734/// };
1735/// @endcode
1736/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1737
1738class OffsetOfExpr : public Expr {
1739public:
1740  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1741  class OffsetOfNode {
1742  public:
1743    /// \brief The kind of offsetof node we have.
1744    enum Kind {
1745      /// \brief An index into an array.
1746      Array = 0x00,
1747      /// \brief A field.
1748      Field = 0x01,
1749      /// \brief A field in a dependent type, known only by its name.
1750      Identifier = 0x02,
1751      /// \brief An implicit indirection through a C++ base class, when the
1752      /// field found is in a base class.
1753      Base = 0x03
1754    };
1755
1756  private:
1757    enum { MaskBits = 2, Mask = 0x03 };
1758
1759    /// \brief The source range that covers this part of the designator.
1760    SourceRange Range;
1761
1762    /// \brief The data describing the designator, which comes in three
1763    /// different forms, depending on the lower two bits.
1764    ///   - An unsigned index into the array of Expr*'s stored after this node
1765    ///     in memory, for [constant-expression] designators.
1766    ///   - A FieldDecl*, for references to a known field.
1767    ///   - An IdentifierInfo*, for references to a field with a given name
1768    ///     when the class type is dependent.
1769    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1770    ///     base class.
1771    uintptr_t Data;
1772
1773  public:
1774    /// \brief Create an offsetof node that refers to an array element.
1775    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1776                 SourceLocation RBracketLoc)
1777      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1778
1779    /// \brief Create an offsetof node that refers to a field.
1780    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1781                 SourceLocation NameLoc)
1782      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1783        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1784
1785    /// \brief Create an offsetof node that refers to an identifier.
1786    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1787                 SourceLocation NameLoc)
1788      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1789        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1790
1791    /// \brief Create an offsetof node that refers into a C++ base class.
1792    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1793      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1794
1795    /// \brief Determine what kind of offsetof node this is.
1796    Kind getKind() const {
1797      return static_cast<Kind>(Data & Mask);
1798    }
1799
1800    /// \brief For an array element node, returns the index into the array
1801    /// of expressions.
1802    unsigned getArrayExprIndex() const {
1803      assert(getKind() == Array);
1804      return Data >> 2;
1805    }
1806
1807    /// \brief For a field offsetof node, returns the field.
1808    FieldDecl *getField() const {
1809      assert(getKind() == Field);
1810      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1811    }
1812
1813    /// \brief For a field or identifier offsetof node, returns the name of
1814    /// the field.
1815    IdentifierInfo *getFieldName() const;
1816
1817    /// \brief For a base class node, returns the base specifier.
1818    CXXBaseSpecifier *getBase() const {
1819      assert(getKind() == Base);
1820      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1821    }
1822
1823    /// \brief Retrieve the source range that covers this offsetof node.
1824    ///
1825    /// For an array element node, the source range contains the locations of
1826    /// the square brackets. For a field or identifier node, the source range
1827    /// contains the location of the period (if there is one) and the
1828    /// identifier.
1829    SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1830    SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1831    SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1832  };
1833
1834private:
1835
1836  SourceLocation OperatorLoc, RParenLoc;
1837  // Base type;
1838  TypeSourceInfo *TSInfo;
1839  // Number of sub-components (i.e. instances of OffsetOfNode).
1840  unsigned NumComps;
1841  // Number of sub-expressions (i.e. array subscript expressions).
1842  unsigned NumExprs;
1843
1844  OffsetOfExpr(ASTContext &C, QualType type,
1845               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1846               ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1847               SourceLocation RParenLoc);
1848
1849  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1850    : Expr(OffsetOfExprClass, EmptyShell()),
1851      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1852
1853public:
1854
1855  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1856                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1857                              ArrayRef<OffsetOfNode> comps,
1858                              ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1859
1860  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1861                                   unsigned NumComps, unsigned NumExprs);
1862
1863  /// getOperatorLoc - Return the location of the operator.
1864  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1865  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1866
1867  /// \brief Return the location of the right parentheses.
1868  SourceLocation getRParenLoc() const { return RParenLoc; }
1869  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1870
1871  TypeSourceInfo *getTypeSourceInfo() const {
1872    return TSInfo;
1873  }
1874  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1875    TSInfo = tsi;
1876  }
1877
1878  const OffsetOfNode &getComponent(unsigned Idx) const {
1879    assert(Idx < NumComps && "Subscript out of range");
1880    return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1881  }
1882
1883  void setComponent(unsigned Idx, OffsetOfNode ON) {
1884    assert(Idx < NumComps && "Subscript out of range");
1885    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1886  }
1887
1888  unsigned getNumComponents() const {
1889    return NumComps;
1890  }
1891
1892  Expr* getIndexExpr(unsigned Idx) {
1893    assert(Idx < NumExprs && "Subscript out of range");
1894    return reinterpret_cast<Expr **>(
1895                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1896  }
1897  const Expr *getIndexExpr(unsigned Idx) const {
1898    return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1899  }
1900
1901  void setIndexExpr(unsigned Idx, Expr* E) {
1902    assert(Idx < NumComps && "Subscript out of range");
1903    reinterpret_cast<Expr **>(
1904                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1905  }
1906
1907  unsigned getNumExpressions() const {
1908    return NumExprs;
1909  }
1910
1911  SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1912  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1913
1914  static bool classof(const Stmt *T) {
1915    return T->getStmtClass() == OffsetOfExprClass;
1916  }
1917
1918  // Iterators
1919  child_range children() {
1920    Stmt **begin =
1921      reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1922                               + NumComps);
1923    return child_range(begin, begin + NumExprs);
1924  }
1925};
1926
1927/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1928/// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
1929/// vec_step (OpenCL 1.1 6.11.12).
1930class UnaryExprOrTypeTraitExpr : public Expr {
1931  union {
1932    TypeSourceInfo *Ty;
1933    Stmt *Ex;
1934  } Argument;
1935  SourceLocation OpLoc, RParenLoc;
1936
1937public:
1938  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1939                           QualType resultType, SourceLocation op,
1940                           SourceLocation rp) :
1941      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1942           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1943           // Value-dependent if the argument is type-dependent.
1944           TInfo->getType()->isDependentType(),
1945           TInfo->getType()->isInstantiationDependentType(),
1946           TInfo->getType()->containsUnexpandedParameterPack()),
1947      OpLoc(op), RParenLoc(rp) {
1948    UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1949    UnaryExprOrTypeTraitExprBits.IsType = true;
1950    Argument.Ty = TInfo;
1951  }
1952
1953  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1954                           QualType resultType, SourceLocation op,
1955                           SourceLocation rp) :
1956      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1957           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1958           // Value-dependent if the argument is type-dependent.
1959           E->isTypeDependent(),
1960           E->isInstantiationDependent(),
1961           E->containsUnexpandedParameterPack()),
1962      OpLoc(op), RParenLoc(rp) {
1963    UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1964    UnaryExprOrTypeTraitExprBits.IsType = false;
1965    Argument.Ex = E;
1966  }
1967
1968  /// \brief Construct an empty sizeof/alignof expression.
1969  explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1970    : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1971
1972  UnaryExprOrTypeTrait getKind() const {
1973    return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
1974  }
1975  void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
1976
1977  bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
1978  QualType getArgumentType() const {
1979    return getArgumentTypeInfo()->getType();
1980  }
1981  TypeSourceInfo *getArgumentTypeInfo() const {
1982    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1983    return Argument.Ty;
1984  }
1985  Expr *getArgumentExpr() {
1986    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1987    return static_cast<Expr*>(Argument.Ex);
1988  }
1989  const Expr *getArgumentExpr() const {
1990    return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
1991  }
1992
1993  void setArgument(Expr *E) {
1994    Argument.Ex = E;
1995    UnaryExprOrTypeTraitExprBits.IsType = false;
1996  }
1997  void setArgument(TypeSourceInfo *TInfo) {
1998    Argument.Ty = TInfo;
1999    UnaryExprOrTypeTraitExprBits.IsType = true;
2000  }
2001
2002  /// Gets the argument type, or the type of the argument expression, whichever
2003  /// is appropriate.
2004  QualType getTypeOfArgument() const {
2005    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2006  }
2007
2008  SourceLocation getOperatorLoc() const { return OpLoc; }
2009  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2010
2011  SourceLocation getRParenLoc() const { return RParenLoc; }
2012  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2013
2014  SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2015  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2016
2017  static bool classof(const Stmt *T) {
2018    return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2019  }
2020
2021  // Iterators
2022  child_range children();
2023};
2024
2025//===----------------------------------------------------------------------===//
2026// Postfix Operators.
2027//===----------------------------------------------------------------------===//
2028
2029/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2030class ArraySubscriptExpr : public Expr {
2031  enum { LHS, RHS, END_EXPR=2 };
2032  Stmt* SubExprs[END_EXPR];
2033  SourceLocation RBracketLoc;
2034public:
2035  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2036                     ExprValueKind VK, ExprObjectKind OK,
2037                     SourceLocation rbracketloc)
2038  : Expr(ArraySubscriptExprClass, t, VK, OK,
2039         lhs->isTypeDependent() || rhs->isTypeDependent(),
2040         lhs->isValueDependent() || rhs->isValueDependent(),
2041         (lhs->isInstantiationDependent() ||
2042          rhs->isInstantiationDependent()),
2043         (lhs->containsUnexpandedParameterPack() ||
2044          rhs->containsUnexpandedParameterPack())),
2045    RBracketLoc(rbracketloc) {
2046    SubExprs[LHS] = lhs;
2047    SubExprs[RHS] = rhs;
2048  }
2049
2050  /// \brief Create an empty array subscript expression.
2051  explicit ArraySubscriptExpr(EmptyShell Shell)
2052    : Expr(ArraySubscriptExprClass, Shell) { }
2053
2054  /// An array access can be written A[4] or 4[A] (both are equivalent).
2055  /// - getBase() and getIdx() always present the normalized view: A[4].
2056  ///    In this case getBase() returns "A" and getIdx() returns "4".
2057  /// - getLHS() and getRHS() present the syntactic view. e.g. for
2058  ///    4[A] getLHS() returns "4".
2059  /// Note: Because vector element access is also written A[4] we must
2060  /// predicate the format conversion in getBase and getIdx only on the
2061  /// the type of the RHS, as it is possible for the LHS to be a vector of
2062  /// integer type
2063  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2064  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2065  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2066
2067  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2068  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2069  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2070
2071  Expr *getBase() {
2072    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2073  }
2074
2075  const Expr *getBase() const {
2076    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2077  }
2078
2079  Expr *getIdx() {
2080    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2081  }
2082
2083  const Expr *getIdx() const {
2084    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2085  }
2086
2087  SourceLocation getLocStart() const LLVM_READONLY {
2088    return getLHS()->getLocStart();
2089  }
2090  SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2091
2092  SourceLocation getRBracketLoc() const { return RBracketLoc; }
2093  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2094
2095  SourceLocation getExprLoc() const LLVM_READONLY {
2096    return getBase()->getExprLoc();
2097  }
2098
2099  static bool classof(const Stmt *T) {
2100    return T->getStmtClass() == ArraySubscriptExprClass;
2101  }
2102
2103  // Iterators
2104  child_range children() {
2105    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2106  }
2107};
2108
2109
2110/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2111/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2112/// while its subclasses may represent alternative syntax that (semantically)
2113/// results in a function call. For example, CXXOperatorCallExpr is
2114/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2115/// "str1 + str2" to resolve to a function call.
2116class CallExpr : public Expr {
2117  enum { FN=0, PREARGS_START=1 };
2118  Stmt **SubExprs;
2119  unsigned NumArgs;
2120  SourceLocation RParenLoc;
2121
2122protected:
2123  // These versions of the constructor are for derived classes.
2124  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2125           ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2126           SourceLocation rparenloc);
2127  CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty);
2128
2129  Stmt *getPreArg(unsigned i) {
2130    assert(i < getNumPreArgs() && "Prearg access out of range!");
2131    return SubExprs[PREARGS_START+i];
2132  }
2133  const Stmt *getPreArg(unsigned i) const {
2134    assert(i < getNumPreArgs() && "Prearg access out of range!");
2135    return SubExprs[PREARGS_START+i];
2136  }
2137  void setPreArg(unsigned i, Stmt *PreArg) {
2138    assert(i < getNumPreArgs() && "Prearg access out of range!");
2139    SubExprs[PREARGS_START+i] = PreArg;
2140  }
2141
2142  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2143
2144public:
2145  CallExpr(ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2146           ExprValueKind VK, SourceLocation rparenloc);
2147
2148  /// \brief Build an empty call expression.
2149  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
2150
2151  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2152  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2153  void setCallee(Expr *F) { SubExprs[FN] = F; }
2154
2155  Decl *getCalleeDecl();
2156  const Decl *getCalleeDecl() const {
2157    return const_cast<CallExpr*>(this)->getCalleeDecl();
2158  }
2159
2160  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2161  FunctionDecl *getDirectCallee();
2162  const FunctionDecl *getDirectCallee() const {
2163    return const_cast<CallExpr*>(this)->getDirectCallee();
2164  }
2165
2166  /// getNumArgs - Return the number of actual arguments to this call.
2167  ///
2168  unsigned getNumArgs() const { return NumArgs; }
2169
2170  /// \brief Retrieve the call arguments.
2171  Expr **getArgs() {
2172    return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2173  }
2174  const Expr *const *getArgs() const {
2175    return const_cast<CallExpr*>(this)->getArgs();
2176  }
2177
2178  /// getArg - Return the specified argument.
2179  Expr *getArg(unsigned Arg) {
2180    assert(Arg < NumArgs && "Arg access out of range!");
2181    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2182  }
2183  const Expr *getArg(unsigned Arg) const {
2184    assert(Arg < NumArgs && "Arg access out of range!");
2185    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2186  }
2187
2188  /// setArg - Set the specified argument.
2189  void setArg(unsigned Arg, Expr *ArgExpr) {
2190    assert(Arg < NumArgs && "Arg access out of range!");
2191    SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2192  }
2193
2194  /// setNumArgs - This changes the number of arguments present in this call.
2195  /// Any orphaned expressions are deleted by this, and any new operands are set
2196  /// to null.
2197  void setNumArgs(ASTContext& C, unsigned NumArgs);
2198
2199  typedef ExprIterator arg_iterator;
2200  typedef ConstExprIterator const_arg_iterator;
2201
2202  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2203  arg_iterator arg_end() {
2204    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2205  }
2206  const_arg_iterator arg_begin() const {
2207    return SubExprs+PREARGS_START+getNumPreArgs();
2208  }
2209  const_arg_iterator arg_end() const {
2210    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2211  }
2212
2213  /// This method provides fast access to all the subexpressions of
2214  /// a CallExpr without going through the slower virtual child_iterator
2215  /// interface.  This provides efficient reverse iteration of the
2216  /// subexpressions.  This is currently used for CFG construction.
2217  ArrayRef<Stmt*> getRawSubExprs() {
2218    return ArrayRef<Stmt*>(SubExprs,
2219                           getNumPreArgs() + PREARGS_START + getNumArgs());
2220  }
2221
2222  /// getNumCommas - Return the number of commas that must have been present in
2223  /// this function call.
2224  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2225
2226  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
2227  /// not, return 0.
2228  unsigned isBuiltinCall() const;
2229
2230  /// \brief Returns \c true if this is a call to a builtin which does not
2231  /// evaluate side-effects within its arguments.
2232  bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
2233
2234  /// getCallReturnType - Get the return type of the call expr. This is not
2235  /// always the type of the expr itself, if the return type is a reference
2236  /// type.
2237  QualType getCallReturnType() const;
2238
2239  SourceLocation getRParenLoc() const { return RParenLoc; }
2240  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2241
2242  SourceLocation getLocStart() const LLVM_READONLY;
2243  SourceLocation getLocEnd() const LLVM_READONLY;
2244
2245  static bool classof(const Stmt *T) {
2246    return T->getStmtClass() >= firstCallExprConstant &&
2247           T->getStmtClass() <= lastCallExprConstant;
2248  }
2249
2250  // Iterators
2251  child_range children() {
2252    return child_range(&SubExprs[0],
2253                       &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2254  }
2255};
2256
2257/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
2258///
2259class MemberExpr : public Expr {
2260  /// Extra data stored in some member expressions.
2261  struct MemberNameQualifier {
2262    /// \brief The nested-name-specifier that qualifies the name, including
2263    /// source-location information.
2264    NestedNameSpecifierLoc QualifierLoc;
2265
2266    /// \brief The DeclAccessPair through which the MemberDecl was found due to
2267    /// name qualifiers.
2268    DeclAccessPair FoundDecl;
2269  };
2270
2271  /// Base - the expression for the base pointer or structure references.  In
2272  /// X.F, this is "X".
2273  Stmt *Base;
2274
2275  /// MemberDecl - This is the decl being referenced by the field/member name.
2276  /// In X.F, this is the decl referenced by F.
2277  ValueDecl *MemberDecl;
2278
2279  /// MemberDNLoc - Provides source/type location info for the
2280  /// declaration name embedded in MemberDecl.
2281  DeclarationNameLoc MemberDNLoc;
2282
2283  /// MemberLoc - This is the location of the member name.
2284  SourceLocation MemberLoc;
2285
2286  /// IsArrow - True if this is "X->F", false if this is "X.F".
2287  bool IsArrow : 1;
2288
2289  /// \brief True if this member expression used a nested-name-specifier to
2290  /// refer to the member, e.g., "x->Base::f", or found its member via a using
2291  /// declaration.  When true, a MemberNameQualifier
2292  /// structure is allocated immediately after the MemberExpr.
2293  bool HasQualifierOrFoundDecl : 1;
2294
2295  /// \brief True if this member expression specified a template keyword
2296  /// and/or a template argument list explicitly, e.g., x->f<int>,
2297  /// x->template f, x->template f<int>.
2298  /// When true, an ASTTemplateKWAndArgsInfo structure and its
2299  /// TemplateArguments (if any) are allocated immediately after
2300  /// the MemberExpr or, if the member expression also has a qualifier,
2301  /// after the MemberNameQualifier structure.
2302  bool HasTemplateKWAndArgsInfo : 1;
2303
2304  /// \brief True if this member expression refers to a method that
2305  /// was resolved from an overloaded set having size greater than 1.
2306  bool HadMultipleCandidates : 1;
2307
2308  /// \brief Retrieve the qualifier that preceded the member name, if any.
2309  MemberNameQualifier *getMemberQualifier() {
2310    assert(HasQualifierOrFoundDecl);
2311    return reinterpret_cast<MemberNameQualifier *> (this + 1);
2312  }
2313
2314  /// \brief Retrieve the qualifier that preceded the member name, if any.
2315  const MemberNameQualifier *getMemberQualifier() const {
2316    return const_cast<MemberExpr *>(this)->getMemberQualifier();
2317  }
2318
2319public:
2320  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2321             const DeclarationNameInfo &NameInfo, QualType ty,
2322             ExprValueKind VK, ExprObjectKind OK)
2323    : Expr(MemberExprClass, ty, VK, OK,
2324           base->isTypeDependent(),
2325           base->isValueDependent(),
2326           base->isInstantiationDependent(),
2327           base->containsUnexpandedParameterPack()),
2328      Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2329      MemberLoc(NameInfo.getLoc()), IsArrow(isarrow),
2330      HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2331      HadMultipleCandidates(false) {
2332    assert(memberdecl->getDeclName() == NameInfo.getName());
2333  }
2334
2335  // NOTE: this constructor should be used only when it is known that
2336  // the member name can not provide additional syntactic info
2337  // (i.e., source locations for C++ operator names or type source info
2338  // for constructors, destructors and conversion operators).
2339  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2340             SourceLocation l, QualType ty,
2341             ExprValueKind VK, ExprObjectKind OK)
2342    : Expr(MemberExprClass, ty, VK, OK,
2343           base->isTypeDependent(), base->isValueDependent(),
2344           base->isInstantiationDependent(),
2345           base->containsUnexpandedParameterPack()),
2346      Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2347      IsArrow(isarrow),
2348      HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2349      HadMultipleCandidates(false) {}
2350
2351  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
2352                            NestedNameSpecifierLoc QualifierLoc,
2353                            SourceLocation TemplateKWLoc,
2354                            ValueDecl *memberdecl, DeclAccessPair founddecl,
2355                            DeclarationNameInfo MemberNameInfo,
2356                            const TemplateArgumentListInfo *targs,
2357                            QualType ty, ExprValueKind VK, ExprObjectKind OK);
2358
2359  void setBase(Expr *E) { Base = E; }
2360  Expr *getBase() const { return cast<Expr>(Base); }
2361
2362  /// \brief Retrieve the member declaration to which this expression refers.
2363  ///
2364  /// The returned declaration will either be a FieldDecl or (in C++)
2365  /// a CXXMethodDecl.
2366  ValueDecl *getMemberDecl() const { return MemberDecl; }
2367  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2368
2369  /// \brief Retrieves the declaration found by lookup.
2370  DeclAccessPair getFoundDecl() const {
2371    if (!HasQualifierOrFoundDecl)
2372      return DeclAccessPair::make(getMemberDecl(),
2373                                  getMemberDecl()->getAccess());
2374    return getMemberQualifier()->FoundDecl;
2375  }
2376
2377  /// \brief Determines whether this member expression actually had
2378  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2379  /// x->Base::foo.
2380  bool hasQualifier() const { return getQualifier() != 0; }
2381
2382  /// \brief If the member name was qualified, retrieves the
2383  /// nested-name-specifier that precedes the member name. Otherwise, returns
2384  /// NULL.
2385  NestedNameSpecifier *getQualifier() const {
2386    if (!HasQualifierOrFoundDecl)
2387      return 0;
2388
2389    return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2390  }
2391
2392  /// \brief If the member name was qualified, retrieves the
2393  /// nested-name-specifier that precedes the member name, with source-location
2394  /// information.
2395  NestedNameSpecifierLoc getQualifierLoc() const {
2396    if (!hasQualifier())
2397      return NestedNameSpecifierLoc();
2398
2399    return getMemberQualifier()->QualifierLoc;
2400  }
2401
2402  /// \brief Return the optional template keyword and arguments info.
2403  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2404    if (!HasTemplateKWAndArgsInfo)
2405      return 0;
2406
2407    if (!HasQualifierOrFoundDecl)
2408      return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
2409
2410    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
2411                                                      getMemberQualifier() + 1);
2412  }
2413
2414  /// \brief Return the optional template keyword and arguments info.
2415  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2416    return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
2417  }
2418
2419  /// \brief Retrieve the location of the template keyword preceding
2420  /// the member name, if any.
2421  SourceLocation getTemplateKeywordLoc() const {
2422    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2423    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2424  }
2425
2426  /// \brief Retrieve the location of the left angle bracket starting the
2427  /// explicit template argument list following the member name, if any.
2428  SourceLocation getLAngleLoc() const {
2429    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2430    return getTemplateKWAndArgsInfo()->LAngleLoc;
2431  }
2432
2433  /// \brief Retrieve the location of the right angle bracket ending the
2434  /// explicit template argument list following the member name, if any.
2435  SourceLocation getRAngleLoc() const {
2436    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2437    return getTemplateKWAndArgsInfo()->RAngleLoc;
2438  }
2439
2440  /// Determines whether the member name was preceded by the template keyword.
2441  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2442
2443  /// \brief Determines whether the member name was followed by an
2444  /// explicit template argument list.
2445  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2446
2447  /// \brief Copies the template arguments (if present) into the given
2448  /// structure.
2449  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2450    if (hasExplicitTemplateArgs())
2451      getExplicitTemplateArgs().copyInto(List);
2452  }
2453
2454  /// \brief Retrieve the explicit template argument list that
2455  /// follow the member template name.  This must only be called on an
2456  /// expression with explicit template arguments.
2457  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2458    assert(hasExplicitTemplateArgs());
2459    return *getTemplateKWAndArgsInfo();
2460  }
2461
2462  /// \brief Retrieve the explicit template argument list that
2463  /// followed the member template name.  This must only be called on
2464  /// an expression with explicit template arguments.
2465  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2466    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2467  }
2468
2469  /// \brief Retrieves the optional explicit template arguments.
2470  /// This points to the same data as getExplicitTemplateArgs(), but
2471  /// returns null if there are no explicit template arguments.
2472  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2473    if (!hasExplicitTemplateArgs()) return 0;
2474    return &getExplicitTemplateArgs();
2475  }
2476
2477  /// \brief Retrieve the template arguments provided as part of this
2478  /// template-id.
2479  const TemplateArgumentLoc *getTemplateArgs() const {
2480    if (!hasExplicitTemplateArgs())
2481      return 0;
2482
2483    return getExplicitTemplateArgs().getTemplateArgs();
2484  }
2485
2486  /// \brief Retrieve the number of template arguments provided as part of this
2487  /// template-id.
2488  unsigned getNumTemplateArgs() const {
2489    if (!hasExplicitTemplateArgs())
2490      return 0;
2491
2492    return getExplicitTemplateArgs().NumTemplateArgs;
2493  }
2494
2495  /// \brief Retrieve the member declaration name info.
2496  DeclarationNameInfo getMemberNameInfo() const {
2497    return DeclarationNameInfo(MemberDecl->getDeclName(),
2498                               MemberLoc, MemberDNLoc);
2499  }
2500
2501  bool isArrow() const { return IsArrow; }
2502  void setArrow(bool A) { IsArrow = A; }
2503
2504  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2505  /// location of 'F'.
2506  SourceLocation getMemberLoc() const { return MemberLoc; }
2507  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2508
2509  SourceLocation getLocStart() const LLVM_READONLY;
2510  SourceLocation getLocEnd() const LLVM_READONLY;
2511
2512  SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2513
2514  /// \brief Determine whether the base of this explicit is implicit.
2515  bool isImplicitAccess() const {
2516    return getBase() && getBase()->isImplicitCXXThis();
2517  }
2518
2519  /// \brief Returns true if this member expression refers to a method that
2520  /// was resolved from an overloaded set having size greater than 1.
2521  bool hadMultipleCandidates() const {
2522    return HadMultipleCandidates;
2523  }
2524  /// \brief Sets the flag telling whether this expression refers to
2525  /// a method that was resolved from an overloaded set having size
2526  /// greater than 1.
2527  void setHadMultipleCandidates(bool V = true) {
2528    HadMultipleCandidates = V;
2529  }
2530
2531  static bool classof(const Stmt *T) {
2532    return T->getStmtClass() == MemberExprClass;
2533  }
2534
2535  // Iterators
2536  child_range children() { return child_range(&Base, &Base+1); }
2537
2538  friend class ASTReader;
2539  friend class ASTStmtWriter;
2540};
2541
2542/// CompoundLiteralExpr - [C99 6.5.2.5]
2543///
2544class CompoundLiteralExpr : public Expr {
2545  /// LParenLoc - If non-null, this is the location of the left paren in a
2546  /// compound literal like "(int){4}".  This can be null if this is a
2547  /// synthesized compound expression.
2548  SourceLocation LParenLoc;
2549
2550  /// The type as written.  This can be an incomplete array type, in
2551  /// which case the actual expression type will be different.
2552  /// The int part of the pair stores whether this expr is file scope.
2553  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2554  Stmt *Init;
2555public:
2556  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2557                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2558    : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2559           tinfo->getType()->isDependentType(),
2560           init->isValueDependent(),
2561           (init->isInstantiationDependent() ||
2562            tinfo->getType()->isInstantiationDependentType()),
2563           init->containsUnexpandedParameterPack()),
2564      LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2565
2566  /// \brief Construct an empty compound literal.
2567  explicit CompoundLiteralExpr(EmptyShell Empty)
2568    : Expr(CompoundLiteralExprClass, Empty) { }
2569
2570  const Expr *getInitializer() const { return cast<Expr>(Init); }
2571  Expr *getInitializer() { return cast<Expr>(Init); }
2572  void setInitializer(Expr *E) { Init = E; }
2573
2574  bool isFileScope() const { return TInfoAndScope.getInt(); }
2575  void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2576
2577  SourceLocation getLParenLoc() const { return LParenLoc; }
2578  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2579
2580  TypeSourceInfo *getTypeSourceInfo() const {
2581    return TInfoAndScope.getPointer();
2582  }
2583  void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2584    TInfoAndScope.setPointer(tinfo);
2585  }
2586
2587  SourceLocation getLocStart() const LLVM_READONLY {
2588    // FIXME: Init should never be null.
2589    if (!Init)
2590      return SourceLocation();
2591    if (LParenLoc.isInvalid())
2592      return Init->getLocStart();
2593    return LParenLoc;
2594  }
2595  SourceLocation getLocEnd() const LLVM_READONLY {
2596    // FIXME: Init should never be null.
2597    if (!Init)
2598      return SourceLocation();
2599    return Init->getLocEnd();
2600  }
2601
2602  static bool classof(const Stmt *T) {
2603    return T->getStmtClass() == CompoundLiteralExprClass;
2604  }
2605
2606  // Iterators
2607  child_range children() { return child_range(&Init, &Init+1); }
2608};
2609
2610/// CastExpr - Base class for type casts, including both implicit
2611/// casts (ImplicitCastExpr) and explicit casts that have some
2612/// representation in the source code (ExplicitCastExpr's derived
2613/// classes).
2614class CastExpr : public Expr {
2615public:
2616  typedef clang::CastKind CastKind;
2617
2618private:
2619  Stmt *Op;
2620
2621  void CheckCastConsistency() const;
2622
2623  const CXXBaseSpecifier * const *path_buffer() const {
2624    return const_cast<CastExpr*>(this)->path_buffer();
2625  }
2626  CXXBaseSpecifier **path_buffer();
2627
2628  void setBasePathSize(unsigned basePathSize) {
2629    CastExprBits.BasePathSize = basePathSize;
2630    assert(CastExprBits.BasePathSize == basePathSize &&
2631           "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2632  }
2633
2634protected:
2635  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2636           const CastKind kind, Expr *op, unsigned BasePathSize) :
2637    Expr(SC, ty, VK, OK_Ordinary,
2638         // Cast expressions are type-dependent if the type is
2639         // dependent (C++ [temp.dep.expr]p3).
2640         ty->isDependentType(),
2641         // Cast expressions are value-dependent if the type is
2642         // dependent or if the subexpression is value-dependent.
2643         ty->isDependentType() || (op && op->isValueDependent()),
2644         (ty->isInstantiationDependentType() ||
2645          (op && op->isInstantiationDependent())),
2646         (ty->containsUnexpandedParameterPack() ||
2647          (op && op->containsUnexpandedParameterPack()))),
2648    Op(op) {
2649    assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2650    CastExprBits.Kind = kind;
2651    setBasePathSize(BasePathSize);
2652#ifndef NDEBUG
2653    CheckCastConsistency();
2654#endif
2655  }
2656
2657  /// \brief Construct an empty cast.
2658  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2659    : Expr(SC, Empty) {
2660    setBasePathSize(BasePathSize);
2661  }
2662
2663public:
2664  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2665  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2666  const char *getCastKindName() const;
2667
2668  Expr *getSubExpr() { return cast<Expr>(Op); }
2669  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2670  void setSubExpr(Expr *E) { Op = E; }
2671
2672  /// \brief Retrieve the cast subexpression as it was written in the source
2673  /// code, looking through any implicit casts or other intermediate nodes
2674  /// introduced by semantic analysis.
2675  Expr *getSubExprAsWritten();
2676  const Expr *getSubExprAsWritten() const {
2677    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2678  }
2679
2680  typedef CXXBaseSpecifier **path_iterator;
2681  typedef const CXXBaseSpecifier * const *path_const_iterator;
2682  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2683  unsigned path_size() const { return CastExprBits.BasePathSize; }
2684  path_iterator path_begin() { return path_buffer(); }
2685  path_iterator path_end() { return path_buffer() + path_size(); }
2686  path_const_iterator path_begin() const { return path_buffer(); }
2687  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2688
2689  void setCastPath(const CXXCastPath &Path);
2690
2691  static bool classof(const Stmt *T) {
2692    return T->getStmtClass() >= firstCastExprConstant &&
2693           T->getStmtClass() <= lastCastExprConstant;
2694  }
2695
2696  // Iterators
2697  child_range children() { return child_range(&Op, &Op+1); }
2698};
2699
2700/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2701/// conversions, which have no direct representation in the original
2702/// source code. For example: converting T[]->T*, void f()->void
2703/// (*f)(), float->double, short->int, etc.
2704///
2705/// In C, implicit casts always produce rvalues. However, in C++, an
2706/// implicit cast whose result is being bound to a reference will be
2707/// an lvalue or xvalue. For example:
2708///
2709/// @code
2710/// class Base { };
2711/// class Derived : public Base { };
2712/// Derived &&ref();
2713/// void f(Derived d) {
2714///   Base& b = d; // initializer is an ImplicitCastExpr
2715///                // to an lvalue of type Base
2716///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2717///                     // to an xvalue of type Base
2718/// }
2719/// @endcode
2720class ImplicitCastExpr : public CastExpr {
2721private:
2722  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2723                   unsigned BasePathLength, ExprValueKind VK)
2724    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2725  }
2726
2727  /// \brief Construct an empty implicit cast.
2728  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2729    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2730
2731public:
2732  enum OnStack_t { OnStack };
2733  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2734                   ExprValueKind VK)
2735    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2736  }
2737
2738  static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2739                                  CastKind Kind, Expr *Operand,
2740                                  const CXXCastPath *BasePath,
2741                                  ExprValueKind Cat);
2742
2743  static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2744
2745  SourceLocation getLocStart() const LLVM_READONLY {
2746    return getSubExpr()->getLocStart();
2747  }
2748  SourceLocation getLocEnd() const LLVM_READONLY {
2749    return getSubExpr()->getLocEnd();
2750  }
2751
2752  static bool classof(const Stmt *T) {
2753    return T->getStmtClass() == ImplicitCastExprClass;
2754  }
2755};
2756
2757inline Expr *Expr::IgnoreImpCasts() {
2758  Expr *e = this;
2759  while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2760    e = ice->getSubExpr();
2761  return e;
2762}
2763
2764/// ExplicitCastExpr - An explicit cast written in the source
2765/// code.
2766///
2767/// This class is effectively an abstract class, because it provides
2768/// the basic representation of an explicitly-written cast without
2769/// specifying which kind of cast (C cast, functional cast, static
2770/// cast, etc.) was written; specific derived classes represent the
2771/// particular style of cast and its location information.
2772///
2773/// Unlike implicit casts, explicit cast nodes have two different
2774/// types: the type that was written into the source code, and the
2775/// actual type of the expression as determined by semantic
2776/// analysis. These types may differ slightly. For example, in C++ one
2777/// can cast to a reference type, which indicates that the resulting
2778/// expression will be an lvalue or xvalue. The reference type, however,
2779/// will not be used as the type of the expression.
2780class ExplicitCastExpr : public CastExpr {
2781  /// TInfo - Source type info for the (written) type
2782  /// this expression is casting to.
2783  TypeSourceInfo *TInfo;
2784
2785protected:
2786  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2787                   CastKind kind, Expr *op, unsigned PathSize,
2788                   TypeSourceInfo *writtenTy)
2789    : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2790
2791  /// \brief Construct an empty explicit cast.
2792  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2793    : CastExpr(SC, Shell, PathSize) { }
2794
2795public:
2796  /// getTypeInfoAsWritten - Returns the type source info for the type
2797  /// that this expression is casting to.
2798  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2799  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2800
2801  /// getTypeAsWritten - Returns the type that this expression is
2802  /// casting to, as written in the source code.
2803  QualType getTypeAsWritten() const { return TInfo->getType(); }
2804
2805  static bool classof(const Stmt *T) {
2806     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2807            T->getStmtClass() <= lastExplicitCastExprConstant;
2808  }
2809};
2810
2811/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2812/// cast in C++ (C++ [expr.cast]), which uses the syntax
2813/// (Type)expr. For example: @c (int)f.
2814class CStyleCastExpr : public ExplicitCastExpr {
2815  SourceLocation LPLoc; // the location of the left paren
2816  SourceLocation RPLoc; // the location of the right paren
2817
2818  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2819                 unsigned PathSize, TypeSourceInfo *writtenTy,
2820                 SourceLocation l, SourceLocation r)
2821    : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2822                       writtenTy), LPLoc(l), RPLoc(r) {}
2823
2824  /// \brief Construct an empty C-style explicit cast.
2825  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2826    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2827
2828public:
2829  static CStyleCastExpr *Create(ASTContext &Context, QualType T,
2830                                ExprValueKind VK, CastKind K,
2831                                Expr *Op, const CXXCastPath *BasePath,
2832                                TypeSourceInfo *WrittenTy, SourceLocation L,
2833                                SourceLocation R);
2834
2835  static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2836
2837  SourceLocation getLParenLoc() const { return LPLoc; }
2838  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2839
2840  SourceLocation getRParenLoc() const { return RPLoc; }
2841  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2842
2843  SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2844  SourceLocation getLocEnd() const LLVM_READONLY {
2845    return getSubExpr()->getLocEnd();
2846  }
2847
2848  static bool classof(const Stmt *T) {
2849    return T->getStmtClass() == CStyleCastExprClass;
2850  }
2851};
2852
2853/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2854///
2855/// This expression node kind describes a builtin binary operation,
2856/// such as "x + y" for integer values "x" and "y". The operands will
2857/// already have been converted to appropriate types (e.g., by
2858/// performing promotions or conversions).
2859///
2860/// In C++, where operators may be overloaded, a different kind of
2861/// expression node (CXXOperatorCallExpr) is used to express the
2862/// invocation of an overloaded operator with operator syntax. Within
2863/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2864/// used to store an expression "x + y" depends on the subexpressions
2865/// for x and y. If neither x or y is type-dependent, and the "+"
2866/// operator resolves to a built-in operation, BinaryOperator will be
2867/// used to express the computation (x and y may still be
2868/// value-dependent). If either x or y is type-dependent, or if the
2869/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2870/// be used to express the computation.
2871class BinaryOperator : public Expr {
2872public:
2873  typedef BinaryOperatorKind Opcode;
2874
2875private:
2876  unsigned Opc : 6;
2877
2878  // Records the FP_CONTRACT pragma status at the point that this binary
2879  // operator was parsed. This bit is only meaningful for operations on
2880  // floating point types. For all other types it should default to
2881  // false.
2882  unsigned FPContractable : 1;
2883  SourceLocation OpLoc;
2884
2885  enum { LHS, RHS, END_EXPR };
2886  Stmt* SubExprs[END_EXPR];
2887public:
2888
2889  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2890                 ExprValueKind VK, ExprObjectKind OK,
2891                 SourceLocation opLoc, bool fpContractable)
2892    : Expr(BinaryOperatorClass, ResTy, VK, OK,
2893           lhs->isTypeDependent() || rhs->isTypeDependent(),
2894           lhs->isValueDependent() || rhs->isValueDependent(),
2895           (lhs->isInstantiationDependent() ||
2896            rhs->isInstantiationDependent()),
2897           (lhs->containsUnexpandedParameterPack() ||
2898            rhs->containsUnexpandedParameterPack())),
2899      Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2900    SubExprs[LHS] = lhs;
2901    SubExprs[RHS] = rhs;
2902    assert(!isCompoundAssignmentOp() &&
2903           "Use CompoundAssignOperator for compound assignments");
2904  }
2905
2906  /// \brief Construct an empty binary operator.
2907  explicit BinaryOperator(EmptyShell Empty)
2908    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2909
2910  SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2911  SourceLocation getOperatorLoc() const { return OpLoc; }
2912  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2913
2914  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2915  void setOpcode(Opcode O) { Opc = O; }
2916
2917  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2918  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2919  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2920  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2921
2922  SourceLocation getLocStart() const LLVM_READONLY {
2923    return getLHS()->getLocStart();
2924  }
2925  SourceLocation getLocEnd() const LLVM_READONLY {
2926    return getRHS()->getLocEnd();
2927  }
2928
2929  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2930  /// corresponds to, e.g. "<<=".
2931  static StringRef getOpcodeStr(Opcode Op);
2932
2933  StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2934
2935  /// \brief Retrieve the binary opcode that corresponds to the given
2936  /// overloaded operator.
2937  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2938
2939  /// \brief Retrieve the overloaded operator kind that corresponds to
2940  /// the given binary opcode.
2941  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2942
2943  /// predicates to categorize the respective opcodes.
2944  bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2945  bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2946  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2947  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2948  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2949  bool isShiftOp() const { return isShiftOp(getOpcode()); }
2950
2951  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2952  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2953
2954  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2955  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2956
2957  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2958  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2959
2960  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2961  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2962
2963  static Opcode negateComparisonOp(Opcode Opc) {
2964    switch (Opc) {
2965    default:
2966      llvm_unreachable("Not a comparsion operator.");
2967    case BO_LT: return BO_GE;
2968    case BO_GT: return BO_LE;
2969    case BO_LE: return BO_GT;
2970    case BO_GE: return BO_LT;
2971    case BO_EQ: return BO_NE;
2972    case BO_NE: return BO_EQ;
2973    }
2974  }
2975
2976  static Opcode reverseComparisonOp(Opcode Opc) {
2977    switch (Opc) {
2978    default:
2979      llvm_unreachable("Not a comparsion operator.");
2980    case BO_LT: return BO_GT;
2981    case BO_GT: return BO_LT;
2982    case BO_LE: return BO_GE;
2983    case BO_GE: return BO_LE;
2984    case BO_EQ:
2985    case BO_NE:
2986      return Opc;
2987    }
2988  }
2989
2990  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2991  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2992
2993  static bool isAssignmentOp(Opcode Opc) {
2994    return Opc >= BO_Assign && Opc <= BO_OrAssign;
2995  }
2996  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
2997
2998  static bool isCompoundAssignmentOp(Opcode Opc) {
2999    return Opc > BO_Assign && Opc <= BO_OrAssign;
3000  }
3001  bool isCompoundAssignmentOp() const {
3002    return isCompoundAssignmentOp(getOpcode());
3003  }
3004  static Opcode getOpForCompoundAssignment(Opcode Opc) {
3005    assert(isCompoundAssignmentOp(Opc));
3006    if (Opc >= BO_AndAssign)
3007      return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3008    else
3009      return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3010  }
3011
3012  static bool isShiftAssignOp(Opcode Opc) {
3013    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3014  }
3015  bool isShiftAssignOp() const {
3016    return isShiftAssignOp(getOpcode());
3017  }
3018
3019  static bool classof(const Stmt *S) {
3020    return S->getStmtClass() >= firstBinaryOperatorConstant &&
3021           S->getStmtClass() <= lastBinaryOperatorConstant;
3022  }
3023
3024  // Iterators
3025  child_range children() {
3026    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3027  }
3028
3029  // Set the FP contractability status of this operator. Only meaningful for
3030  // operations on floating point types.
3031  void setFPContractable(bool FPC) { FPContractable = FPC; }
3032
3033  // Get the FP contractability status of this operator. Only meaningful for
3034  // operations on floating point types.
3035  bool isFPContractable() const { return FPContractable; }
3036
3037protected:
3038  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3039                 ExprValueKind VK, ExprObjectKind OK,
3040                 SourceLocation opLoc, bool fpContractable, bool dead2)
3041    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3042           lhs->isTypeDependent() || rhs->isTypeDependent(),
3043           lhs->isValueDependent() || rhs->isValueDependent(),
3044           (lhs->isInstantiationDependent() ||
3045            rhs->isInstantiationDependent()),
3046           (lhs->containsUnexpandedParameterPack() ||
3047            rhs->containsUnexpandedParameterPack())),
3048      Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3049    SubExprs[LHS] = lhs;
3050    SubExprs[RHS] = rhs;
3051  }
3052
3053  BinaryOperator(StmtClass SC, EmptyShell Empty)
3054    : Expr(SC, Empty), Opc(BO_MulAssign) { }
3055};
3056
3057/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3058/// track of the type the operation is performed in.  Due to the semantics of
3059/// these operators, the operands are promoted, the arithmetic performed, an
3060/// implicit conversion back to the result type done, then the assignment takes
3061/// place.  This captures the intermediate type which the computation is done
3062/// in.
3063class CompoundAssignOperator : public BinaryOperator {
3064  QualType ComputationLHSType;
3065  QualType ComputationResultType;
3066public:
3067  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3068                         ExprValueKind VK, ExprObjectKind OK,
3069                         QualType CompLHSType, QualType CompResultType,
3070                         SourceLocation OpLoc, bool fpContractable)
3071    : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3072                     true),
3073      ComputationLHSType(CompLHSType),
3074      ComputationResultType(CompResultType) {
3075    assert(isCompoundAssignmentOp() &&
3076           "Only should be used for compound assignments");
3077  }
3078
3079  /// \brief Build an empty compound assignment operator expression.
3080  explicit CompoundAssignOperator(EmptyShell Empty)
3081    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3082
3083  // The two computation types are the type the LHS is converted
3084  // to for the computation and the type of the result; the two are
3085  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3086  QualType getComputationLHSType() const { return ComputationLHSType; }
3087  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3088
3089  QualType getComputationResultType() const { return ComputationResultType; }
3090  void setComputationResultType(QualType T) { ComputationResultType = T; }
3091
3092  static bool classof(const Stmt *S) {
3093    return S->getStmtClass() == CompoundAssignOperatorClass;
3094  }
3095};
3096
3097/// AbstractConditionalOperator - An abstract base class for
3098/// ConditionalOperator and BinaryConditionalOperator.
3099class AbstractConditionalOperator : public Expr {
3100  SourceLocation QuestionLoc, ColonLoc;
3101  friend class ASTStmtReader;
3102
3103protected:
3104  AbstractConditionalOperator(StmtClass SC, QualType T,
3105                              ExprValueKind VK, ExprObjectKind OK,
3106                              bool TD, bool VD, bool ID,
3107                              bool ContainsUnexpandedParameterPack,
3108                              SourceLocation qloc,
3109                              SourceLocation cloc)
3110    : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3111      QuestionLoc(qloc), ColonLoc(cloc) {}
3112
3113  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3114    : Expr(SC, Empty) { }
3115
3116public:
3117  // getCond - Return the expression representing the condition for
3118  //   the ?: operator.
3119  Expr *getCond() const;
3120
3121  // getTrueExpr - Return the subexpression representing the value of
3122  //   the expression if the condition evaluates to true.
3123  Expr *getTrueExpr() const;
3124
3125  // getFalseExpr - Return the subexpression representing the value of
3126  //   the expression if the condition evaluates to false.  This is
3127  //   the same as getRHS.
3128  Expr *getFalseExpr() const;
3129
3130  SourceLocation getQuestionLoc() const { return QuestionLoc; }
3131  SourceLocation getColonLoc() const { return ColonLoc; }
3132
3133  static bool classof(const Stmt *T) {
3134    return T->getStmtClass() == ConditionalOperatorClass ||
3135           T->getStmtClass() == BinaryConditionalOperatorClass;
3136  }
3137};
3138
3139/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
3140/// middle" extension is a BinaryConditionalOperator.
3141class ConditionalOperator : public AbstractConditionalOperator {
3142  enum { COND, LHS, RHS, END_EXPR };
3143  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3144
3145  friend class ASTStmtReader;
3146public:
3147  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3148                      SourceLocation CLoc, Expr *rhs,
3149                      QualType t, ExprValueKind VK, ExprObjectKind OK)
3150    : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3151           // FIXME: the type of the conditional operator doesn't
3152           // depend on the type of the conditional, but the standard
3153           // seems to imply that it could. File a bug!
3154           (lhs->isTypeDependent() || rhs->isTypeDependent()),
3155           (cond->isValueDependent() || lhs->isValueDependent() ||
3156            rhs->isValueDependent()),
3157           (cond->isInstantiationDependent() ||
3158            lhs->isInstantiationDependent() ||
3159            rhs->isInstantiationDependent()),
3160           (cond->containsUnexpandedParameterPack() ||
3161            lhs->containsUnexpandedParameterPack() ||
3162            rhs->containsUnexpandedParameterPack()),
3163                                  QLoc, CLoc) {
3164    SubExprs[COND] = cond;
3165    SubExprs[LHS] = lhs;
3166    SubExprs[RHS] = rhs;
3167  }
3168
3169  /// \brief Build an empty conditional operator.
3170  explicit ConditionalOperator(EmptyShell Empty)
3171    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3172
3173  // getCond - Return the expression representing the condition for
3174  //   the ?: operator.
3175  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3176
3177  // getTrueExpr - Return the subexpression representing the value of
3178  //   the expression if the condition evaluates to true.
3179  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3180
3181  // getFalseExpr - Return the subexpression representing the value of
3182  //   the expression if the condition evaluates to false.  This is
3183  //   the same as getRHS.
3184  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3185
3186  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3187  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3188
3189  SourceLocation getLocStart() const LLVM_READONLY {
3190    return getCond()->getLocStart();
3191  }
3192  SourceLocation getLocEnd() const LLVM_READONLY {
3193    return getRHS()->getLocEnd();
3194  }
3195
3196  static bool classof(const Stmt *T) {
3197    return T->getStmtClass() == ConditionalOperatorClass;
3198  }
3199
3200  // Iterators
3201  child_range children() {
3202    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3203  }
3204};
3205
3206/// BinaryConditionalOperator - The GNU extension to the conditional
3207/// operator which allows the middle operand to be omitted.
3208///
3209/// This is a different expression kind on the assumption that almost
3210/// every client ends up needing to know that these are different.
3211class BinaryConditionalOperator : public AbstractConditionalOperator {
3212  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3213
3214  /// - the common condition/left-hand-side expression, which will be
3215  ///   evaluated as the opaque value
3216  /// - the condition, expressed in terms of the opaque value
3217  /// - the left-hand-side, expressed in terms of the opaque value
3218  /// - the right-hand-side
3219  Stmt *SubExprs[NUM_SUBEXPRS];
3220  OpaqueValueExpr *OpaqueValue;
3221
3222  friend class ASTStmtReader;
3223public:
3224  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3225                            Expr *cond, Expr *lhs, Expr *rhs,
3226                            SourceLocation qloc, SourceLocation cloc,
3227                            QualType t, ExprValueKind VK, ExprObjectKind OK)
3228    : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3229           (common->isTypeDependent() || rhs->isTypeDependent()),
3230           (common->isValueDependent() || rhs->isValueDependent()),
3231           (common->isInstantiationDependent() ||
3232            rhs->isInstantiationDependent()),
3233           (common->containsUnexpandedParameterPack() ||
3234            rhs->containsUnexpandedParameterPack()),
3235                                  qloc, cloc),
3236      OpaqueValue(opaqueValue) {
3237    SubExprs[COMMON] = common;
3238    SubExprs[COND] = cond;
3239    SubExprs[LHS] = lhs;
3240    SubExprs[RHS] = rhs;
3241    assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3242  }
3243
3244  /// \brief Build an empty conditional operator.
3245  explicit BinaryConditionalOperator(EmptyShell Empty)
3246    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3247
3248  /// \brief getCommon - Return the common expression, written to the
3249  ///   left of the condition.  The opaque value will be bound to the
3250  ///   result of this expression.
3251  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3252
3253  /// \brief getOpaqueValue - Return the opaque value placeholder.
3254  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3255
3256  /// \brief getCond - Return the condition expression; this is defined
3257  ///   in terms of the opaque value.
3258  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3259
3260  /// \brief getTrueExpr - Return the subexpression which will be
3261  ///   evaluated if the condition evaluates to true;  this is defined
3262  ///   in terms of the opaque value.
3263  Expr *getTrueExpr() const {
3264    return cast<Expr>(SubExprs[LHS]);
3265  }
3266
3267  /// \brief getFalseExpr - Return the subexpression which will be
3268  ///   evaluated if the condnition evaluates to false; this is
3269  ///   defined in terms of the opaque value.
3270  Expr *getFalseExpr() const {
3271    return cast<Expr>(SubExprs[RHS]);
3272  }
3273
3274  SourceLocation getLocStart() const LLVM_READONLY {
3275    return getCommon()->getLocStart();
3276  }
3277  SourceLocation getLocEnd() const LLVM_READONLY {
3278    return getFalseExpr()->getLocEnd();
3279  }
3280
3281  static bool classof(const Stmt *T) {
3282    return T->getStmtClass() == BinaryConditionalOperatorClass;
3283  }
3284
3285  // Iterators
3286  child_range children() {
3287    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3288  }
3289};
3290
3291inline Expr *AbstractConditionalOperator::getCond() const {
3292  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3293    return co->getCond();
3294  return cast<BinaryConditionalOperator>(this)->getCond();
3295}
3296
3297inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3298  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3299    return co->getTrueExpr();
3300  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3301}
3302
3303inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3304  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3305    return co->getFalseExpr();
3306  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3307}
3308
3309/// AddrLabelExpr - The GNU address of label extension, representing &&label.
3310class AddrLabelExpr : public Expr {
3311  SourceLocation AmpAmpLoc, LabelLoc;
3312  LabelDecl *Label;
3313public:
3314  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3315                QualType t)
3316    : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3317           false),
3318      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3319
3320  /// \brief Build an empty address of a label expression.
3321  explicit AddrLabelExpr(EmptyShell Empty)
3322    : Expr(AddrLabelExprClass, Empty) { }
3323
3324  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3325  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3326  SourceLocation getLabelLoc() const { return LabelLoc; }
3327  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3328
3329  SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3330  SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3331
3332  LabelDecl *getLabel() const { return Label; }
3333  void setLabel(LabelDecl *L) { Label = L; }
3334
3335  static bool classof(const Stmt *T) {
3336    return T->getStmtClass() == AddrLabelExprClass;
3337  }
3338
3339  // Iterators
3340  child_range children() { return child_range(); }
3341};
3342
3343/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3344/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3345/// takes the value of the last subexpression.
3346///
3347/// A StmtExpr is always an r-value; values "returned" out of a
3348/// StmtExpr will be copied.
3349class StmtExpr : public Expr {
3350  Stmt *SubStmt;
3351  SourceLocation LParenLoc, RParenLoc;
3352public:
3353  // FIXME: Does type-dependence need to be computed differently?
3354  // FIXME: Do we need to compute instantiation instantiation-dependence for
3355  // statements? (ugh!)
3356  StmtExpr(CompoundStmt *substmt, QualType T,
3357           SourceLocation lp, SourceLocation rp) :
3358    Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3359         T->isDependentType(), false, false, false),
3360    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3361
3362  /// \brief Build an empty statement expression.
3363  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3364
3365  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3366  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3367  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3368
3369  SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3370  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3371
3372  SourceLocation getLParenLoc() const { return LParenLoc; }
3373  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3374  SourceLocation getRParenLoc() const { return RParenLoc; }
3375  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3376
3377  static bool classof(const Stmt *T) {
3378    return T->getStmtClass() == StmtExprClass;
3379  }
3380
3381  // Iterators
3382  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3383};
3384
3385
3386/// ShuffleVectorExpr - clang-specific builtin-in function
3387/// __builtin_shufflevector.
3388/// This AST node represents a operator that does a constant
3389/// shuffle, similar to LLVM's shufflevector instruction. It takes
3390/// two vectors and a variable number of constant indices,
3391/// and returns the appropriately shuffled vector.
3392class ShuffleVectorExpr : public Expr {
3393  SourceLocation BuiltinLoc, RParenLoc;
3394
3395  // SubExprs - the list of values passed to the __builtin_shufflevector
3396  // function. The first two are vectors, and the rest are constant
3397  // indices.  The number of values in this list is always
3398  // 2+the number of indices in the vector type.
3399  Stmt **SubExprs;
3400  unsigned NumExprs;
3401
3402public:
3403  ShuffleVectorExpr(ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3404                    SourceLocation BLoc, SourceLocation RP);
3405
3406  /// \brief Build an empty vector-shuffle expression.
3407  explicit ShuffleVectorExpr(EmptyShell Empty)
3408    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
3409
3410  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3411  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3412
3413  SourceLocation getRParenLoc() const { return RParenLoc; }
3414  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3415
3416  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3417  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3418
3419  static bool classof(const Stmt *T) {
3420    return T->getStmtClass() == ShuffleVectorExprClass;
3421  }
3422
3423  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
3424  /// constant expression, the actual arguments passed in, and the function
3425  /// pointers.
3426  unsigned getNumSubExprs() const { return NumExprs; }
3427
3428  /// \brief Retrieve the array of expressions.
3429  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3430
3431  /// getExpr - Return the Expr at the specified index.
3432  Expr *getExpr(unsigned Index) {
3433    assert((Index < NumExprs) && "Arg access out of range!");
3434    return cast<Expr>(SubExprs[Index]);
3435  }
3436  const Expr *getExpr(unsigned Index) const {
3437    assert((Index < NumExprs) && "Arg access out of range!");
3438    return cast<Expr>(SubExprs[Index]);
3439  }
3440
3441  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
3442
3443  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) const {
3444    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3445    return getExpr(N+2)->EvaluateKnownConstInt(Ctx).getZExtValue();
3446  }
3447
3448  // Iterators
3449  child_range children() {
3450    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3451  }
3452};
3453
3454/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3455/// This AST node is similar to the conditional operator (?:) in C, with
3456/// the following exceptions:
3457/// - the test expression must be a integer constant expression.
3458/// - the expression returned acts like the chosen subexpression in every
3459///   visible way: the type is the same as that of the chosen subexpression,
3460///   and all predicates (whether it's an l-value, whether it's an integer
3461///   constant expression, etc.) return the same result as for the chosen
3462///   sub-expression.
3463class ChooseExpr : public Expr {
3464  enum { COND, LHS, RHS, END_EXPR };
3465  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3466  SourceLocation BuiltinLoc, RParenLoc;
3467public:
3468  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3469             QualType t, ExprValueKind VK, ExprObjectKind OK,
3470             SourceLocation RP, bool TypeDependent, bool ValueDependent)
3471    : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3472           (cond->isInstantiationDependent() ||
3473            lhs->isInstantiationDependent() ||
3474            rhs->isInstantiationDependent()),
3475           (cond->containsUnexpandedParameterPack() ||
3476            lhs->containsUnexpandedParameterPack() ||
3477            rhs->containsUnexpandedParameterPack())),
3478      BuiltinLoc(BLoc), RParenLoc(RP) {
3479      SubExprs[COND] = cond;
3480      SubExprs[LHS] = lhs;
3481      SubExprs[RHS] = rhs;
3482    }
3483
3484  /// \brief Build an empty __builtin_choose_expr.
3485  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3486
3487  /// isConditionTrue - Return whether the condition is true (i.e. not
3488  /// equal to zero).
3489  bool isConditionTrue(const ASTContext &C) const;
3490
3491  /// getChosenSubExpr - Return the subexpression chosen according to the
3492  /// condition.
3493  Expr *getChosenSubExpr(const ASTContext &C) const {
3494    return isConditionTrue(C) ? getLHS() : getRHS();
3495  }
3496
3497  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3498  void setCond(Expr *E) { SubExprs[COND] = E; }
3499  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3500  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3501  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3502  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3503
3504  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3505  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3506
3507  SourceLocation getRParenLoc() const { return RParenLoc; }
3508  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3509
3510  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3511  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3512
3513  static bool classof(const Stmt *T) {
3514    return T->getStmtClass() == ChooseExprClass;
3515  }
3516
3517  // Iterators
3518  child_range children() {
3519    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3520  }
3521};
3522
3523/// GNUNullExpr - Implements the GNU __null extension, which is a name
3524/// for a null pointer constant that has integral type (e.g., int or
3525/// long) and is the same size and alignment as a pointer. The __null
3526/// extension is typically only used by system headers, which define
3527/// NULL as __null in C++ rather than using 0 (which is an integer
3528/// that may not match the size of a pointer).
3529class GNUNullExpr : public Expr {
3530  /// TokenLoc - The location of the __null keyword.
3531  SourceLocation TokenLoc;
3532
3533public:
3534  GNUNullExpr(QualType Ty, SourceLocation Loc)
3535    : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3536           false),
3537      TokenLoc(Loc) { }
3538
3539  /// \brief Build an empty GNU __null expression.
3540  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3541
3542  /// getTokenLocation - The location of the __null token.
3543  SourceLocation getTokenLocation() const { return TokenLoc; }
3544  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3545
3546  SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3547  SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3548
3549  static bool classof(const Stmt *T) {
3550    return T->getStmtClass() == GNUNullExprClass;
3551  }
3552
3553  // Iterators
3554  child_range children() { return child_range(); }
3555};
3556
3557/// VAArgExpr, used for the builtin function __builtin_va_arg.
3558class VAArgExpr : public Expr {
3559  Stmt *Val;
3560  TypeSourceInfo *TInfo;
3561  SourceLocation BuiltinLoc, RParenLoc;
3562public:
3563  VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3564            SourceLocation RPLoc, QualType t)
3565    : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3566           t->isDependentType(), false,
3567           (TInfo->getType()->isInstantiationDependentType() ||
3568            e->isInstantiationDependent()),
3569           (TInfo->getType()->containsUnexpandedParameterPack() ||
3570            e->containsUnexpandedParameterPack())),
3571      Val(e), TInfo(TInfo),
3572      BuiltinLoc(BLoc),
3573      RParenLoc(RPLoc) { }
3574
3575  /// \brief Create an empty __builtin_va_arg expression.
3576  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3577
3578  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3579  Expr *getSubExpr() { return cast<Expr>(Val); }
3580  void setSubExpr(Expr *E) { Val = E; }
3581
3582  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3583  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3584
3585  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3586  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3587
3588  SourceLocation getRParenLoc() const { return RParenLoc; }
3589  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3590
3591  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3592  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3593
3594  static bool classof(const Stmt *T) {
3595    return T->getStmtClass() == VAArgExprClass;
3596  }
3597
3598  // Iterators
3599  child_range children() { return child_range(&Val, &Val+1); }
3600};
3601
3602/// @brief Describes an C or C++ initializer list.
3603///
3604/// InitListExpr describes an initializer list, which can be used to
3605/// initialize objects of different types, including
3606/// struct/class/union types, arrays, and vectors. For example:
3607///
3608/// @code
3609/// struct foo x = { 1, { 2, 3 } };
3610/// @endcode
3611///
3612/// Prior to semantic analysis, an initializer list will represent the
3613/// initializer list as written by the user, but will have the
3614/// placeholder type "void". This initializer list is called the
3615/// syntactic form of the initializer, and may contain C99 designated
3616/// initializers (represented as DesignatedInitExprs), initializations
3617/// of subobject members without explicit braces, and so on. Clients
3618/// interested in the original syntax of the initializer list should
3619/// use the syntactic form of the initializer list.
3620///
3621/// After semantic analysis, the initializer list will represent the
3622/// semantic form of the initializer, where the initializations of all
3623/// subobjects are made explicit with nested InitListExpr nodes and
3624/// C99 designators have been eliminated by placing the designated
3625/// initializations into the subobject they initialize. Additionally,
3626/// any "holes" in the initialization, where no initializer has been
3627/// specified for a particular subobject, will be replaced with
3628/// implicitly-generated ImplicitValueInitExpr expressions that
3629/// value-initialize the subobjects. Note, however, that the
3630/// initializer lists may still have fewer initializers than there are
3631/// elements to initialize within the object.
3632///
3633/// After semantic analysis has completed, given an initializer list,
3634/// method isSemanticForm() returns true if and only if this is the
3635/// semantic form of the initializer list (note: the same AST node
3636/// may at the same time be the syntactic form).
3637/// Given the semantic form of the initializer list, one can retrieve
3638/// the syntactic form of that initializer list (when different)
3639/// using method getSyntacticForm(); the method returns null if applied
3640/// to a initializer list which is already in syntactic form.
3641/// Similarly, given the syntactic form (i.e., an initializer list such
3642/// that isSemanticForm() returns false), one can retrieve the semantic
3643/// form using method getSemanticForm().
3644/// Since many initializer lists have the same syntactic and semantic forms,
3645/// getSyntacticForm() may return NULL, indicating that the current
3646/// semantic initializer list also serves as its syntactic form.
3647class InitListExpr : public Expr {
3648  // FIXME: Eliminate this vector in favor of ASTContext allocation
3649  typedef ASTVector<Stmt *> InitExprsTy;
3650  InitExprsTy InitExprs;
3651  SourceLocation LBraceLoc, RBraceLoc;
3652
3653  /// The alternative form of the initializer list (if it exists).
3654  /// The int part of the pair stores whether this initalizer list is
3655  /// in semantic form. If not null, the pointer points to:
3656  ///   - the syntactic form, if this is in semantic form;
3657  ///   - the semantic form, if this is in syntactic form.
3658  llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3659
3660  /// \brief Either:
3661  ///  If this initializer list initializes an array with more elements than
3662  ///  there are initializers in the list, specifies an expression to be used
3663  ///  for value initialization of the rest of the elements.
3664  /// Or
3665  ///  If this initializer list initializes a union, specifies which
3666  ///  field within the union will be initialized.
3667  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3668
3669public:
3670  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
3671               ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3672
3673  /// \brief Build an empty initializer list.
3674  explicit InitListExpr(EmptyShell Empty)
3675    : Expr(InitListExprClass, Empty) { }
3676
3677  unsigned getNumInits() const { return InitExprs.size(); }
3678
3679  /// \brief Retrieve the set of initializers.
3680  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3681
3682  const Expr *getInit(unsigned Init) const {
3683    assert(Init < getNumInits() && "Initializer access out of range!");
3684    return cast_or_null<Expr>(InitExprs[Init]);
3685  }
3686
3687  Expr *getInit(unsigned Init) {
3688    assert(Init < getNumInits() && "Initializer access out of range!");
3689    return cast_or_null<Expr>(InitExprs[Init]);
3690  }
3691
3692  void setInit(unsigned Init, Expr *expr) {
3693    assert(Init < getNumInits() && "Initializer access out of range!");
3694    InitExprs[Init] = expr;
3695  }
3696
3697  /// \brief Reserve space for some number of initializers.
3698  void reserveInits(ASTContext &C, unsigned NumInits);
3699
3700  /// @brief Specify the number of initializers
3701  ///
3702  /// If there are more than @p NumInits initializers, the remaining
3703  /// initializers will be destroyed. If there are fewer than @p
3704  /// NumInits initializers, NULL expressions will be added for the
3705  /// unknown initializers.
3706  void resizeInits(ASTContext &Context, unsigned NumInits);
3707
3708  /// @brief Updates the initializer at index @p Init with the new
3709  /// expression @p expr, and returns the old expression at that
3710  /// location.
3711  ///
3712  /// When @p Init is out of range for this initializer list, the
3713  /// initializer list will be extended with NULL expressions to
3714  /// accommodate the new entry.
3715  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
3716
3717  /// \brief If this initializer list initializes an array with more elements
3718  /// than there are initializers in the list, specifies an expression to be
3719  /// used for value initialization of the rest of the elements.
3720  Expr *getArrayFiller() {
3721    return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3722  }
3723  const Expr *getArrayFiller() const {
3724    return const_cast<InitListExpr *>(this)->getArrayFiller();
3725  }
3726  void setArrayFiller(Expr *filler);
3727
3728  /// \brief Return true if this is an array initializer and its array "filler"
3729  /// has been set.
3730  bool hasArrayFiller() const { return getArrayFiller(); }
3731
3732  /// \brief If this initializes a union, specifies which field in the
3733  /// union to initialize.
3734  ///
3735  /// Typically, this field is the first named field within the
3736  /// union. However, a designated initializer can specify the
3737  /// initialization of a different field within the union.
3738  FieldDecl *getInitializedFieldInUnion() {
3739    return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3740  }
3741  const FieldDecl *getInitializedFieldInUnion() const {
3742    return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3743  }
3744  void setInitializedFieldInUnion(FieldDecl *FD) {
3745    ArrayFillerOrUnionFieldInit = FD;
3746  }
3747
3748  // Explicit InitListExpr's originate from source code (and have valid source
3749  // locations). Implicit InitListExpr's are created by the semantic analyzer.
3750  bool isExplicit() {
3751    return LBraceLoc.isValid() && RBraceLoc.isValid();
3752  }
3753
3754  // Is this an initializer for an array of characters, initialized by a string
3755  // literal or an @encode?
3756  bool isStringLiteralInit() const;
3757
3758  SourceLocation getLBraceLoc() const { return LBraceLoc; }
3759  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3760  SourceLocation getRBraceLoc() const { return RBraceLoc; }
3761  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3762
3763  bool isSemanticForm() const { return AltForm.getInt(); }
3764  InitListExpr *getSemanticForm() const {
3765    return isSemanticForm() ? 0 : AltForm.getPointer();
3766  }
3767  InitListExpr *getSyntacticForm() const {
3768    return isSemanticForm() ? AltForm.getPointer() : 0;
3769  }
3770
3771  void setSyntacticForm(InitListExpr *Init) {
3772    AltForm.setPointer(Init);
3773    AltForm.setInt(true);
3774    Init->AltForm.setPointer(this);
3775    Init->AltForm.setInt(false);
3776  }
3777
3778  bool hadArrayRangeDesignator() const {
3779    return InitListExprBits.HadArrayRangeDesignator != 0;
3780  }
3781  void sawArrayRangeDesignator(bool ARD = true) {
3782    InitListExprBits.HadArrayRangeDesignator = ARD;
3783  }
3784
3785  bool initializesStdInitializerList() const {
3786    return InitListExprBits.InitializesStdInitializerList != 0;
3787  }
3788  void setInitializesStdInitializerList(bool ISIL = true) {
3789    InitListExprBits.InitializesStdInitializerList = ISIL;
3790  }
3791
3792  SourceLocation getLocStart() const LLVM_READONLY;
3793  SourceLocation getLocEnd() const LLVM_READONLY;
3794
3795  static bool classof(const Stmt *T) {
3796    return T->getStmtClass() == InitListExprClass;
3797  }
3798
3799  // Iterators
3800  child_range children() {
3801    if (InitExprs.empty()) return child_range();
3802    return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3803  }
3804
3805  typedef InitExprsTy::iterator iterator;
3806  typedef InitExprsTy::const_iterator const_iterator;
3807  typedef InitExprsTy::reverse_iterator reverse_iterator;
3808  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3809
3810  iterator begin() { return InitExprs.begin(); }
3811  const_iterator begin() const { return InitExprs.begin(); }
3812  iterator end() { return InitExprs.end(); }
3813  const_iterator end() const { return InitExprs.end(); }
3814  reverse_iterator rbegin() { return InitExprs.rbegin(); }
3815  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3816  reverse_iterator rend() { return InitExprs.rend(); }
3817  const_reverse_iterator rend() const { return InitExprs.rend(); }
3818
3819  friend class ASTStmtReader;
3820  friend class ASTStmtWriter;
3821};
3822
3823/// @brief Represents a C99 designated initializer expression.
3824///
3825/// A designated initializer expression (C99 6.7.8) contains one or
3826/// more designators (which can be field designators, array
3827/// designators, or GNU array-range designators) followed by an
3828/// expression that initializes the field or element(s) that the
3829/// designators refer to. For example, given:
3830///
3831/// @code
3832/// struct point {
3833///   double x;
3834///   double y;
3835/// };
3836/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3837/// @endcode
3838///
3839/// The InitListExpr contains three DesignatedInitExprs, the first of
3840/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3841/// designators, one array designator for @c [2] followed by one field
3842/// designator for @c .y. The initalization expression will be 1.0.
3843class DesignatedInitExpr : public Expr {
3844public:
3845  /// \brief Forward declaration of the Designator class.
3846  class Designator;
3847
3848private:
3849  /// The location of the '=' or ':' prior to the actual initializer
3850  /// expression.
3851  SourceLocation EqualOrColonLoc;
3852
3853  /// Whether this designated initializer used the GNU deprecated
3854  /// syntax rather than the C99 '=' syntax.
3855  bool GNUSyntax : 1;
3856
3857  /// The number of designators in this initializer expression.
3858  unsigned NumDesignators : 15;
3859
3860  /// The number of subexpressions of this initializer expression,
3861  /// which contains both the initializer and any additional
3862  /// expressions used by array and array-range designators.
3863  unsigned NumSubExprs : 16;
3864
3865  /// \brief The designators in this designated initialization
3866  /// expression.
3867  Designator *Designators;
3868
3869
3870  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3871                     const Designator *Designators,
3872                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
3873                     ArrayRef<Expr*> IndexExprs, Expr *Init);
3874
3875  explicit DesignatedInitExpr(unsigned NumSubExprs)
3876    : Expr(DesignatedInitExprClass, EmptyShell()),
3877      NumDesignators(0), NumSubExprs(NumSubExprs), Designators(0) { }
3878
3879public:
3880  /// A field designator, e.g., ".x".
3881  struct FieldDesignator {
3882    /// Refers to the field that is being initialized. The low bit
3883    /// of this field determines whether this is actually a pointer
3884    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3885    /// initially constructed, a field designator will store an
3886    /// IdentifierInfo*. After semantic analysis has resolved that
3887    /// name, the field designator will instead store a FieldDecl*.
3888    uintptr_t NameOrField;
3889
3890    /// The location of the '.' in the designated initializer.
3891    unsigned DotLoc;
3892
3893    /// The location of the field name in the designated initializer.
3894    unsigned FieldLoc;
3895  };
3896
3897  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3898  struct ArrayOrRangeDesignator {
3899    /// Location of the first index expression within the designated
3900    /// initializer expression's list of subexpressions.
3901    unsigned Index;
3902    /// The location of the '[' starting the array range designator.
3903    unsigned LBracketLoc;
3904    /// The location of the ellipsis separating the start and end
3905    /// indices. Only valid for GNU array-range designators.
3906    unsigned EllipsisLoc;
3907    /// The location of the ']' terminating the array range designator.
3908    unsigned RBracketLoc;
3909  };
3910
3911  /// @brief Represents a single C99 designator.
3912  ///
3913  /// @todo This class is infuriatingly similar to clang::Designator,
3914  /// but minor differences (storing indices vs. storing pointers)
3915  /// keep us from reusing it. Try harder, later, to rectify these
3916  /// differences.
3917  class Designator {
3918    /// @brief The kind of designator this describes.
3919    enum {
3920      FieldDesignator,
3921      ArrayDesignator,
3922      ArrayRangeDesignator
3923    } Kind;
3924
3925    union {
3926      /// A field designator, e.g., ".x".
3927      struct FieldDesignator Field;
3928      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3929      struct ArrayOrRangeDesignator ArrayOrRange;
3930    };
3931    friend class DesignatedInitExpr;
3932
3933  public:
3934    Designator() {}
3935
3936    /// @brief Initializes a field designator.
3937    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3938               SourceLocation FieldLoc)
3939      : Kind(FieldDesignator) {
3940      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3941      Field.DotLoc = DotLoc.getRawEncoding();
3942      Field.FieldLoc = FieldLoc.getRawEncoding();
3943    }
3944
3945    /// @brief Initializes an array designator.
3946    Designator(unsigned Index, SourceLocation LBracketLoc,
3947               SourceLocation RBracketLoc)
3948      : Kind(ArrayDesignator) {
3949      ArrayOrRange.Index = Index;
3950      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3951      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3952      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3953    }
3954
3955    /// @brief Initializes a GNU array-range designator.
3956    Designator(unsigned Index, SourceLocation LBracketLoc,
3957               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3958      : Kind(ArrayRangeDesignator) {
3959      ArrayOrRange.Index = Index;
3960      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3961      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3962      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3963    }
3964
3965    bool isFieldDesignator() const { return Kind == FieldDesignator; }
3966    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3967    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3968
3969    IdentifierInfo *getFieldName() const;
3970
3971    FieldDecl *getField() const {
3972      assert(Kind == FieldDesignator && "Only valid on a field designator");
3973      if (Field.NameOrField & 0x01)
3974        return 0;
3975      else
3976        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3977    }
3978
3979    void setField(FieldDecl *FD) {
3980      assert(Kind == FieldDesignator && "Only valid on a field designator");
3981      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3982    }
3983
3984    SourceLocation getDotLoc() const {
3985      assert(Kind == FieldDesignator && "Only valid on a field designator");
3986      return SourceLocation::getFromRawEncoding(Field.DotLoc);
3987    }
3988
3989    SourceLocation getFieldLoc() const {
3990      assert(Kind == FieldDesignator && "Only valid on a field designator");
3991      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3992    }
3993
3994    SourceLocation getLBracketLoc() const {
3995      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3996             "Only valid on an array or array-range designator");
3997      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3998    }
3999
4000    SourceLocation getRBracketLoc() const {
4001      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4002             "Only valid on an array or array-range designator");
4003      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4004    }
4005
4006    SourceLocation getEllipsisLoc() const {
4007      assert(Kind == ArrayRangeDesignator &&
4008             "Only valid on an array-range designator");
4009      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4010    }
4011
4012    unsigned getFirstExprIndex() const {
4013      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4014             "Only valid on an array or array-range designator");
4015      return ArrayOrRange.Index;
4016    }
4017
4018    SourceLocation getLocStart() const LLVM_READONLY {
4019      if (Kind == FieldDesignator)
4020        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4021      else
4022        return getLBracketLoc();
4023    }
4024    SourceLocation getLocEnd() const LLVM_READONLY {
4025      return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4026    }
4027    SourceRange getSourceRange() const LLVM_READONLY {
4028      return SourceRange(getLocStart(), getLocEnd());
4029    }
4030  };
4031
4032  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
4033                                    unsigned NumDesignators,
4034                                    ArrayRef<Expr*> IndexExprs,
4035                                    SourceLocation EqualOrColonLoc,
4036                                    bool GNUSyntax, Expr *Init);
4037
4038  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
4039
4040  /// @brief Returns the number of designators in this initializer.
4041  unsigned size() const { return NumDesignators; }
4042
4043  // Iterator access to the designators.
4044  typedef Designator *designators_iterator;
4045  designators_iterator designators_begin() { return Designators; }
4046  designators_iterator designators_end() {
4047    return Designators + NumDesignators;
4048  }
4049
4050  typedef const Designator *const_designators_iterator;
4051  const_designators_iterator designators_begin() const { return Designators; }
4052  const_designators_iterator designators_end() const {
4053    return Designators + NumDesignators;
4054  }
4055
4056  typedef std::reverse_iterator<designators_iterator>
4057          reverse_designators_iterator;
4058  reverse_designators_iterator designators_rbegin() {
4059    return reverse_designators_iterator(designators_end());
4060  }
4061  reverse_designators_iterator designators_rend() {
4062    return reverse_designators_iterator(designators_begin());
4063  }
4064
4065  typedef std::reverse_iterator<const_designators_iterator>
4066          const_reverse_designators_iterator;
4067  const_reverse_designators_iterator designators_rbegin() const {
4068    return const_reverse_designators_iterator(designators_end());
4069  }
4070  const_reverse_designators_iterator designators_rend() const {
4071    return const_reverse_designators_iterator(designators_begin());
4072  }
4073
4074  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4075
4076  void setDesignators(ASTContext &C, const Designator *Desigs,
4077                      unsigned NumDesigs);
4078
4079  Expr *getArrayIndex(const Designator &D) const;
4080  Expr *getArrayRangeStart(const Designator &D) const;
4081  Expr *getArrayRangeEnd(const Designator &D) const;
4082
4083  /// @brief Retrieve the location of the '=' that precedes the
4084  /// initializer value itself, if present.
4085  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4086  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4087
4088  /// @brief Determines whether this designated initializer used the
4089  /// deprecated GNU syntax for designated initializers.
4090  bool usesGNUSyntax() const { return GNUSyntax; }
4091  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4092
4093  /// @brief Retrieve the initializer value.
4094  Expr *getInit() const {
4095    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4096  }
4097
4098  void setInit(Expr *init) {
4099    *child_begin() = init;
4100  }
4101
4102  /// \brief Retrieve the total number of subexpressions in this
4103  /// designated initializer expression, including the actual
4104  /// initialized value and any expressions that occur within array
4105  /// and array-range designators.
4106  unsigned getNumSubExprs() const { return NumSubExprs; }
4107
4108  Expr *getSubExpr(unsigned Idx) {
4109    assert(Idx < NumSubExprs && "Subscript out of range");
4110    char* Ptr = static_cast<char*>(static_cast<void *>(this));
4111    Ptr += sizeof(DesignatedInitExpr);
4112    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
4113  }
4114
4115  void setSubExpr(unsigned Idx, Expr *E) {
4116    assert(Idx < NumSubExprs && "Subscript out of range");
4117    char* Ptr = static_cast<char*>(static_cast<void *>(this));
4118    Ptr += sizeof(DesignatedInitExpr);
4119    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
4120  }
4121
4122  /// \brief Replaces the designator at index @p Idx with the series
4123  /// of designators in [First, Last).
4124  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
4125                        const Designator *Last);
4126
4127  SourceRange getDesignatorsSourceRange() const;
4128
4129  SourceLocation getLocStart() const LLVM_READONLY;
4130  SourceLocation getLocEnd() const LLVM_READONLY;
4131
4132  static bool classof(const Stmt *T) {
4133    return T->getStmtClass() == DesignatedInitExprClass;
4134  }
4135
4136  // Iterators
4137  child_range children() {
4138    Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4139    return child_range(begin, begin + NumSubExprs);
4140  }
4141};
4142
4143/// \brief Represents an implicitly-generated value initialization of
4144/// an object of a given type.
4145///
4146/// Implicit value initializations occur within semantic initializer
4147/// list expressions (InitListExpr) as placeholders for subobject
4148/// initializations not explicitly specified by the user.
4149///
4150/// \see InitListExpr
4151class ImplicitValueInitExpr : public Expr {
4152public:
4153  explicit ImplicitValueInitExpr(QualType ty)
4154    : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4155           false, false, ty->isInstantiationDependentType(), false) { }
4156
4157  /// \brief Construct an empty implicit value initialization.
4158  explicit ImplicitValueInitExpr(EmptyShell Empty)
4159    : Expr(ImplicitValueInitExprClass, Empty) { }
4160
4161  static bool classof(const Stmt *T) {
4162    return T->getStmtClass() == ImplicitValueInitExprClass;
4163  }
4164
4165  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4166  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4167
4168  // Iterators
4169  child_range children() { return child_range(); }
4170};
4171
4172
4173class ParenListExpr : public Expr {
4174  Stmt **Exprs;
4175  unsigned NumExprs;
4176  SourceLocation LParenLoc, RParenLoc;
4177
4178public:
4179  ParenListExpr(ASTContext& C, SourceLocation lparenloc, ArrayRef<Expr*> exprs,
4180                SourceLocation rparenloc);
4181
4182  /// \brief Build an empty paren list.
4183  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4184
4185  unsigned getNumExprs() const { return NumExprs; }
4186
4187  const Expr* getExpr(unsigned Init) const {
4188    assert(Init < getNumExprs() && "Initializer access out of range!");
4189    return cast_or_null<Expr>(Exprs[Init]);
4190  }
4191
4192  Expr* getExpr(unsigned Init) {
4193    assert(Init < getNumExprs() && "Initializer access out of range!");
4194    return cast_or_null<Expr>(Exprs[Init]);
4195  }
4196
4197  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4198
4199  SourceLocation getLParenLoc() const { return LParenLoc; }
4200  SourceLocation getRParenLoc() const { return RParenLoc; }
4201
4202  SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4203  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4204
4205  static bool classof(const Stmt *T) {
4206    return T->getStmtClass() == ParenListExprClass;
4207  }
4208
4209  // Iterators
4210  child_range children() {
4211    return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4212  }
4213
4214  friend class ASTStmtReader;
4215  friend class ASTStmtWriter;
4216};
4217
4218
4219/// \brief Represents a C11 generic selection.
4220///
4221/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4222/// expression, followed by one or more generic associations.  Each generic
4223/// association specifies a type name and an expression, or "default" and an
4224/// expression (in which case it is known as a default generic association).
4225/// The type and value of the generic selection are identical to those of its
4226/// result expression, which is defined as the expression in the generic
4227/// association with a type name that is compatible with the type of the
4228/// controlling expression, or the expression in the default generic association
4229/// if no types are compatible.  For example:
4230///
4231/// @code
4232/// _Generic(X, double: 1, float: 2, default: 3)
4233/// @endcode
4234///
4235/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4236/// or 3 if "hello".
4237///
4238/// As an extension, generic selections are allowed in C++, where the following
4239/// additional semantics apply:
4240///
4241/// Any generic selection whose controlling expression is type-dependent or
4242/// which names a dependent type in its association list is result-dependent,
4243/// which means that the choice of result expression is dependent.
4244/// Result-dependent generic associations are both type- and value-dependent.
4245class GenericSelectionExpr : public Expr {
4246  enum { CONTROLLING, END_EXPR };
4247  TypeSourceInfo **AssocTypes;
4248  Stmt **SubExprs;
4249  unsigned NumAssocs, ResultIndex;
4250  SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4251
4252public:
4253  GenericSelectionExpr(ASTContext &Context,
4254                       SourceLocation GenericLoc, Expr *ControllingExpr,
4255                       ArrayRef<TypeSourceInfo*> AssocTypes,
4256                       ArrayRef<Expr*> AssocExprs,
4257                       SourceLocation DefaultLoc, SourceLocation RParenLoc,
4258                       bool ContainsUnexpandedParameterPack,
4259                       unsigned ResultIndex);
4260
4261  /// This constructor is used in the result-dependent case.
4262  GenericSelectionExpr(ASTContext &Context,
4263                       SourceLocation GenericLoc, Expr *ControllingExpr,
4264                       ArrayRef<TypeSourceInfo*> AssocTypes,
4265                       ArrayRef<Expr*> AssocExprs,
4266                       SourceLocation DefaultLoc, SourceLocation RParenLoc,
4267                       bool ContainsUnexpandedParameterPack);
4268
4269  explicit GenericSelectionExpr(EmptyShell Empty)
4270    : Expr(GenericSelectionExprClass, Empty) { }
4271
4272  unsigned getNumAssocs() const { return NumAssocs; }
4273
4274  SourceLocation getGenericLoc() const { return GenericLoc; }
4275  SourceLocation getDefaultLoc() const { return DefaultLoc; }
4276  SourceLocation getRParenLoc() const { return RParenLoc; }
4277
4278  const Expr *getAssocExpr(unsigned i) const {
4279    return cast<Expr>(SubExprs[END_EXPR+i]);
4280  }
4281  Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4282
4283  const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4284    return AssocTypes[i];
4285  }
4286  TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4287
4288  QualType getAssocType(unsigned i) const {
4289    if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4290      return TS->getType();
4291    else
4292      return QualType();
4293  }
4294
4295  const Expr *getControllingExpr() const {
4296    return cast<Expr>(SubExprs[CONTROLLING]);
4297  }
4298  Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4299
4300  /// Whether this generic selection is result-dependent.
4301  bool isResultDependent() const { return ResultIndex == -1U; }
4302
4303  /// The zero-based index of the result expression's generic association in
4304  /// the generic selection's association list.  Defined only if the
4305  /// generic selection is not result-dependent.
4306  unsigned getResultIndex() const {
4307    assert(!isResultDependent() && "Generic selection is result-dependent");
4308    return ResultIndex;
4309  }
4310
4311  /// The generic selection's result expression.  Defined only if the
4312  /// generic selection is not result-dependent.
4313  const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4314  Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4315
4316  SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4317  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4318
4319  static bool classof(const Stmt *T) {
4320    return T->getStmtClass() == GenericSelectionExprClass;
4321  }
4322
4323  child_range children() {
4324    return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4325  }
4326
4327  friend class ASTStmtReader;
4328};
4329
4330//===----------------------------------------------------------------------===//
4331// Clang Extensions
4332//===----------------------------------------------------------------------===//
4333
4334
4335/// ExtVectorElementExpr - This represents access to specific elements of a
4336/// vector, and may occur on the left hand side or right hand side.  For example
4337/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
4338///
4339/// Note that the base may have either vector or pointer to vector type, just
4340/// like a struct field reference.
4341///
4342class ExtVectorElementExpr : public Expr {
4343  Stmt *Base;
4344  IdentifierInfo *Accessor;
4345  SourceLocation AccessorLoc;
4346public:
4347  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4348                       IdentifierInfo &accessor, SourceLocation loc)
4349    : Expr(ExtVectorElementExprClass, ty, VK,
4350           (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4351           base->isTypeDependent(), base->isValueDependent(),
4352           base->isInstantiationDependent(),
4353           base->containsUnexpandedParameterPack()),
4354      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4355
4356  /// \brief Build an empty vector element expression.
4357  explicit ExtVectorElementExpr(EmptyShell Empty)
4358    : Expr(ExtVectorElementExprClass, Empty) { }
4359
4360  const Expr *getBase() const { return cast<Expr>(Base); }
4361  Expr *getBase() { return cast<Expr>(Base); }
4362  void setBase(Expr *E) { Base = E; }
4363
4364  IdentifierInfo &getAccessor() const { return *Accessor; }
4365  void setAccessor(IdentifierInfo *II) { Accessor = II; }
4366
4367  SourceLocation getAccessorLoc() const { return AccessorLoc; }
4368  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4369
4370  /// getNumElements - Get the number of components being selected.
4371  unsigned getNumElements() const;
4372
4373  /// containsDuplicateElements - Return true if any element access is
4374  /// repeated.
4375  bool containsDuplicateElements() const;
4376
4377  /// getEncodedElementAccess - Encode the elements accessed into an llvm
4378  /// aggregate Constant of ConstantInt(s).
4379  void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4380
4381  SourceLocation getLocStart() const LLVM_READONLY {
4382    return getBase()->getLocStart();
4383  }
4384  SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4385
4386  /// isArrow - Return true if the base expression is a pointer to vector,
4387  /// return false if the base expression is a vector.
4388  bool isArrow() const;
4389
4390  static bool classof(const Stmt *T) {
4391    return T->getStmtClass() == ExtVectorElementExprClass;
4392  }
4393
4394  // Iterators
4395  child_range children() { return child_range(&Base, &Base+1); }
4396};
4397
4398
4399/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4400/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
4401class BlockExpr : public Expr {
4402protected:
4403  BlockDecl *TheBlock;
4404public:
4405  BlockExpr(BlockDecl *BD, QualType ty)
4406    : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4407           ty->isDependentType(), ty->isDependentType(),
4408           ty->isInstantiationDependentType() || BD->isDependentContext(),
4409           false),
4410      TheBlock(BD) {}
4411
4412  /// \brief Build an empty block expression.
4413  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4414
4415  const BlockDecl *getBlockDecl() const { return TheBlock; }
4416  BlockDecl *getBlockDecl() { return TheBlock; }
4417  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4418
4419  // Convenience functions for probing the underlying BlockDecl.
4420  SourceLocation getCaretLocation() const;
4421  const Stmt *getBody() const;
4422  Stmt *getBody();
4423
4424  SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4425  SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4426
4427  /// getFunctionType - Return the underlying function type for this block.
4428  const FunctionProtoType *getFunctionType() const;
4429
4430  static bool classof(const Stmt *T) {
4431    return T->getStmtClass() == BlockExprClass;
4432  }
4433
4434  // Iterators
4435  child_range children() { return child_range(); }
4436};
4437
4438/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4439/// This AST node provides support for reinterpreting a type to another
4440/// type of the same size.
4441class AsTypeExpr : public Expr { // Should this be an ExplicitCastExpr?
4442private:
4443  Stmt *SrcExpr;
4444  SourceLocation BuiltinLoc, RParenLoc;
4445
4446  friend class ASTReader;
4447  friend class ASTStmtReader;
4448  explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4449
4450public:
4451  AsTypeExpr(Expr* SrcExpr, QualType DstType,
4452             ExprValueKind VK, ExprObjectKind OK,
4453             SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4454    : Expr(AsTypeExprClass, DstType, VK, OK,
4455           DstType->isDependentType(),
4456           DstType->isDependentType() || SrcExpr->isValueDependent(),
4457           (DstType->isInstantiationDependentType() ||
4458            SrcExpr->isInstantiationDependent()),
4459           (DstType->containsUnexpandedParameterPack() ||
4460            SrcExpr->containsUnexpandedParameterPack())),
4461  SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4462
4463  /// getSrcExpr - Return the Expr to be converted.
4464  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4465
4466  /// getBuiltinLoc - Return the location of the __builtin_astype token.
4467  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4468
4469  /// getRParenLoc - Return the location of final right parenthesis.
4470  SourceLocation getRParenLoc() const { return RParenLoc; }
4471
4472  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4473  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4474
4475  static bool classof(const Stmt *T) {
4476    return T->getStmtClass() == AsTypeExprClass;
4477  }
4478
4479  // Iterators
4480  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4481};
4482
4483/// PseudoObjectExpr - An expression which accesses a pseudo-object
4484/// l-value.  A pseudo-object is an abstract object, accesses to which
4485/// are translated to calls.  The pseudo-object expression has a
4486/// syntactic form, which shows how the expression was actually
4487/// written in the source code, and a semantic form, which is a series
4488/// of expressions to be executed in order which detail how the
4489/// operation is actually evaluated.  Optionally, one of the semantic
4490/// forms may also provide a result value for the expression.
4491///
4492/// If any of the semantic-form expressions is an OpaqueValueExpr,
4493/// that OVE is required to have a source expression, and it is bound
4494/// to the result of that source expression.  Such OVEs may appear
4495/// only in subsequent semantic-form expressions and as
4496/// sub-expressions of the syntactic form.
4497///
4498/// PseudoObjectExpr should be used only when an operation can be
4499/// usefully described in terms of fairly simple rewrite rules on
4500/// objects and functions that are meant to be used by end-developers.
4501/// For example, under the Itanium ABI, dynamic casts are implemented
4502/// as a call to a runtime function called __dynamic_cast; using this
4503/// class to describe that would be inappropriate because that call is
4504/// not really part of the user-visible semantics, and instead the
4505/// cast is properly reflected in the AST and IR-generation has been
4506/// taught to generate the call as necessary.  In contrast, an
4507/// Objective-C property access is semantically defined to be
4508/// equivalent to a particular message send, and this is very much
4509/// part of the user model.  The name of this class encourages this
4510/// modelling design.
4511class PseudoObjectExpr : public Expr {
4512  // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4513  // Always at least two, because the first sub-expression is the
4514  // syntactic form.
4515
4516  // PseudoObjectExprBits.ResultIndex - The index of the
4517  // sub-expression holding the result.  0 means the result is void,
4518  // which is unambiguous because it's the index of the syntactic
4519  // form.  Note that this is therefore 1 higher than the value passed
4520  // in to Create, which is an index within the semantic forms.
4521  // Note also that ASTStmtWriter assumes this encoding.
4522
4523  Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
4524  const Expr * const *getSubExprsBuffer() const {
4525    return reinterpret_cast<const Expr * const *>(this + 1);
4526  }
4527
4528  friend class ASTStmtReader;
4529
4530  PseudoObjectExpr(QualType type, ExprValueKind VK,
4531                   Expr *syntactic, ArrayRef<Expr*> semantic,
4532                   unsigned resultIndex);
4533
4534  PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4535
4536  unsigned getNumSubExprs() const {
4537    return PseudoObjectExprBits.NumSubExprs;
4538  }
4539
4540public:
4541  /// NoResult - A value for the result index indicating that there is
4542  /// no semantic result.
4543  enum { NoResult = ~0U };
4544
4545  static PseudoObjectExpr *Create(ASTContext &Context, Expr *syntactic,
4546                                  ArrayRef<Expr*> semantic,
4547                                  unsigned resultIndex);
4548
4549  static PseudoObjectExpr *Create(ASTContext &Context, EmptyShell shell,
4550                                  unsigned numSemanticExprs);
4551
4552  /// Return the syntactic form of this expression, i.e. the
4553  /// expression it actually looks like.  Likely to be expressed in
4554  /// terms of OpaqueValueExprs bound in the semantic form.
4555  Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4556  const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4557
4558  /// Return the index of the result-bearing expression into the semantics
4559  /// expressions, or PseudoObjectExpr::NoResult if there is none.
4560  unsigned getResultExprIndex() const {
4561    if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4562    return PseudoObjectExprBits.ResultIndex - 1;
4563  }
4564
4565  /// Return the result-bearing expression, or null if there is none.
4566  Expr *getResultExpr() {
4567    if (PseudoObjectExprBits.ResultIndex == 0)
4568      return 0;
4569    return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4570  }
4571  const Expr *getResultExpr() const {
4572    return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4573  }
4574
4575  unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4576
4577  typedef Expr * const *semantics_iterator;
4578  typedef const Expr * const *const_semantics_iterator;
4579  semantics_iterator semantics_begin() {
4580    return getSubExprsBuffer() + 1;
4581  }
4582  const_semantics_iterator semantics_begin() const {
4583    return getSubExprsBuffer() + 1;
4584  }
4585  semantics_iterator semantics_end() {
4586    return getSubExprsBuffer() + getNumSubExprs();
4587  }
4588  const_semantics_iterator semantics_end() const {
4589    return getSubExprsBuffer() + getNumSubExprs();
4590  }
4591  Expr *getSemanticExpr(unsigned index) {
4592    assert(index + 1 < getNumSubExprs());
4593    return getSubExprsBuffer()[index + 1];
4594  }
4595  const Expr *getSemanticExpr(unsigned index) const {
4596    return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4597  }
4598
4599  SourceLocation getExprLoc() const LLVM_READONLY {
4600    return getSyntacticForm()->getExprLoc();
4601  }
4602
4603  SourceLocation getLocStart() const LLVM_READONLY {
4604    return getSyntacticForm()->getLocStart();
4605  }
4606  SourceLocation getLocEnd() const LLVM_READONLY {
4607    return getSyntacticForm()->getLocEnd();
4608  }
4609
4610  child_range children() {
4611    Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4612    return child_range(cs, cs + getNumSubExprs());
4613  }
4614
4615  static bool classof(const Stmt *T) {
4616    return T->getStmtClass() == PseudoObjectExprClass;
4617  }
4618};
4619
4620/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4621/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4622/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4623/// All of these instructions take one primary pointer and at least one memory
4624/// order.
4625class AtomicExpr : public Expr {
4626public:
4627  enum AtomicOp {
4628#define BUILTIN(ID, TYPE, ATTRS)
4629#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4630#include "clang/Basic/Builtins.def"
4631    // Avoid trailing comma
4632    BI_First = 0
4633  };
4634
4635private:
4636  enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4637  Stmt* SubExprs[END_EXPR];
4638  unsigned NumSubExprs;
4639  SourceLocation BuiltinLoc, RParenLoc;
4640  AtomicOp Op;
4641
4642  friend class ASTStmtReader;
4643
4644public:
4645  AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4646             AtomicOp op, SourceLocation RP);
4647
4648  /// \brief Determine the number of arguments the specified atomic builtin
4649  /// should have.
4650  static unsigned getNumSubExprs(AtomicOp Op);
4651
4652  /// \brief Build an empty AtomicExpr.
4653  explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4654
4655  Expr *getPtr() const {
4656    return cast<Expr>(SubExprs[PTR]);
4657  }
4658  Expr *getOrder() const {
4659    return cast<Expr>(SubExprs[ORDER]);
4660  }
4661  Expr *getVal1() const {
4662    if (Op == AO__c11_atomic_init)
4663      return cast<Expr>(SubExprs[ORDER]);
4664    assert(NumSubExprs > VAL1);
4665    return cast<Expr>(SubExprs[VAL1]);
4666  }
4667  Expr *getOrderFail() const {
4668    assert(NumSubExprs > ORDER_FAIL);
4669    return cast<Expr>(SubExprs[ORDER_FAIL]);
4670  }
4671  Expr *getVal2() const {
4672    if (Op == AO__atomic_exchange)
4673      return cast<Expr>(SubExprs[ORDER_FAIL]);
4674    assert(NumSubExprs > VAL2);
4675    return cast<Expr>(SubExprs[VAL2]);
4676  }
4677  Expr *getWeak() const {
4678    assert(NumSubExprs > WEAK);
4679    return cast<Expr>(SubExprs[WEAK]);
4680  }
4681
4682  AtomicOp getOp() const { return Op; }
4683  unsigned getNumSubExprs() { return NumSubExprs; }
4684
4685  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4686
4687  bool isVolatile() const {
4688    return getPtr()->getType()->getPointeeType().isVolatileQualified();
4689  }
4690
4691  bool isCmpXChg() const {
4692    return getOp() == AO__c11_atomic_compare_exchange_strong ||
4693           getOp() == AO__c11_atomic_compare_exchange_weak ||
4694           getOp() == AO__atomic_compare_exchange ||
4695           getOp() == AO__atomic_compare_exchange_n;
4696  }
4697
4698  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4699  SourceLocation getRParenLoc() const { return RParenLoc; }
4700
4701  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4702  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4703
4704  static bool classof(const Stmt *T) {
4705    return T->getStmtClass() == AtomicExprClass;
4706  }
4707
4708  // Iterators
4709  child_range children() {
4710    return child_range(SubExprs, SubExprs+NumSubExprs);
4711  }
4712};
4713}  // end namespace clang
4714
4715#endif
4716