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