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