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