Expr.h revision 2de56d1d0c3a504ad1529de2677628bdfbb95cd4
1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Expr interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPR_H
15#define LLVM_CLANG_AST_EXPR_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/Stmt.h"
19#include "clang/AST/Type.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/OperationKinds.h"
22#include "clang/AST/ASTVector.h"
23#include "clang/AST/UsuallyTinyPtrVector.h"
24#include "llvm/ADT/APSInt.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include <vector>
29
30namespace clang {
31  class ASTContext;
32  class APValue;
33  class Decl;
34  class IdentifierInfo;
35  class ParmVarDecl;
36  class NamedDecl;
37  class ValueDecl;
38  class BlockDecl;
39  class CXXBaseSpecifier;
40  class CXXOperatorCallExpr;
41  class CXXMemberCallExpr;
42  class TemplateArgumentLoc;
43  class TemplateArgumentListInfo;
44
45/// \brief A simple array of base specifiers.
46typedef llvm::SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
47
48/// Expr - This represents one expression.  Note that Expr's are subclasses of
49/// Stmt.  This allows an expression to be transparently used any place a Stmt
50/// is required.
51///
52class Expr : public Stmt {
53  QualType TR;
54
55  virtual void ANCHOR(); // key function.
56protected:
57  /// TypeDependent - Whether this expression is type-dependent
58  /// (C++ [temp.dep.expr]).
59  bool TypeDependent : 1;
60
61  /// ValueDependent - Whether this expression is value-dependent
62  /// (C++ [temp.dep.constexpr]).
63  bool ValueDependent : 1;
64
65  /// ValueKind - The value classification of this expression.
66  /// Only actually used by certain subclasses.
67  unsigned ValueKind : 2;
68
69  enum { BitsRemaining = 28 };
70
71  Expr(StmtClass SC, QualType T, bool TD, bool VD)
72    : Stmt(SC), TypeDependent(TD), ValueDependent(VD), ValueKind(0) {
73    setType(T);
74  }
75
76  /// \brief Construct an empty expression.
77  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
78
79public:
80  /// \brief Increases the reference count for this expression.
81  ///
82  /// Invoke the Retain() operation when this expression
83  /// is being shared by another owner.
84  Expr *Retain() {
85    Stmt::Retain();
86    return this;
87  }
88
89  QualType getType() const { return TR; }
90  void setType(QualType t) {
91    // In C++, the type of an expression is always adjusted so that it
92    // will not have reference type an expression will never have
93    // reference type (C++ [expr]p6). Use
94    // QualType::getNonReferenceType() to retrieve the non-reference
95    // type. Additionally, inspect Expr::isLvalue to determine whether
96    // an expression that is adjusted in this manner should be
97    // considered an lvalue.
98    assert((t.isNull() || !t->isReferenceType()) &&
99           "Expressions can't have reference type");
100
101    TR = t;
102  }
103
104  /// isValueDependent - Determines whether this expression is
105  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
106  /// array bound of "Chars" in the following example is
107  /// value-dependent.
108  /// @code
109  /// template<int Size, char (&Chars)[Size]> struct meta_string;
110  /// @endcode
111  bool isValueDependent() const { return ValueDependent; }
112
113  /// \brief Set whether this expression is value-dependent or not.
114  void setValueDependent(bool VD) { ValueDependent = VD; }
115
116  /// isTypeDependent - Determines whether this expression is
117  /// type-dependent (C++ [temp.dep.expr]), which means that its type
118  /// could change from one template instantiation to the next. For
119  /// example, the expressions "x" and "x + y" are type-dependent in
120  /// the following code, but "y" is not type-dependent:
121  /// @code
122  /// template<typename T>
123  /// void add(T x, int y) {
124  ///   x + y;
125  /// }
126  /// @endcode
127  bool isTypeDependent() const { return TypeDependent; }
128
129  /// \brief Set whether this expression is type-dependent or not.
130  void setTypeDependent(bool TD) { TypeDependent = TD; }
131
132  /// SourceLocation tokens are not useful in isolation - they are low level
133  /// value objects created/interpreted by SourceManager. We assume AST
134  /// clients will have a pointer to the respective SourceManager.
135  virtual SourceRange getSourceRange() const = 0;
136
137  /// getExprLoc - Return the preferred location for the arrow when diagnosing
138  /// a problem with a generic expression.
139  virtual SourceLocation getExprLoc() const { return getLocStart(); }
140
141  /// isUnusedResultAWarning - Return true if this immediate expression should
142  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
143  /// with location to warn on and the source range[s] to report with the
144  /// warning.
145  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
146                              SourceRange &R2, ASTContext &Ctx) const;
147
148  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
149  /// incomplete type other than void. Nonarray expressions that can be lvalues:
150  ///  - name, where name must be a variable
151  ///  - e[i]
152  ///  - (e), where e must be an lvalue
153  ///  - e.name, where e must be an lvalue
154  ///  - e->name
155  ///  - *e, the type of e cannot be a function type
156  ///  - string-constant
157  ///  - reference type [C++ [expr]]
158  ///  - b ? x : y, where x and y are lvalues of suitable types [C++]
159  ///
160  enum isLvalueResult {
161    LV_Valid,
162    LV_NotObjectType,
163    LV_IncompleteVoidType,
164    LV_DuplicateVectorComponents,
165    LV_InvalidExpression,
166    LV_MemberFunction,
167    LV_SubObjCPropertySetting,
168    LV_ClassTemporary
169  };
170  isLvalueResult isLvalue(ASTContext &Ctx) const;
171
172  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
173  /// does not have an incomplete type, does not have a const-qualified type,
174  /// and if it is a structure or union, does not have any member (including,
175  /// recursively, any member or element of all contained aggregates or unions)
176  /// with a const-qualified type.
177  ///
178  /// \param Loc [in] [out] - A source location which *may* be filled
179  /// in with the location of the expression making this a
180  /// non-modifiable lvalue, if specified.
181  enum isModifiableLvalueResult {
182    MLV_Valid,
183    MLV_NotObjectType,
184    MLV_IncompleteVoidType,
185    MLV_DuplicateVectorComponents,
186    MLV_InvalidExpression,
187    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
188    MLV_IncompleteType,
189    MLV_ConstQualified,
190    MLV_ArrayType,
191    MLV_NotBlockQualified,
192    MLV_ReadonlyProperty,
193    MLV_NoSetterProperty,
194    MLV_MemberFunction,
195    MLV_SubObjCPropertySetting,
196    MLV_ClassTemporary
197  };
198  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
199                                              SourceLocation *Loc = 0) const;
200
201  /// \brief The return type of classify(). Represents the C++0x expression
202  ///        taxonomy.
203  class Classification {
204  public:
205    /// \brief The various classification results. Most of these mean prvalue.
206    enum Kinds {
207      CL_LValue,
208      CL_XValue,
209      CL_Function, // Functions cannot be lvalues in C.
210      CL_Void, // Void cannot be an lvalue in C.
211      CL_DuplicateVectorComponents, // A vector shuffle with dupes.
212      CL_MemberFunction, // An expression referring to a member function
213      CL_SubObjCPropertySetting,
214      CL_ClassTemporary, // A prvalue of class type
215      CL_PRValue // A prvalue for any other reason, of any other type
216    };
217    /// \brief The results of modification testing.
218    enum ModifiableType {
219      CM_Untested, // testModifiable was false.
220      CM_Modifiable,
221      CM_RValue, // Not modifiable because it's an rvalue
222      CM_Function, // Not modifiable because it's a function; C++ only
223      CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
224      CM_NotBlockQualified, // Not captured in the closure
225      CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
226      CM_ConstQualified,
227      CM_ArrayType,
228      CM_IncompleteType
229    };
230
231  private:
232    friend class Expr;
233
234    unsigned short Kind;
235    unsigned short Modifiable;
236
237    explicit Classification(Kinds k, ModifiableType m)
238      : Kind(k), Modifiable(m)
239    {}
240
241  public:
242    Classification() {}
243
244    Kinds getKind() const { return static_cast<Kinds>(Kind); }
245    ModifiableType getModifiable() const {
246      assert(Modifiable != CM_Untested && "Did not test for modifiability.");
247      return static_cast<ModifiableType>(Modifiable);
248    }
249    bool isLValue() const { return Kind == CL_LValue; }
250    bool isXValue() const { return Kind == CL_XValue; }
251    bool isGLValue() const { return Kind <= CL_XValue; }
252    bool isPRValue() const { return Kind >= CL_Function; }
253    bool isRValue() const { return Kind >= CL_XValue; }
254    bool isModifiable() const { return getModifiable() == CM_Modifiable; }
255  };
256  /// \brief classify - Classify this expression according to the C++0x
257  ///        expression taxonomy.
258  ///
259  /// C++0x defines ([basic.lval]) a new taxonomy of expressions to replace the
260  /// old lvalue vs rvalue. This function determines the type of expression this
261  /// is. There are three expression types:
262  /// - lvalues are classical lvalues as in C++03.
263  /// - prvalues are equivalent to rvalues in C++03.
264  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
265  ///   function returning an rvalue reference.
266  /// lvalues and xvalues are collectively referred to as glvalues, while
267  /// prvalues and xvalues together form rvalues.
268  Classification Classify(ASTContext &Ctx) const {
269    return ClassifyImpl(Ctx, 0);
270  }
271
272  /// \brief classifyModifiable - Classify this expression according to the
273  ///        C++0x expression taxonomy, and see if it is valid on the left side
274  ///        of an assignment.
275  ///
276  /// This function extends classify in that it also tests whether the
277  /// expression is modifiable (C99 6.3.2.1p1).
278  /// \param Loc A source location that might be filled with a relevant location
279  ///            if the expression is not modifiable.
280  Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
281    return ClassifyImpl(Ctx, &Loc);
282  }
283
284private:
285  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
286
287public:
288
289  /// \brief If this expression refers to a bit-field, retrieve the
290  /// declaration of that bit-field.
291  FieldDecl *getBitField();
292
293  const FieldDecl *getBitField() const {
294    return const_cast<Expr*>(this)->getBitField();
295  }
296
297  /// \brief Returns whether this expression refers to a vector element.
298  bool refersToVectorElement() const;
299
300  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
301  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
302  /// but also int expressions which are produced by things like comparisons in
303  /// C.
304  bool isKnownToHaveBooleanValue() const;
305
306  /// isIntegerConstantExpr - Return true if this expression is a valid integer
307  /// constant expression, and, if so, return its value in Result.  If not a
308  /// valid i-c-e, return false and fill in Loc (if specified) with the location
309  /// of the invalid expression.
310  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
311                             SourceLocation *Loc = 0,
312                             bool isEvaluated = true) const;
313  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
314    llvm::APSInt X;
315    return isIntegerConstantExpr(X, Ctx, Loc);
316  }
317  /// isConstantInitializer - Returns true if this expression is a constant
318  /// initializer, which can be emitted at compile-time.
319  bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
320
321  /// EvalResult is a struct with detailed info about an evaluated expression.
322  struct EvalResult {
323    /// Val - This is the value the expression can be folded to.
324    APValue Val;
325
326    /// HasSideEffects - Whether the evaluated expression has side effects.
327    /// For example, (f() && 0) can be folded, but it still has side effects.
328    bool HasSideEffects;
329
330    /// Diag - If the expression is unfoldable, then Diag contains a note
331    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
332    /// position for the error, and DiagExpr is the expression that caused
333    /// the error.
334    /// If the expression is foldable, but not an integer constant expression,
335    /// Diag contains a note diagnostic that describes why it isn't an integer
336    /// constant expression. If the expression *is* an integer constant
337    /// expression, then Diag will be zero.
338    unsigned Diag;
339    const Expr *DiagExpr;
340    SourceLocation DiagLoc;
341
342    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
343
344    // isGlobalLValue - Return true if the evaluated lvalue expression
345    // is global.
346    bool isGlobalLValue() const;
347    // hasSideEffects - Return true if the evaluated expression has
348    // side effects.
349    bool hasSideEffects() const {
350      return HasSideEffects;
351    }
352  };
353
354  /// Evaluate - Return true if this is a constant which we can fold using
355  /// any crazy technique (that has nothing to do with language standards) that
356  /// we want to.  If this function returns true, it returns the folded constant
357  /// in Result.
358  bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
359
360  /// EvaluateAsBooleanCondition - Return true if this is a constant
361  /// which we we can fold and convert to a boolean condition using
362  /// any crazy technique that we want to.
363  bool EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const;
364
365  /// isEvaluatable - Call Evaluate to see if this expression can be constant
366  /// folded, but discard the result.
367  bool isEvaluatable(ASTContext &Ctx) const;
368
369  /// HasSideEffects - This routine returns true for all those expressions
370  /// which must be evaluated each time and must not be optimization away
371  /// or evaluated at compile time. Example is a function call, volatile
372  /// variable read.
373  bool HasSideEffects(ASTContext &Ctx) const;
374
375  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
376  /// must be called on an expression that constant folds to an integer.
377  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
378
379  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
380  /// with link time known address.
381  bool EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const;
382
383  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue.
384  bool EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const;
385
386  /// \brief Enumeration used to describe how \c isNullPointerConstant()
387  /// should cope with value-dependent expressions.
388  enum NullPointerConstantValueDependence {
389    /// \brief Specifies that the expression should never be value-dependent.
390    NPC_NeverValueDependent = 0,
391
392    /// \brief Specifies that a value-dependent expression of integral or
393    /// dependent type should be considered a null pointer constant.
394    NPC_ValueDependentIsNull,
395
396    /// \brief Specifies that a value-dependent expression should be considered
397    /// to never be a null pointer constant.
398    NPC_ValueDependentIsNotNull
399  };
400
401  /// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
402  /// integer constant expression with the value zero, or if this is one that is
403  /// cast to void*.
404  bool isNullPointerConstant(ASTContext &Ctx,
405                             NullPointerConstantValueDependence NPC) const;
406
407  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
408  /// write barrier.
409  bool isOBJCGCCandidate(ASTContext &Ctx) const;
410
411  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
412  ///  its subexpression.  If that subexpression is also a ParenExpr,
413  ///  then this method recursively returns its subexpression, and so forth.
414  ///  Otherwise, the method returns the current Expr.
415  Expr *IgnoreParens();
416
417  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
418  /// or CastExprs, returning their operand.
419  Expr *IgnoreParenCasts();
420
421  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip off any
422  /// ParenExpr or ImplicitCastExprs, returning their operand.
423  Expr *IgnoreParenImpCasts();
424
425  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
426  /// value (including ptr->int casts of the same size).  Strip off any
427  /// ParenExpr or CastExprs, returning their operand.
428  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
429
430  /// \brief Determine whether this expression is a default function argument.
431  ///
432  /// Default arguments are implicitly generated in the abstract syntax tree
433  /// by semantic analysis for function calls, object constructions, etc. in
434  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
435  /// this routine also looks through any implicit casts to determine whether
436  /// the expression is a default argument.
437  bool isDefaultArgument() const;
438
439  /// \brief Determine whether this expression directly creates a
440  /// temporary object (of class type).
441  bool isTemporaryObject() const { return getTemporaryObject() != 0; }
442
443  /// \brief If this expression directly creates a temporary object of
444  /// class type, return the expression that actually constructs that
445  /// temporary object.
446  const Expr *getTemporaryObject() const;
447
448  const Expr *IgnoreParens() const {
449    return const_cast<Expr*>(this)->IgnoreParens();
450  }
451  const Expr *IgnoreParenCasts() const {
452    return const_cast<Expr*>(this)->IgnoreParenCasts();
453  }
454  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
455    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
456  }
457
458  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
459  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
460
461  static bool classof(const Stmt *T) {
462    return T->getStmtClass() >= firstExprConstant &&
463           T->getStmtClass() <= lastExprConstant;
464  }
465  static bool classof(const Expr *) { return true; }
466};
467
468
469//===----------------------------------------------------------------------===//
470// Primary Expressions.
471//===----------------------------------------------------------------------===//
472
473/// \brief Represents the qualifier that may precede a C++ name, e.g., the
474/// "std::" in "std::sort".
475struct NameQualifier {
476  /// \brief The nested name specifier.
477  NestedNameSpecifier *NNS;
478
479  /// \brief The source range covered by the nested name specifier.
480  SourceRange Range;
481};
482
483/// \brief Represents an explicit template argument list in C++, e.g.,
484/// the "<int>" in "sort<int>".
485struct ExplicitTemplateArgumentList {
486  /// \brief The source location of the left angle bracket ('<');
487  SourceLocation LAngleLoc;
488
489  /// \brief The source location of the right angle bracket ('>');
490  SourceLocation RAngleLoc;
491
492  /// \brief The number of template arguments in TemplateArgs.
493  /// The actual template arguments (if any) are stored after the
494  /// ExplicitTemplateArgumentList structure.
495  unsigned NumTemplateArgs;
496
497  /// \brief Retrieve the template arguments
498  TemplateArgumentLoc *getTemplateArgs() {
499    return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
500  }
501
502  /// \brief Retrieve the template arguments
503  const TemplateArgumentLoc *getTemplateArgs() const {
504    return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
505  }
506
507  void initializeFrom(const TemplateArgumentListInfo &List);
508  void copyInto(TemplateArgumentListInfo &List) const;
509  static std::size_t sizeFor(unsigned NumTemplateArgs);
510  static std::size_t sizeFor(const TemplateArgumentListInfo &List);
511};
512
513/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
514/// enum, etc.
515class DeclRefExpr : public Expr {
516  enum {
517    // Flag on DecoratedD that specifies when this declaration reference
518    // expression has a C++ nested-name-specifier.
519    HasQualifierFlag = 0x01,
520    // Flag on DecoratedD that specifies when this declaration reference
521    // expression has an explicit C++ template argument list.
522    HasExplicitTemplateArgumentListFlag = 0x02
523  };
524
525  // DecoratedD - The declaration that we are referencing, plus two bits to
526  // indicate whether (1) the declaration's name was explicitly qualified and
527  // (2) the declaration's name was followed by an explicit template
528  // argument list.
529  llvm::PointerIntPair<ValueDecl *, 2> DecoratedD;
530
531  // Loc - The location of the declaration name itself.
532  SourceLocation Loc;
533
534  /// DNLoc - Provides source/type location info for the
535  /// declaration name embedded in DecoratedD.
536  DeclarationNameLoc DNLoc;
537
538  /// \brief Retrieve the qualifier that preceded the declaration name, if any.
539  NameQualifier *getNameQualifier() {
540    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
541      return 0;
542
543    return reinterpret_cast<NameQualifier *> (this + 1);
544  }
545
546  /// \brief Retrieve the qualifier that preceded the member name, if any.
547  const NameQualifier *getNameQualifier() const {
548    return const_cast<DeclRefExpr *>(this)->getNameQualifier();
549  }
550
551  DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange,
552              ValueDecl *D, SourceLocation NameLoc,
553              const TemplateArgumentListInfo *TemplateArgs,
554              QualType T);
555
556  DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange,
557              ValueDecl *D, const DeclarationNameInfo &NameInfo,
558              const TemplateArgumentListInfo *TemplateArgs,
559              QualType T);
560
561  /// \brief Construct an empty declaration reference expression.
562  explicit DeclRefExpr(EmptyShell Empty)
563    : Expr(DeclRefExprClass, Empty) { }
564
565  /// \brief Computes the type- and value-dependence flags for this
566  /// declaration reference expression.
567  void computeDependence();
568
569public:
570  DeclRefExpr(ValueDecl *d, QualType t, SourceLocation l) :
571    Expr(DeclRefExprClass, t, false, false), DecoratedD(d, 0), Loc(l) {
572    computeDependence();
573  }
574
575  static DeclRefExpr *Create(ASTContext &Context,
576                             NestedNameSpecifier *Qualifier,
577                             SourceRange QualifierRange,
578                             ValueDecl *D,
579                             SourceLocation NameLoc,
580                             QualType T,
581                             const TemplateArgumentListInfo *TemplateArgs = 0);
582
583  static DeclRefExpr *Create(ASTContext &Context,
584                             NestedNameSpecifier *Qualifier,
585                             SourceRange QualifierRange,
586                             ValueDecl *D,
587                             const DeclarationNameInfo &NameInfo,
588                             QualType T,
589                             const TemplateArgumentListInfo *TemplateArgs = 0);
590
591  /// \brief Construct an empty declaration reference expression.
592  static DeclRefExpr *CreateEmpty(ASTContext &Context,
593                                  bool HasQualifier, unsigned NumTemplateArgs);
594
595  ValueDecl *getDecl() { return DecoratedD.getPointer(); }
596  const ValueDecl *getDecl() const { return DecoratedD.getPointer(); }
597  void setDecl(ValueDecl *NewD) { DecoratedD.setPointer(NewD); }
598
599  DeclarationNameInfo getNameInfo() const {
600    return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
601  }
602
603  SourceLocation getLocation() const { return Loc; }
604  void setLocation(SourceLocation L) { Loc = L; }
605  virtual SourceRange getSourceRange() const;
606
607  /// \brief Determine whether this declaration reference was preceded by a
608  /// C++ nested-name-specifier, e.g., \c N::foo.
609  bool hasQualifier() const { return DecoratedD.getInt() & HasQualifierFlag; }
610
611  /// \brief If the name was qualified, retrieves the source range of
612  /// the nested-name-specifier that precedes the name. Otherwise,
613  /// returns an empty source range.
614  SourceRange getQualifierRange() const {
615    if (!hasQualifier())
616      return SourceRange();
617
618    return getNameQualifier()->Range;
619  }
620
621  /// \brief If the name was qualified, retrieves the nested-name-specifier
622  /// that precedes the name. Otherwise, returns NULL.
623  NestedNameSpecifier *getQualifier() const {
624    if (!hasQualifier())
625      return 0;
626
627    return getNameQualifier()->NNS;
628  }
629
630  bool hasExplicitTemplateArgs() const {
631    return (DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag);
632  }
633
634  /// \brief Retrieve the explicit template argument list that followed the
635  /// member template name.
636  ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
637    assert(hasExplicitTemplateArgs());
638
639    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
640      return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
641
642    return *reinterpret_cast<ExplicitTemplateArgumentList *>(
643                                                      getNameQualifier() + 1);
644  }
645
646  /// \brief Retrieve the explicit template argument list that followed the
647  /// member template name.
648  const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
649    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
650  }
651
652  /// \brief Retrieves the optional explicit template arguments.
653  /// This points to the same data as getExplicitTemplateArgs(), but
654  /// returns null if there are no explicit template arguments.
655  const ExplicitTemplateArgumentList *getExplicitTemplateArgsOpt() const {
656    if (!hasExplicitTemplateArgs()) return 0;
657    return &getExplicitTemplateArgs();
658  }
659
660  /// \brief Copies the template arguments (if present) into the given
661  /// structure.
662  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
663    if (hasExplicitTemplateArgs())
664      getExplicitTemplateArgs().copyInto(List);
665  }
666
667  /// \brief Retrieve the location of the left angle bracket following the
668  /// member name ('<'), if any.
669  SourceLocation getLAngleLoc() const {
670    if (!hasExplicitTemplateArgs())
671      return SourceLocation();
672
673    return getExplicitTemplateArgs().LAngleLoc;
674  }
675
676  /// \brief Retrieve the template arguments provided as part of this
677  /// template-id.
678  const TemplateArgumentLoc *getTemplateArgs() const {
679    if (!hasExplicitTemplateArgs())
680      return 0;
681
682    return getExplicitTemplateArgs().getTemplateArgs();
683  }
684
685  /// \brief Retrieve the number of template arguments provided as part of this
686  /// template-id.
687  unsigned getNumTemplateArgs() const {
688    if (!hasExplicitTemplateArgs())
689      return 0;
690
691    return getExplicitTemplateArgs().NumTemplateArgs;
692  }
693
694  /// \brief Retrieve the location of the right angle bracket following the
695  /// template arguments ('>').
696  SourceLocation getRAngleLoc() const {
697    if (!hasExplicitTemplateArgs())
698      return SourceLocation();
699
700    return getExplicitTemplateArgs().RAngleLoc;
701  }
702
703  static bool classof(const Stmt *T) {
704    return T->getStmtClass() == DeclRefExprClass;
705  }
706  static bool classof(const DeclRefExpr *) { return true; }
707
708  // Iterators
709  virtual child_iterator child_begin();
710  virtual child_iterator child_end();
711
712  friend class ASTStmtReader;
713  friend class ASTStmtWriter;
714};
715
716/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
717class PredefinedExpr : public Expr {
718public:
719  enum IdentType {
720    Func,
721    Function,
722    PrettyFunction,
723    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
724    /// 'virtual' keyword is omitted for virtual member functions.
725    PrettyFunctionNoVirtual
726  };
727
728private:
729  SourceLocation Loc;
730  IdentType Type;
731public:
732  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
733    : Expr(PredefinedExprClass, type, type->isDependentType(),
734           type->isDependentType()), Loc(l), Type(IT) {}
735
736  /// \brief Construct an empty predefined expression.
737  explicit PredefinedExpr(EmptyShell Empty)
738    : Expr(PredefinedExprClass, Empty) { }
739
740  IdentType getIdentType() const { return Type; }
741  void setIdentType(IdentType IT) { Type = IT; }
742
743  SourceLocation getLocation() const { return Loc; }
744  void setLocation(SourceLocation L) { Loc = L; }
745
746  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
747
748  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
749
750  static bool classof(const Stmt *T) {
751    return T->getStmtClass() == PredefinedExprClass;
752  }
753  static bool classof(const PredefinedExpr *) { return true; }
754
755  // Iterators
756  virtual child_iterator child_begin();
757  virtual child_iterator child_end();
758};
759
760class IntegerLiteral : public Expr {
761  llvm::APInt Value;
762  SourceLocation Loc;
763public:
764  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
765  // or UnsignedLongLongTy
766  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
767    : Expr(IntegerLiteralClass, type, false, false), Value(V), Loc(l) {
768    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
769  }
770
771  /// \brief Construct an empty integer literal.
772  explicit IntegerLiteral(EmptyShell Empty)
773    : Expr(IntegerLiteralClass, Empty) { }
774
775  const llvm::APInt &getValue() const { return Value; }
776  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
777
778  /// \brief Retrieve the location of the literal.
779  SourceLocation getLocation() const { return Loc; }
780
781  void setValue(const llvm::APInt &Val) { Value = Val; }
782  void setLocation(SourceLocation Location) { Loc = Location; }
783
784  static bool classof(const Stmt *T) {
785    return T->getStmtClass() == IntegerLiteralClass;
786  }
787  static bool classof(const IntegerLiteral *) { return true; }
788
789  // Iterators
790  virtual child_iterator child_begin();
791  virtual child_iterator child_end();
792};
793
794class CharacterLiteral : public Expr {
795  unsigned Value;
796  SourceLocation Loc;
797  bool IsWide;
798public:
799  // type should be IntTy
800  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
801    : Expr(CharacterLiteralClass, type, false, false), Value(value), Loc(l),
802      IsWide(iswide) {
803  }
804
805  /// \brief Construct an empty character literal.
806  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
807
808  SourceLocation getLocation() const { return Loc; }
809  bool isWide() const { return IsWide; }
810
811  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
812
813  unsigned getValue() const { return Value; }
814
815  void setLocation(SourceLocation Location) { Loc = Location; }
816  void setWide(bool W) { IsWide = W; }
817  void setValue(unsigned Val) { Value = Val; }
818
819  static bool classof(const Stmt *T) {
820    return T->getStmtClass() == CharacterLiteralClass;
821  }
822  static bool classof(const CharacterLiteral *) { return true; }
823
824  // Iterators
825  virtual child_iterator child_begin();
826  virtual child_iterator child_end();
827};
828
829class FloatingLiteral : public Expr {
830  llvm::APFloat Value;
831  bool IsExact : 1;
832  SourceLocation Loc;
833public:
834  FloatingLiteral(const llvm::APFloat &V, bool isexact,
835                  QualType Type, SourceLocation L)
836    : Expr(FloatingLiteralClass, Type, false, false), Value(V),
837      IsExact(isexact), Loc(L) {}
838
839  /// \brief Construct an empty floating-point literal.
840  explicit FloatingLiteral(EmptyShell Empty)
841    : Expr(FloatingLiteralClass, Empty), Value(0.0) { }
842
843  const llvm::APFloat &getValue() const { return Value; }
844  void setValue(const llvm::APFloat &Val) { Value = Val; }
845
846  bool isExact() const { return IsExact; }
847  void setExact(bool E) { IsExact = E; }
848
849  /// getValueAsApproximateDouble - This returns the value as an inaccurate
850  /// double.  Note that this may cause loss of precision, but is useful for
851  /// debugging dumps, etc.
852  double getValueAsApproximateDouble() const;
853
854  SourceLocation getLocation() const { return Loc; }
855  void setLocation(SourceLocation L) { Loc = L; }
856
857  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
858
859  static bool classof(const Stmt *T) {
860    return T->getStmtClass() == FloatingLiteralClass;
861  }
862  static bool classof(const FloatingLiteral *) { return true; }
863
864  // Iterators
865  virtual child_iterator child_begin();
866  virtual child_iterator child_end();
867};
868
869/// ImaginaryLiteral - We support imaginary integer and floating point literals,
870/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
871/// IntegerLiteral classes.  Instances of this class always have a Complex type
872/// whose element type matches the subexpression.
873///
874class ImaginaryLiteral : public Expr {
875  Stmt *Val;
876public:
877  ImaginaryLiteral(Expr *val, QualType Ty)
878    : Expr(ImaginaryLiteralClass, Ty, false, false), Val(val) {}
879
880  /// \brief Build an empty imaginary literal.
881  explicit ImaginaryLiteral(EmptyShell Empty)
882    : Expr(ImaginaryLiteralClass, Empty) { }
883
884  const Expr *getSubExpr() const { return cast<Expr>(Val); }
885  Expr *getSubExpr() { return cast<Expr>(Val); }
886  void setSubExpr(Expr *E) { Val = E; }
887
888  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
889  static bool classof(const Stmt *T) {
890    return T->getStmtClass() == ImaginaryLiteralClass;
891  }
892  static bool classof(const ImaginaryLiteral *) { return true; }
893
894  // Iterators
895  virtual child_iterator child_begin();
896  virtual child_iterator child_end();
897};
898
899/// StringLiteral - This represents a string literal expression, e.g. "foo"
900/// or L"bar" (wide strings).  The actual string is returned by getStrData()
901/// is NOT null-terminated, and the length of the string is determined by
902/// calling getByteLength().  The C type for a string is always a
903/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
904/// not.
905///
906/// Note that strings in C can be formed by concatenation of multiple string
907/// literal pptokens in translation phase #6.  This keeps track of the locations
908/// of each of these pieces.
909///
910/// Strings in C can also be truncated and extended by assigning into arrays,
911/// e.g. with constructs like:
912///   char X[2] = "foobar";
913/// In this case, getByteLength() will return 6, but the string literal will
914/// have type "char[2]".
915class StringLiteral : public Expr {
916  const char *StrData;
917  unsigned ByteLength;
918  bool IsWide;
919  unsigned NumConcatenated;
920  SourceLocation TokLocs[1];
921
922  StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty, false, false) {}
923
924public:
925  /// This is the "fully general" constructor that allows representation of
926  /// strings formed from multiple concatenated tokens.
927  static StringLiteral *Create(ASTContext &C, const char *StrData,
928                               unsigned ByteLength, bool Wide, QualType Ty,
929                               const SourceLocation *Loc, unsigned NumStrs);
930
931  /// Simple constructor for string literals made from one token.
932  static StringLiteral *Create(ASTContext &C, const char *StrData,
933                               unsigned ByteLength,
934                               bool Wide, QualType Ty, SourceLocation Loc) {
935    return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
936  }
937
938  /// \brief Construct an empty string literal.
939  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
940
941  llvm::StringRef getString() const {
942    return llvm::StringRef(StrData, ByteLength);
943  }
944
945  unsigned getByteLength() const { return ByteLength; }
946
947  /// \brief Sets the string data to the given string data.
948  void setString(ASTContext &C, llvm::StringRef Str);
949
950  bool isWide() const { return IsWide; }
951  void setWide(bool W) { IsWide = W; }
952
953  bool containsNonAsciiOrNull() const {
954    llvm::StringRef Str = getString();
955    for (unsigned i = 0, e = Str.size(); i != e; ++i)
956      if (!isascii(Str[i]) || !Str[i])
957        return true;
958    return false;
959  }
960  /// getNumConcatenated - Get the number of string literal tokens that were
961  /// concatenated in translation phase #6 to form this string literal.
962  unsigned getNumConcatenated() const { return NumConcatenated; }
963
964  SourceLocation getStrTokenLoc(unsigned TokNum) const {
965    assert(TokNum < NumConcatenated && "Invalid tok number");
966    return TokLocs[TokNum];
967  }
968  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
969    assert(TokNum < NumConcatenated && "Invalid tok number");
970    TokLocs[TokNum] = L;
971  }
972
973  typedef const SourceLocation *tokloc_iterator;
974  tokloc_iterator tokloc_begin() const { return TokLocs; }
975  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
976
977  virtual SourceRange getSourceRange() const {
978    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
979  }
980  static bool classof(const Stmt *T) {
981    return T->getStmtClass() == StringLiteralClass;
982  }
983  static bool classof(const StringLiteral *) { return true; }
984
985  // Iterators
986  virtual child_iterator child_begin();
987  virtual child_iterator child_end();
988};
989
990/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
991/// AST node is only formed if full location information is requested.
992class ParenExpr : public Expr {
993  SourceLocation L, R;
994  Stmt *Val;
995public:
996  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
997    : Expr(ParenExprClass, val->getType(),
998           val->isTypeDependent(), val->isValueDependent()),
999      L(l), R(r), Val(val) {}
1000
1001  /// \brief Construct an empty parenthesized expression.
1002  explicit ParenExpr(EmptyShell Empty)
1003    : Expr(ParenExprClass, Empty) { }
1004
1005  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1006  Expr *getSubExpr() { return cast<Expr>(Val); }
1007  void setSubExpr(Expr *E) { Val = E; }
1008
1009  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
1010
1011  /// \brief Get the location of the left parentheses '('.
1012  SourceLocation getLParen() const { return L; }
1013  void setLParen(SourceLocation Loc) { L = Loc; }
1014
1015  /// \brief Get the location of the right parentheses ')'.
1016  SourceLocation getRParen() const { return R; }
1017  void setRParen(SourceLocation Loc) { R = Loc; }
1018
1019  static bool classof(const Stmt *T) {
1020    return T->getStmtClass() == ParenExprClass;
1021  }
1022  static bool classof(const ParenExpr *) { return true; }
1023
1024  // Iterators
1025  virtual child_iterator child_begin();
1026  virtual child_iterator child_end();
1027};
1028
1029
1030/// UnaryOperator - This represents the unary-expression's (except sizeof and
1031/// alignof), the postinc/postdec operators from postfix-expression, and various
1032/// extensions.
1033///
1034/// Notes on various nodes:
1035///
1036/// Real/Imag - These return the real/imag part of a complex operand.  If
1037///   applied to a non-complex value, the former returns its operand and the
1038///   later returns zero in the type of the operand.
1039///
1040class UnaryOperator : public Expr {
1041public:
1042  typedef UnaryOperatorKind Opcode;
1043
1044private:
1045  unsigned Opc : 5;
1046  SourceLocation Loc;
1047  Stmt *Val;
1048public:
1049
1050  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
1051    : Expr(UnaryOperatorClass, type,
1052           input->isTypeDependent() || type->isDependentType(),
1053           input->isValueDependent()),
1054      Opc(opc), Loc(l), Val(input) {}
1055
1056  /// \brief Build an empty unary operator.
1057  explicit UnaryOperator(EmptyShell Empty)
1058    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1059
1060  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1061  void setOpcode(Opcode O) { Opc = O; }
1062
1063  Expr *getSubExpr() const { return cast<Expr>(Val); }
1064  void setSubExpr(Expr *E) { Val = E; }
1065
1066  /// getOperatorLoc - Return the location of the operator.
1067  SourceLocation getOperatorLoc() const { return Loc; }
1068  void setOperatorLoc(SourceLocation L) { Loc = L; }
1069
1070  /// isPostfix - Return true if this is a postfix operation, like x++.
1071  static bool isPostfix(Opcode Op) {
1072    return Op == UO_PostInc || Op == UO_PostDec;
1073  }
1074
1075  /// isPostfix - Return true if this is a prefix operation, like --x.
1076  static bool isPrefix(Opcode Op) {
1077    return Op == UO_PreInc || Op == UO_PreDec;
1078  }
1079
1080  bool isPrefix() const { return isPrefix(getOpcode()); }
1081  bool isPostfix() const { return isPostfix(getOpcode()); }
1082  bool isIncrementOp() const {
1083    return Opc == UO_PreInc || getOpcode() == UO_PostInc;
1084  }
1085  bool isIncrementDecrementOp() const {
1086    return Opc >= UO_PostInc && Opc <= UO_PreDec;
1087  }
1088  static bool isArithmeticOp(Opcode Op) {
1089    return Op >= UO_Plus && Op <= UO_LNot;
1090  }
1091  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1092
1093  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1094  /// corresponds to, e.g. "sizeof" or "[pre]++"
1095  static const char *getOpcodeStr(Opcode Op);
1096
1097  /// \brief Retrieve the unary opcode that corresponds to the given
1098  /// overloaded operator.
1099  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1100
1101  /// \brief Retrieve the overloaded operator kind that corresponds to
1102  /// the given unary opcode.
1103  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1104
1105  virtual SourceRange getSourceRange() const {
1106    if (isPostfix())
1107      return SourceRange(Val->getLocStart(), Loc);
1108    else
1109      return SourceRange(Loc, Val->getLocEnd());
1110  }
1111  virtual SourceLocation getExprLoc() const { return Loc; }
1112
1113  static bool classof(const Stmt *T) {
1114    return T->getStmtClass() == UnaryOperatorClass;
1115  }
1116  static bool classof(const UnaryOperator *) { return true; }
1117
1118  // Iterators
1119  virtual child_iterator child_begin();
1120  virtual child_iterator child_end();
1121};
1122
1123/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1124/// offsetof(record-type, member-designator). For example, given:
1125/// @code
1126/// struct S {
1127///   float f;
1128///   double d;
1129/// };
1130/// struct T {
1131///   int i;
1132///   struct S s[10];
1133/// };
1134/// @endcode
1135/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1136
1137class OffsetOfExpr : public Expr {
1138public:
1139  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1140  class OffsetOfNode {
1141  public:
1142    /// \brief The kind of offsetof node we have.
1143    enum Kind {
1144      /// \brief An index into an array.
1145      Array = 0x00,
1146      /// \brief A field.
1147      Field = 0x01,
1148      /// \brief A field in a dependent type, known only by its name.
1149      Identifier = 0x02,
1150      /// \brief An implicit indirection through a C++ base class, when the
1151      /// field found is in a base class.
1152      Base = 0x03
1153    };
1154
1155  private:
1156    enum { MaskBits = 2, Mask = 0x03 };
1157
1158    /// \brief The source range that covers this part of the designator.
1159    SourceRange Range;
1160
1161    /// \brief The data describing the designator, which comes in three
1162    /// different forms, depending on the lower two bits.
1163    ///   - An unsigned index into the array of Expr*'s stored after this node
1164    ///     in memory, for [constant-expression] designators.
1165    ///   - A FieldDecl*, for references to a known field.
1166    ///   - An IdentifierInfo*, for references to a field with a given name
1167    ///     when the class type is dependent.
1168    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1169    ///     base class.
1170    uintptr_t Data;
1171
1172  public:
1173    /// \brief Create an offsetof node that refers to an array element.
1174    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1175                 SourceLocation RBracketLoc)
1176      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1177
1178    /// \brief Create an offsetof node that refers to a field.
1179    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1180                 SourceLocation NameLoc)
1181      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1182        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1183
1184    /// \brief Create an offsetof node that refers to an identifier.
1185    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1186                 SourceLocation NameLoc)
1187      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1188        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1189
1190    /// \brief Create an offsetof node that refers into a C++ base class.
1191    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1192      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1193
1194    /// \brief Determine what kind of offsetof node this is.
1195    Kind getKind() const {
1196      return static_cast<Kind>(Data & Mask);
1197    }
1198
1199    /// \brief For an array element node, returns the index into the array
1200    /// of expressions.
1201    unsigned getArrayExprIndex() const {
1202      assert(getKind() == Array);
1203      return Data >> 2;
1204    }
1205
1206    /// \brief For a field offsetof node, returns the field.
1207    FieldDecl *getField() const {
1208      assert(getKind() == Field);
1209      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1210    }
1211
1212    /// \brief For a field or identifier offsetof node, returns the name of
1213    /// the field.
1214    IdentifierInfo *getFieldName() const;
1215
1216    /// \brief For a base class node, returns the base specifier.
1217    CXXBaseSpecifier *getBase() const {
1218      assert(getKind() == Base);
1219      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1220    }
1221
1222    /// \brief Retrieve the source range that covers this offsetof node.
1223    ///
1224    /// For an array element node, the source range contains the locations of
1225    /// the square brackets. For a field or identifier node, the source range
1226    /// contains the location of the period (if there is one) and the
1227    /// identifier.
1228    SourceRange getRange() const { return Range; }
1229  };
1230
1231private:
1232
1233  SourceLocation OperatorLoc, RParenLoc;
1234  // Base type;
1235  TypeSourceInfo *TSInfo;
1236  // Number of sub-components (i.e. instances of OffsetOfNode).
1237  unsigned NumComps;
1238  // Number of sub-expressions (i.e. array subscript expressions).
1239  unsigned NumExprs;
1240
1241  OffsetOfExpr(ASTContext &C, QualType type,
1242               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1243               OffsetOfNode* compsPtr, unsigned numComps,
1244               Expr** exprsPtr, unsigned numExprs,
1245               SourceLocation RParenLoc);
1246
1247  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1248    : Expr(OffsetOfExprClass, EmptyShell()),
1249      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1250
1251public:
1252
1253  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1254                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1255                              OffsetOfNode* compsPtr, unsigned numComps,
1256                              Expr** exprsPtr, unsigned numExprs,
1257                              SourceLocation RParenLoc);
1258
1259  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1260                                   unsigned NumComps, unsigned NumExprs);
1261
1262  /// getOperatorLoc - Return the location of the operator.
1263  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1264  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1265
1266  /// \brief Return the location of the right parentheses.
1267  SourceLocation getRParenLoc() const { return RParenLoc; }
1268  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1269
1270  TypeSourceInfo *getTypeSourceInfo() const {
1271    return TSInfo;
1272  }
1273  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1274    TSInfo = tsi;
1275  }
1276
1277  const OffsetOfNode &getComponent(unsigned Idx) {
1278    assert(Idx < NumComps && "Subscript out of range");
1279    return reinterpret_cast<OffsetOfNode *> (this + 1)[Idx];
1280  }
1281
1282  void setComponent(unsigned Idx, OffsetOfNode ON) {
1283    assert(Idx < NumComps && "Subscript out of range");
1284    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1285  }
1286
1287  unsigned getNumComponents() const {
1288    return NumComps;
1289  }
1290
1291  Expr* getIndexExpr(unsigned Idx) {
1292    assert(Idx < NumExprs && "Subscript out of range");
1293    return reinterpret_cast<Expr **>(
1294                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1295  }
1296
1297  void setIndexExpr(unsigned Idx, Expr* E) {
1298    assert(Idx < NumComps && "Subscript out of range");
1299    reinterpret_cast<Expr **>(
1300                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1301  }
1302
1303  unsigned getNumExpressions() const {
1304    return NumExprs;
1305  }
1306
1307  virtual SourceRange getSourceRange() const {
1308    return SourceRange(OperatorLoc, RParenLoc);
1309  }
1310
1311  static bool classof(const Stmt *T) {
1312    return T->getStmtClass() == OffsetOfExprClass;
1313  }
1314
1315  static bool classof(const OffsetOfExpr *) { return true; }
1316
1317  // Iterators
1318  virtual child_iterator child_begin();
1319  virtual child_iterator child_end();
1320};
1321
1322/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
1323/// types and expressions.
1324class SizeOfAlignOfExpr : public Expr {
1325  bool isSizeof : 1;  // true if sizeof, false if alignof.
1326  bool isType : 1;    // true if operand is a type, false if an expression
1327  union {
1328    TypeSourceInfo *Ty;
1329    Stmt *Ex;
1330  } Argument;
1331  SourceLocation OpLoc, RParenLoc;
1332
1333public:
1334  SizeOfAlignOfExpr(bool issizeof, TypeSourceInfo *TInfo,
1335                    QualType resultType, SourceLocation op,
1336                    SourceLocation rp) :
1337      Expr(SizeOfAlignOfExprClass, resultType,
1338           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1339           // Value-dependent if the argument is type-dependent.
1340           TInfo->getType()->isDependentType()),
1341      isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) {
1342    Argument.Ty = TInfo;
1343  }
1344
1345  SizeOfAlignOfExpr(bool issizeof, Expr *E,
1346                    QualType resultType, SourceLocation op,
1347                    SourceLocation rp) :
1348      Expr(SizeOfAlignOfExprClass, resultType,
1349           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1350           // Value-dependent if the argument is type-dependent.
1351           E->isTypeDependent()),
1352      isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) {
1353    Argument.Ex = E;
1354  }
1355
1356  /// \brief Construct an empty sizeof/alignof expression.
1357  explicit SizeOfAlignOfExpr(EmptyShell Empty)
1358    : Expr(SizeOfAlignOfExprClass, Empty) { }
1359
1360  bool isSizeOf() const { return isSizeof; }
1361  void setSizeof(bool S) { isSizeof = S; }
1362
1363  bool isArgumentType() const { return isType; }
1364  QualType getArgumentType() const {
1365    return getArgumentTypeInfo()->getType();
1366  }
1367  TypeSourceInfo *getArgumentTypeInfo() const {
1368    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1369    return Argument.Ty;
1370  }
1371  Expr *getArgumentExpr() {
1372    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1373    return static_cast<Expr*>(Argument.Ex);
1374  }
1375  const Expr *getArgumentExpr() const {
1376    return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
1377  }
1378
1379  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1380  void setArgument(TypeSourceInfo *TInfo) {
1381    Argument.Ty = TInfo;
1382    isType = true;
1383  }
1384
1385  /// Gets the argument type, or the type of the argument expression, whichever
1386  /// is appropriate.
1387  QualType getTypeOfArgument() const {
1388    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1389  }
1390
1391  SourceLocation getOperatorLoc() const { return OpLoc; }
1392  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1393
1394  SourceLocation getRParenLoc() const { return RParenLoc; }
1395  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1396
1397  virtual SourceRange getSourceRange() const {
1398    return SourceRange(OpLoc, RParenLoc);
1399  }
1400
1401  static bool classof(const Stmt *T) {
1402    return T->getStmtClass() == SizeOfAlignOfExprClass;
1403  }
1404  static bool classof(const SizeOfAlignOfExpr *) { return true; }
1405
1406  // Iterators
1407  virtual child_iterator child_begin();
1408  virtual child_iterator child_end();
1409};
1410
1411//===----------------------------------------------------------------------===//
1412// Postfix Operators.
1413//===----------------------------------------------------------------------===//
1414
1415/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1416class ArraySubscriptExpr : public Expr {
1417  enum { LHS, RHS, END_EXPR=2 };
1418  Stmt* SubExprs[END_EXPR];
1419  SourceLocation RBracketLoc;
1420public:
1421  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1422                     SourceLocation rbracketloc)
1423  : Expr(ArraySubscriptExprClass, t,
1424         lhs->isTypeDependent() || rhs->isTypeDependent(),
1425         lhs->isValueDependent() || rhs->isValueDependent()),
1426    RBracketLoc(rbracketloc) {
1427    SubExprs[LHS] = lhs;
1428    SubExprs[RHS] = rhs;
1429  }
1430
1431  /// \brief Create an empty array subscript expression.
1432  explicit ArraySubscriptExpr(EmptyShell Shell)
1433    : Expr(ArraySubscriptExprClass, Shell) { }
1434
1435  /// An array access can be written A[4] or 4[A] (both are equivalent).
1436  /// - getBase() and getIdx() always present the normalized view: A[4].
1437  ///    In this case getBase() returns "A" and getIdx() returns "4".
1438  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1439  ///    4[A] getLHS() returns "4".
1440  /// Note: Because vector element access is also written A[4] we must
1441  /// predicate the format conversion in getBase and getIdx only on the
1442  /// the type of the RHS, as it is possible for the LHS to be a vector of
1443  /// integer type
1444  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1445  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1446  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1447
1448  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1449  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1450  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1451
1452  Expr *getBase() {
1453    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1454  }
1455
1456  const Expr *getBase() const {
1457    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1458  }
1459
1460  Expr *getIdx() {
1461    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1462  }
1463
1464  const Expr *getIdx() const {
1465    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1466  }
1467
1468  virtual SourceRange getSourceRange() const {
1469    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1470  }
1471
1472  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1473  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1474
1475  virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1476
1477  static bool classof(const Stmt *T) {
1478    return T->getStmtClass() == ArraySubscriptExprClass;
1479  }
1480  static bool classof(const ArraySubscriptExpr *) { return true; }
1481
1482  // Iterators
1483  virtual child_iterator child_begin();
1484  virtual child_iterator child_end();
1485};
1486
1487
1488/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1489/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1490/// while its subclasses may represent alternative syntax that (semantically)
1491/// results in a function call. For example, CXXOperatorCallExpr is
1492/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1493/// "str1 + str2" to resolve to a function call.
1494class CallExpr : public Expr {
1495  enum { FN=0, ARGS_START=1 };
1496  Stmt **SubExprs;
1497  unsigned NumArgs;
1498  SourceLocation RParenLoc;
1499
1500protected:
1501  // This version of the constructor is for derived classes.
1502  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs,
1503           QualType t, SourceLocation rparenloc);
1504
1505public:
1506  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1507           SourceLocation rparenloc);
1508
1509  /// \brief Build an empty call expression.
1510  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1511
1512  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1513  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1514  void setCallee(Expr *F) { SubExprs[FN] = F; }
1515
1516  Decl *getCalleeDecl();
1517  const Decl *getCalleeDecl() const {
1518    return const_cast<CallExpr*>(this)->getCalleeDecl();
1519  }
1520
1521  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1522  FunctionDecl *getDirectCallee();
1523  const FunctionDecl *getDirectCallee() const {
1524    return const_cast<CallExpr*>(this)->getDirectCallee();
1525  }
1526
1527  /// getNumArgs - Return the number of actual arguments to this call.
1528  ///
1529  unsigned getNumArgs() const { return NumArgs; }
1530
1531  /// getArg - Return the specified argument.
1532  Expr *getArg(unsigned Arg) {
1533    assert(Arg < NumArgs && "Arg access out of range!");
1534    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1535  }
1536  const Expr *getArg(unsigned Arg) const {
1537    assert(Arg < NumArgs && "Arg access out of range!");
1538    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1539  }
1540
1541  /// setArg - Set the specified argument.
1542  void setArg(unsigned Arg, Expr *ArgExpr) {
1543    assert(Arg < NumArgs && "Arg access out of range!");
1544    SubExprs[Arg+ARGS_START] = ArgExpr;
1545  }
1546
1547  /// setNumArgs - This changes the number of arguments present in this call.
1548  /// Any orphaned expressions are deleted by this, and any new operands are set
1549  /// to null.
1550  void setNumArgs(ASTContext& C, unsigned NumArgs);
1551
1552  typedef ExprIterator arg_iterator;
1553  typedef ConstExprIterator const_arg_iterator;
1554
1555  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
1556  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
1557  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
1558  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
1559
1560  /// getNumCommas - Return the number of commas that must have been present in
1561  /// this function call.
1562  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1563
1564  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1565  /// not, return 0.
1566  unsigned isBuiltinCall(ASTContext &Context) const;
1567
1568  /// getCallReturnType - Get the return type of the call expr. This is not
1569  /// always the type of the expr itself, if the return type is a reference
1570  /// type.
1571  QualType getCallReturnType() const;
1572
1573  SourceLocation getRParenLoc() const { return RParenLoc; }
1574  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1575
1576  virtual SourceRange getSourceRange() const {
1577    return SourceRange(getCallee()->getLocStart(), RParenLoc);
1578  }
1579
1580  static bool classof(const Stmt *T) {
1581    return T->getStmtClass() >= firstCallExprConstant &&
1582           T->getStmtClass() <= lastCallExprConstant;
1583  }
1584  static bool classof(const CallExpr *) { return true; }
1585
1586  // Iterators
1587  virtual child_iterator child_begin();
1588  virtual child_iterator child_end();
1589};
1590
1591/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1592///
1593class MemberExpr : public Expr {
1594  /// Extra data stored in some member expressions.
1595  struct MemberNameQualifier : public NameQualifier {
1596    DeclAccessPair FoundDecl;
1597  };
1598
1599  /// Base - the expression for the base pointer or structure references.  In
1600  /// X.F, this is "X".
1601  Stmt *Base;
1602
1603  /// MemberDecl - This is the decl being referenced by the field/member name.
1604  /// In X.F, this is the decl referenced by F.
1605  ValueDecl *MemberDecl;
1606
1607  /// MemberLoc - This is the location of the member name.
1608  SourceLocation MemberLoc;
1609
1610  /// MemberDNLoc - Provides source/type location info for the
1611  /// declaration name embedded in MemberDecl.
1612  DeclarationNameLoc MemberDNLoc;
1613
1614  /// IsArrow - True if this is "X->F", false if this is "X.F".
1615  bool IsArrow : 1;
1616
1617  /// \brief True if this member expression used a nested-name-specifier to
1618  /// refer to the member, e.g., "x->Base::f", or found its member via a using
1619  /// declaration.  When true, a MemberNameQualifier
1620  /// structure is allocated immediately after the MemberExpr.
1621  bool HasQualifierOrFoundDecl : 1;
1622
1623  /// \brief True if this member expression specified a template argument list
1624  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
1625  /// structure (and its TemplateArguments) are allocated immediately after
1626  /// the MemberExpr or, if the member expression also has a qualifier, after
1627  /// the MemberNameQualifier structure.
1628  bool HasExplicitTemplateArgumentList : 1;
1629
1630  /// \brief Retrieve the qualifier that preceded the member name, if any.
1631  MemberNameQualifier *getMemberQualifier() {
1632    assert(HasQualifierOrFoundDecl);
1633    return reinterpret_cast<MemberNameQualifier *> (this + 1);
1634  }
1635
1636  /// \brief Retrieve the qualifier that preceded the member name, if any.
1637  const MemberNameQualifier *getMemberQualifier() const {
1638    return const_cast<MemberExpr *>(this)->getMemberQualifier();
1639  }
1640
1641public:
1642  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1643             const DeclarationNameInfo &NameInfo, QualType ty)
1644    : Expr(MemberExprClass, ty,
1645           base->isTypeDependent(), base->isValueDependent()),
1646      Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
1647      MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
1648      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {
1649    assert(memberdecl->getDeclName() == NameInfo.getName());
1650  }
1651
1652  // NOTE: this constructor should be used only when it is known that
1653  // the member name can not provide additional syntactic info
1654  // (i.e., source locations for C++ operator names or type source info
1655  // for constructors, destructors and conversion oeprators).
1656  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1657             SourceLocation l, QualType ty)
1658    : Expr(MemberExprClass, ty,
1659           base->isTypeDependent(), base->isValueDependent()),
1660      Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
1661      IsArrow(isarrow),
1662      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
1663
1664  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
1665                            NestedNameSpecifier *qual, SourceRange qualrange,
1666                            ValueDecl *memberdecl, DeclAccessPair founddecl,
1667                            DeclarationNameInfo MemberNameInfo,
1668                            const TemplateArgumentListInfo *targs,
1669                            QualType ty);
1670
1671  void setBase(Expr *E) { Base = E; }
1672  Expr *getBase() const { return cast<Expr>(Base); }
1673
1674  /// \brief Retrieve the member declaration to which this expression refers.
1675  ///
1676  /// The returned declaration will either be a FieldDecl or (in C++)
1677  /// a CXXMethodDecl.
1678  ValueDecl *getMemberDecl() const { return MemberDecl; }
1679  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
1680
1681  /// \brief Retrieves the declaration found by lookup.
1682  DeclAccessPair getFoundDecl() const {
1683    if (!HasQualifierOrFoundDecl)
1684      return DeclAccessPair::make(getMemberDecl(),
1685                                  getMemberDecl()->getAccess());
1686    return getMemberQualifier()->FoundDecl;
1687  }
1688
1689  /// \brief Determines whether this member expression actually had
1690  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
1691  /// x->Base::foo.
1692  bool hasQualifier() const { return getQualifier() != 0; }
1693
1694  /// \brief If the member name was qualified, retrieves the source range of
1695  /// the nested-name-specifier that precedes the member name. Otherwise,
1696  /// returns an empty source range.
1697  SourceRange getQualifierRange() const {
1698    if (!HasQualifierOrFoundDecl)
1699      return SourceRange();
1700
1701    return getMemberQualifier()->Range;
1702  }
1703
1704  /// \brief If the member name was qualified, retrieves the
1705  /// nested-name-specifier that precedes the member name. Otherwise, returns
1706  /// NULL.
1707  NestedNameSpecifier *getQualifier() const {
1708    if (!HasQualifierOrFoundDecl)
1709      return 0;
1710
1711    return getMemberQualifier()->NNS;
1712  }
1713
1714  /// \brief Determines whether this member expression actually had a C++
1715  /// template argument list explicitly specified, e.g., x.f<int>.
1716  bool hasExplicitTemplateArgs() const {
1717    return HasExplicitTemplateArgumentList;
1718  }
1719
1720  /// \brief Copies the template arguments (if present) into the given
1721  /// structure.
1722  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1723    if (hasExplicitTemplateArgs())
1724      getExplicitTemplateArgs().copyInto(List);
1725  }
1726
1727  /// \brief Retrieve the explicit template argument list that
1728  /// follow the member template name.  This must only be called on an
1729  /// expression with explicit template arguments.
1730  ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
1731    assert(HasExplicitTemplateArgumentList);
1732    if (!HasQualifierOrFoundDecl)
1733      return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
1734
1735    return *reinterpret_cast<ExplicitTemplateArgumentList *>(
1736                                                      getMemberQualifier() + 1);
1737  }
1738
1739  /// \brief Retrieve the explicit template argument list that
1740  /// followed the member template name.  This must only be called on
1741  /// an expression with explicit template arguments.
1742  const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
1743    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
1744  }
1745
1746  /// \brief Retrieves the optional explicit template arguments.
1747  /// This points to the same data as getExplicitTemplateArgs(), but
1748  /// returns null if there are no explicit template arguments.
1749  const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() const {
1750    if (!hasExplicitTemplateArgs()) return 0;
1751    return &getExplicitTemplateArgs();
1752  }
1753
1754  /// \brief Retrieve the location of the left angle bracket following the
1755  /// member name ('<'), if any.
1756  SourceLocation getLAngleLoc() const {
1757    if (!HasExplicitTemplateArgumentList)
1758      return SourceLocation();
1759
1760    return getExplicitTemplateArgs().LAngleLoc;
1761  }
1762
1763  /// \brief Retrieve the template arguments provided as part of this
1764  /// template-id.
1765  const TemplateArgumentLoc *getTemplateArgs() const {
1766    if (!HasExplicitTemplateArgumentList)
1767      return 0;
1768
1769    return getExplicitTemplateArgs().getTemplateArgs();
1770  }
1771
1772  /// \brief Retrieve the number of template arguments provided as part of this
1773  /// template-id.
1774  unsigned getNumTemplateArgs() const {
1775    if (!HasExplicitTemplateArgumentList)
1776      return 0;
1777
1778    return getExplicitTemplateArgs().NumTemplateArgs;
1779  }
1780
1781  /// \brief Retrieve the location of the right angle bracket following the
1782  /// template arguments ('>').
1783  SourceLocation getRAngleLoc() const {
1784    if (!HasExplicitTemplateArgumentList)
1785      return SourceLocation();
1786
1787    return getExplicitTemplateArgs().RAngleLoc;
1788  }
1789
1790  /// \brief Retrieve the member declaration name info.
1791  DeclarationNameInfo getMemberNameInfo() const {
1792    return DeclarationNameInfo(MemberDecl->getDeclName(),
1793                               MemberLoc, MemberDNLoc);
1794  }
1795
1796  bool isArrow() const { return IsArrow; }
1797  void setArrow(bool A) { IsArrow = A; }
1798
1799  /// getMemberLoc - Return the location of the "member", in X->F, it is the
1800  /// location of 'F'.
1801  SourceLocation getMemberLoc() const { return MemberLoc; }
1802  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
1803
1804  virtual SourceRange getSourceRange() const {
1805    // If we have an implicit base (like a C++ implicit this),
1806    // make sure not to return its location
1807    SourceLocation EndLoc = (HasExplicitTemplateArgumentList)
1808      ? getRAngleLoc() : getMemberNameInfo().getEndLoc();
1809
1810    SourceLocation BaseLoc = getBase()->getLocStart();
1811    if (BaseLoc.isInvalid())
1812      return SourceRange(MemberLoc, EndLoc);
1813    return SourceRange(BaseLoc, EndLoc);
1814  }
1815
1816  virtual SourceLocation getExprLoc() const { return MemberLoc; }
1817
1818  static bool classof(const Stmt *T) {
1819    return T->getStmtClass() == MemberExprClass;
1820  }
1821  static bool classof(const MemberExpr *) { return true; }
1822
1823  // Iterators
1824  virtual child_iterator child_begin();
1825  virtual child_iterator child_end();
1826};
1827
1828/// CompoundLiteralExpr - [C99 6.5.2.5]
1829///
1830class CompoundLiteralExpr : public Expr {
1831  /// LParenLoc - If non-null, this is the location of the left paren in a
1832  /// compound literal like "(int){4}".  This can be null if this is a
1833  /// synthesized compound expression.
1834  SourceLocation LParenLoc;
1835
1836  /// The type as written.  This can be an incomplete array type, in
1837  /// which case the actual expression type will be different.
1838  TypeSourceInfo *TInfo;
1839  Stmt *Init;
1840  bool FileScope;
1841public:
1842  // FIXME: Can compound literals be value-dependent?
1843  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
1844                      QualType T, Expr *init, bool fileScope)
1845    : Expr(CompoundLiteralExprClass, T,
1846           tinfo->getType()->isDependentType(), false),
1847      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
1848
1849  /// \brief Construct an empty compound literal.
1850  explicit CompoundLiteralExpr(EmptyShell Empty)
1851    : Expr(CompoundLiteralExprClass, Empty) { }
1852
1853  const Expr *getInitializer() const { return cast<Expr>(Init); }
1854  Expr *getInitializer() { return cast<Expr>(Init); }
1855  void setInitializer(Expr *E) { Init = E; }
1856
1857  bool isFileScope() const { return FileScope; }
1858  void setFileScope(bool FS) { FileScope = FS; }
1859
1860  SourceLocation getLParenLoc() const { return LParenLoc; }
1861  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1862
1863  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
1864  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
1865
1866  virtual SourceRange getSourceRange() const {
1867    // FIXME: Init should never be null.
1868    if (!Init)
1869      return SourceRange();
1870    if (LParenLoc.isInvalid())
1871      return Init->getSourceRange();
1872    return SourceRange(LParenLoc, Init->getLocEnd());
1873  }
1874
1875  static bool classof(const Stmt *T) {
1876    return T->getStmtClass() == CompoundLiteralExprClass;
1877  }
1878  static bool classof(const CompoundLiteralExpr *) { return true; }
1879
1880  // Iterators
1881  virtual child_iterator child_begin();
1882  virtual child_iterator child_end();
1883};
1884
1885/// CastExpr - Base class for type casts, including both implicit
1886/// casts (ImplicitCastExpr) and explicit casts that have some
1887/// representation in the source code (ExplicitCastExpr's derived
1888/// classes).
1889class CastExpr : public Expr {
1890public:
1891  typedef clang::CastKind CastKind;
1892
1893private:
1894  unsigned Kind : 5;
1895  unsigned BasePathSize : BitsRemaining - 5;
1896  Stmt *Op;
1897
1898  void CheckBasePath() const {
1899#ifndef NDEBUG
1900    switch (getCastKind()) {
1901    case CK_DerivedToBase:
1902    case CK_UncheckedDerivedToBase:
1903    case CK_DerivedToBaseMemberPointer:
1904    case CK_BaseToDerived:
1905    case CK_BaseToDerivedMemberPointer:
1906      assert(!path_empty() && "Cast kind should have a base path!");
1907      break;
1908
1909    // These should not have an inheritance path.
1910    case CK_Unknown:
1911    case CK_BitCast:
1912    case CK_LValueBitCast:
1913    case CK_NoOp:
1914    case CK_Dynamic:
1915    case CK_ToUnion:
1916    case CK_ArrayToPointerDecay:
1917    case CK_FunctionToPointerDecay:
1918    case CK_NullToMemberPointer:
1919    case CK_UserDefinedConversion:
1920    case CK_ConstructorConversion:
1921    case CK_IntegralToPointer:
1922    case CK_PointerToIntegral:
1923    case CK_ToVoid:
1924    case CK_VectorSplat:
1925    case CK_IntegralCast:
1926    case CK_IntegralToFloating:
1927    case CK_FloatingToIntegral:
1928    case CK_FloatingCast:
1929    case CK_MemberPointerToBoolean:
1930    case CK_AnyPointerToObjCPointerCast:
1931    case CK_AnyPointerToBlockPointerCast:
1932    case CK_ObjCObjectLValueCast:
1933      assert(path_empty() && "Cast kind should not have a base path!");
1934      break;
1935    }
1936#endif
1937  }
1938
1939  const CXXBaseSpecifier * const *path_buffer() const {
1940    return const_cast<CastExpr*>(this)->path_buffer();
1941  }
1942  CXXBaseSpecifier **path_buffer();
1943
1944protected:
1945  CastExpr(StmtClass SC, QualType ty, const CastKind kind, Expr *op,
1946           unsigned BasePathSize) :
1947    Expr(SC, ty,
1948         // Cast expressions are type-dependent if the type is
1949         // dependent (C++ [temp.dep.expr]p3).
1950         ty->isDependentType(),
1951         // Cast expressions are value-dependent if the type is
1952         // dependent or if the subexpression is value-dependent.
1953         ty->isDependentType() || (op && op->isValueDependent())),
1954    Kind(kind), BasePathSize(BasePathSize), Op(op) {
1955    CheckBasePath();
1956  }
1957
1958  /// \brief Construct an empty cast.
1959  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
1960    : Expr(SC, Empty), BasePathSize(BasePathSize) { }
1961
1962public:
1963  CastKind getCastKind() const { return static_cast<CastKind>(Kind); }
1964  void setCastKind(CastKind K) { Kind = K; }
1965  const char *getCastKindName() const;
1966
1967  Expr *getSubExpr() { return cast<Expr>(Op); }
1968  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1969  void setSubExpr(Expr *E) { Op = E; }
1970
1971  /// \brief Retrieve the cast subexpression as it was written in the source
1972  /// code, looking through any implicit casts or other intermediate nodes
1973  /// introduced by semantic analysis.
1974  Expr *getSubExprAsWritten();
1975  const Expr *getSubExprAsWritten() const {
1976    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
1977  }
1978
1979  typedef CXXBaseSpecifier **path_iterator;
1980  typedef const CXXBaseSpecifier * const *path_const_iterator;
1981  bool path_empty() const { return BasePathSize == 0; }
1982  unsigned path_size() const { return BasePathSize; }
1983  path_iterator path_begin() { return path_buffer(); }
1984  path_iterator path_end() { return path_buffer() + path_size(); }
1985  path_const_iterator path_begin() const { return path_buffer(); }
1986  path_const_iterator path_end() const { return path_buffer() + path_size(); }
1987
1988  void setCastPath(const CXXCastPath &Path);
1989
1990  static bool classof(const Stmt *T) {
1991    return T->getStmtClass() >= firstCastExprConstant &&
1992           T->getStmtClass() <= lastCastExprConstant;
1993  }
1994  static bool classof(const CastExpr *) { return true; }
1995
1996  // Iterators
1997  virtual child_iterator child_begin();
1998  virtual child_iterator child_end();
1999};
2000
2001/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2002/// conversions, which have no direct representation in the original
2003/// source code. For example: converting T[]->T*, void f()->void
2004/// (*f)(), float->double, short->int, etc.
2005///
2006/// In C, implicit casts always produce rvalues. However, in C++, an
2007/// implicit cast whose result is being bound to a reference will be
2008/// an lvalue or xvalue. For example:
2009///
2010/// @code
2011/// class Base { };
2012/// class Derived : public Base { };
2013/// Derived &&ref();
2014/// void f(Derived d) {
2015///   Base& b = d; // initializer is an ImplicitCastExpr
2016///                // to an lvalue of type Base
2017///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2018///                     // to an xvalue of type Base
2019/// }
2020/// @endcode
2021class ImplicitCastExpr : public CastExpr {
2022private:
2023  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2024                   unsigned BasePathLength, ExprValueKind VK)
2025    : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePathLength) {
2026    ValueKind = VK;
2027  }
2028
2029  /// \brief Construct an empty implicit cast.
2030  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2031    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2032
2033public:
2034  enum OnStack_t { OnStack };
2035  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2036                   ExprValueKind VK)
2037    : CastExpr(ImplicitCastExprClass, ty, kind, op, 0) {
2038    ValueKind = VK;
2039  }
2040
2041  static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2042                                  CastKind Kind, Expr *Operand,
2043                                  const CXXCastPath *BasePath,
2044                                  ExprValueKind Cat);
2045
2046  static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2047
2048  virtual SourceRange getSourceRange() const {
2049    return getSubExpr()->getSourceRange();
2050  }
2051
2052  /// getValueKind - The value kind that this cast produces.
2053  ExprValueKind getValueKind() const {
2054    return static_cast<ExprValueKind>(ValueKind);
2055  }
2056
2057  /// setValueKind - Set the value kind this cast produces.
2058  void setValueKind(ExprValueKind Cat) { ValueKind = Cat; }
2059
2060  static bool classof(const Stmt *T) {
2061    return T->getStmtClass() == ImplicitCastExprClass;
2062  }
2063  static bool classof(const ImplicitCastExpr *) { return true; }
2064};
2065
2066/// ExplicitCastExpr - An explicit cast written in the source
2067/// code.
2068///
2069/// This class is effectively an abstract class, because it provides
2070/// the basic representation of an explicitly-written cast without
2071/// specifying which kind of cast (C cast, functional cast, static
2072/// cast, etc.) was written; specific derived classes represent the
2073/// particular style of cast and its location information.
2074///
2075/// Unlike implicit casts, explicit cast nodes have two different
2076/// types: the type that was written into the source code, and the
2077/// actual type of the expression as determined by semantic
2078/// analysis. These types may differ slightly. For example, in C++ one
2079/// can cast to a reference type, which indicates that the resulting
2080/// expression will be an lvalue or xvalue. The reference type, however,
2081/// will not be used as the type of the expression.
2082class ExplicitCastExpr : public CastExpr {
2083  /// TInfo - Source type info for the (written) type
2084  /// this expression is casting to.
2085  TypeSourceInfo *TInfo;
2086
2087protected:
2088  ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind,
2089                   Expr *op, unsigned PathSize, TypeSourceInfo *writtenTy)
2090    : CastExpr(SC, exprTy, kind, op, PathSize), TInfo(writtenTy) {}
2091
2092  /// \brief Construct an empty explicit cast.
2093  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2094    : CastExpr(SC, Shell, PathSize) { }
2095
2096public:
2097  /// getTypeInfoAsWritten - Returns the type source info for the type
2098  /// that this expression is casting to.
2099  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2100  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2101
2102  /// getTypeAsWritten - Returns the type that this expression is
2103  /// casting to, as written in the source code.
2104  QualType getTypeAsWritten() const { return TInfo->getType(); }
2105
2106  static bool classof(const Stmt *T) {
2107     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2108            T->getStmtClass() <= lastExplicitCastExprConstant;
2109  }
2110  static bool classof(const ExplicitCastExpr *) { return true; }
2111};
2112
2113/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2114/// cast in C++ (C++ [expr.cast]), which uses the syntax
2115/// (Type)expr. For example: @c (int)f.
2116class CStyleCastExpr : public ExplicitCastExpr {
2117  SourceLocation LPLoc; // the location of the left paren
2118  SourceLocation RPLoc; // the location of the right paren
2119
2120  CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op,
2121                 unsigned PathSize, TypeSourceInfo *writtenTy,
2122                 SourceLocation l, SourceLocation r)
2123    : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, PathSize,
2124                       writtenTy), LPLoc(l), RPLoc(r) {}
2125
2126  /// \brief Construct an empty C-style explicit cast.
2127  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2128    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2129
2130public:
2131  static CStyleCastExpr *Create(ASTContext &Context, QualType T, CastKind K,
2132                                Expr *Op, const CXXCastPath *BasePath,
2133                                TypeSourceInfo *WrittenTy, SourceLocation L,
2134                                SourceLocation R);
2135
2136  static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2137
2138  SourceLocation getLParenLoc() const { return LPLoc; }
2139  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2140
2141  SourceLocation getRParenLoc() const { return RPLoc; }
2142  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2143
2144  virtual SourceRange getSourceRange() const {
2145    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2146  }
2147  static bool classof(const Stmt *T) {
2148    return T->getStmtClass() == CStyleCastExprClass;
2149  }
2150  static bool classof(const CStyleCastExpr *) { return true; }
2151};
2152
2153/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2154///
2155/// This expression node kind describes a builtin binary operation,
2156/// such as "x + y" for integer values "x" and "y". The operands will
2157/// already have been converted to appropriate types (e.g., by
2158/// performing promotions or conversions).
2159///
2160/// In C++, where operators may be overloaded, a different kind of
2161/// expression node (CXXOperatorCallExpr) is used to express the
2162/// invocation of an overloaded operator with operator syntax. Within
2163/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2164/// used to store an expression "x + y" depends on the subexpressions
2165/// for x and y. If neither x or y is type-dependent, and the "+"
2166/// operator resolves to a built-in operation, BinaryOperator will be
2167/// used to express the computation (x and y may still be
2168/// value-dependent). If either x or y is type-dependent, or if the
2169/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2170/// be used to express the computation.
2171class BinaryOperator : public Expr {
2172public:
2173  typedef BinaryOperatorKind Opcode;
2174
2175private:
2176  unsigned Opc : 6;
2177  SourceLocation OpLoc;
2178
2179  enum { LHS, RHS, END_EXPR };
2180  Stmt* SubExprs[END_EXPR];
2181public:
2182
2183  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2184                 SourceLocation opLoc)
2185    : Expr(BinaryOperatorClass, ResTy,
2186           lhs->isTypeDependent() || rhs->isTypeDependent(),
2187           lhs->isValueDependent() || rhs->isValueDependent()),
2188      Opc(opc), OpLoc(opLoc) {
2189    SubExprs[LHS] = lhs;
2190    SubExprs[RHS] = rhs;
2191    assert(!isCompoundAssignmentOp() &&
2192           "Use ArithAssignBinaryOperator for compound assignments");
2193  }
2194
2195  /// \brief Construct an empty binary operator.
2196  explicit BinaryOperator(EmptyShell Empty)
2197    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2198
2199  SourceLocation getOperatorLoc() const { return OpLoc; }
2200  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2201
2202  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2203  void setOpcode(Opcode O) { Opc = O; }
2204
2205  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2206  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2207  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2208  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2209
2210  virtual SourceRange getSourceRange() const {
2211    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2212  }
2213
2214  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2215  /// corresponds to, e.g. "<<=".
2216  static const char *getOpcodeStr(Opcode Op);
2217
2218  const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2219
2220  /// \brief Retrieve the binary opcode that corresponds to the given
2221  /// overloaded operator.
2222  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2223
2224  /// \brief Retrieve the overloaded operator kind that corresponds to
2225  /// the given binary opcode.
2226  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2227
2228  /// predicates to categorize the respective opcodes.
2229  bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2230  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2231  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2232  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2233  bool isShiftOp() const { return isShiftOp(getOpcode()); }
2234
2235  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2236  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2237
2238  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2239  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2240
2241  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2242  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2243
2244  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2245  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2246
2247  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2248  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2249
2250  bool isAssignmentOp() const { return Opc >= BO_Assign && Opc <= BO_OrAssign; }
2251  bool isCompoundAssignmentOp() const {
2252    return Opc > BO_Assign && Opc <= BO_OrAssign;
2253  }
2254  bool isShiftAssignOp() const {
2255    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2256  }
2257
2258  static bool classof(const Stmt *S) {
2259    return S->getStmtClass() >= firstBinaryOperatorConstant &&
2260           S->getStmtClass() <= lastBinaryOperatorConstant;
2261  }
2262  static bool classof(const BinaryOperator *) { return true; }
2263
2264  // Iterators
2265  virtual child_iterator child_begin();
2266  virtual child_iterator child_end();
2267
2268protected:
2269  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2270                 SourceLocation opLoc, bool dead)
2271    : Expr(CompoundAssignOperatorClass, ResTy,
2272           lhs->isTypeDependent() || rhs->isTypeDependent(),
2273           lhs->isValueDependent() || rhs->isValueDependent()),
2274      Opc(opc), OpLoc(opLoc) {
2275    SubExprs[LHS] = lhs;
2276    SubExprs[RHS] = rhs;
2277  }
2278
2279  BinaryOperator(StmtClass SC, EmptyShell Empty)
2280    : Expr(SC, Empty), Opc(BO_MulAssign) { }
2281};
2282
2283/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2284/// track of the type the operation is performed in.  Due to the semantics of
2285/// these operators, the operands are promoted, the aritmetic performed, an
2286/// implicit conversion back to the result type done, then the assignment takes
2287/// place.  This captures the intermediate type which the computation is done
2288/// in.
2289class CompoundAssignOperator : public BinaryOperator {
2290  QualType ComputationLHSType;
2291  QualType ComputationResultType;
2292public:
2293  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
2294                         QualType ResType, QualType CompLHSType,
2295                         QualType CompResultType,
2296                         SourceLocation OpLoc)
2297    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
2298      ComputationLHSType(CompLHSType),
2299      ComputationResultType(CompResultType) {
2300    assert(isCompoundAssignmentOp() &&
2301           "Only should be used for compound assignments");
2302  }
2303
2304  /// \brief Build an empty compound assignment operator expression.
2305  explicit CompoundAssignOperator(EmptyShell Empty)
2306    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2307
2308  // The two computation types are the type the LHS is converted
2309  // to for the computation and the type of the result; the two are
2310  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2311  QualType getComputationLHSType() const { return ComputationLHSType; }
2312  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2313
2314  QualType getComputationResultType() const { return ComputationResultType; }
2315  void setComputationResultType(QualType T) { ComputationResultType = T; }
2316
2317  static bool classof(const CompoundAssignOperator *) { return true; }
2318  static bool classof(const Stmt *S) {
2319    return S->getStmtClass() == CompoundAssignOperatorClass;
2320  }
2321};
2322
2323/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
2324/// GNU "missing LHS" extension is in use.
2325///
2326class ConditionalOperator : public Expr {
2327  enum { COND, LHS, RHS, END_EXPR };
2328  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2329  SourceLocation QuestionLoc, ColonLoc;
2330public:
2331  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2332                      SourceLocation CLoc, Expr *rhs, QualType t)
2333    : Expr(ConditionalOperatorClass, t,
2334           // FIXME: the type of the conditional operator doesn't
2335           // depend on the type of the conditional, but the standard
2336           // seems to imply that it could. File a bug!
2337           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
2338           (cond->isValueDependent() ||
2339            (lhs && lhs->isValueDependent()) ||
2340            (rhs && rhs->isValueDependent()))),
2341      QuestionLoc(QLoc),
2342      ColonLoc(CLoc) {
2343    SubExprs[COND] = cond;
2344    SubExprs[LHS] = lhs;
2345    SubExprs[RHS] = rhs;
2346  }
2347
2348  /// \brief Build an empty conditional operator.
2349  explicit ConditionalOperator(EmptyShell Empty)
2350    : Expr(ConditionalOperatorClass, Empty) { }
2351
2352  // getCond - Return the expression representing the condition for
2353  //  the ?: operator.
2354  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2355  void setCond(Expr *E) { SubExprs[COND] = E; }
2356
2357  // getTrueExpr - Return the subexpression representing the value of the ?:
2358  //  expression if the condition evaluates to true.  In most cases this value
2359  //  will be the same as getLHS() except a GCC extension allows the left
2360  //  subexpression to be omitted, and instead of the condition be returned.
2361  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
2362  //  is only evaluated once.
2363  Expr *getTrueExpr() const {
2364    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
2365  }
2366
2367  // getTrueExpr - Return the subexpression representing the value of the ?:
2368  // expression if the condition evaluates to false. This is the same as getRHS.
2369  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2370
2371  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
2372  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2373
2374  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2375  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2376
2377  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2378  void setQuestionLoc(SourceLocation L) { QuestionLoc = L; }
2379
2380  SourceLocation getColonLoc() const { return ColonLoc; }
2381  void setColonLoc(SourceLocation L) { ColonLoc = L; }
2382
2383  virtual SourceRange getSourceRange() const {
2384    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2385  }
2386  static bool classof(const Stmt *T) {
2387    return T->getStmtClass() == ConditionalOperatorClass;
2388  }
2389  static bool classof(const ConditionalOperator *) { return true; }
2390
2391  // Iterators
2392  virtual child_iterator child_begin();
2393  virtual child_iterator child_end();
2394};
2395
2396/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2397class AddrLabelExpr : public Expr {
2398  SourceLocation AmpAmpLoc, LabelLoc;
2399  LabelStmt *Label;
2400public:
2401  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
2402                QualType t)
2403    : Expr(AddrLabelExprClass, t, false, false),
2404      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2405
2406  /// \brief Build an empty address of a label expression.
2407  explicit AddrLabelExpr(EmptyShell Empty)
2408    : Expr(AddrLabelExprClass, Empty) { }
2409
2410  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2411  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2412  SourceLocation getLabelLoc() const { return LabelLoc; }
2413  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2414
2415  virtual SourceRange getSourceRange() const {
2416    return SourceRange(AmpAmpLoc, LabelLoc);
2417  }
2418
2419  LabelStmt *getLabel() const { return Label; }
2420  void setLabel(LabelStmt *S) { Label = S; }
2421
2422  static bool classof(const Stmt *T) {
2423    return T->getStmtClass() == AddrLabelExprClass;
2424  }
2425  static bool classof(const AddrLabelExpr *) { return true; }
2426
2427  // Iterators
2428  virtual child_iterator child_begin();
2429  virtual child_iterator child_end();
2430};
2431
2432/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2433/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2434/// takes the value of the last subexpression.
2435class StmtExpr : public Expr {
2436  Stmt *SubStmt;
2437  SourceLocation LParenLoc, RParenLoc;
2438public:
2439  // FIXME: Does type-dependence need to be computed differently?
2440  StmtExpr(CompoundStmt *substmt, QualType T,
2441           SourceLocation lp, SourceLocation rp) :
2442    Expr(StmtExprClass, T, T->isDependentType(), false),
2443    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2444
2445  /// \brief Build an empty statement expression.
2446  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2447
2448  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2449  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2450  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2451
2452  virtual SourceRange getSourceRange() const {
2453    return SourceRange(LParenLoc, RParenLoc);
2454  }
2455
2456  SourceLocation getLParenLoc() const { return LParenLoc; }
2457  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2458  SourceLocation getRParenLoc() const { return RParenLoc; }
2459  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2460
2461  static bool classof(const Stmt *T) {
2462    return T->getStmtClass() == StmtExprClass;
2463  }
2464  static bool classof(const StmtExpr *) { return true; }
2465
2466  // Iterators
2467  virtual child_iterator child_begin();
2468  virtual child_iterator child_end();
2469};
2470
2471/// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
2472/// This AST node represents a function that returns 1 if two *types* (not
2473/// expressions) are compatible. The result of this built-in function can be
2474/// used in integer constant expressions.
2475class TypesCompatibleExpr : public Expr {
2476  TypeSourceInfo *TInfo1;
2477  TypeSourceInfo *TInfo2;
2478  SourceLocation BuiltinLoc, RParenLoc;
2479public:
2480  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
2481                      TypeSourceInfo *tinfo1, TypeSourceInfo *tinfo2,
2482                      SourceLocation RP) :
2483    Expr(TypesCompatibleExprClass, ReturnType, false, false),
2484    TInfo1(tinfo1), TInfo2(tinfo2), BuiltinLoc(BLoc), RParenLoc(RP) {}
2485
2486  /// \brief Build an empty __builtin_type_compatible_p expression.
2487  explicit TypesCompatibleExpr(EmptyShell Empty)
2488    : Expr(TypesCompatibleExprClass, Empty) { }
2489
2490  TypeSourceInfo *getArgTInfo1() const { return TInfo1; }
2491  void setArgTInfo1(TypeSourceInfo *TInfo) { TInfo1 = TInfo; }
2492  TypeSourceInfo *getArgTInfo2() const { return TInfo2; }
2493  void setArgTInfo2(TypeSourceInfo *TInfo) { TInfo2 = TInfo; }
2494
2495  QualType getArgType1() const { return TInfo1->getType(); }
2496  QualType getArgType2() const { return TInfo2->getType(); }
2497
2498  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2499  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2500
2501  SourceLocation getRParenLoc() const { return RParenLoc; }
2502  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2503
2504  virtual SourceRange getSourceRange() const {
2505    return SourceRange(BuiltinLoc, RParenLoc);
2506  }
2507  static bool classof(const Stmt *T) {
2508    return T->getStmtClass() == TypesCompatibleExprClass;
2509  }
2510  static bool classof(const TypesCompatibleExpr *) { return true; }
2511
2512  // Iterators
2513  virtual child_iterator child_begin();
2514  virtual child_iterator child_end();
2515};
2516
2517/// ShuffleVectorExpr - clang-specific builtin-in function
2518/// __builtin_shufflevector.
2519/// This AST node represents a operator that does a constant
2520/// shuffle, similar to LLVM's shufflevector instruction. It takes
2521/// two vectors and a variable number of constant indices,
2522/// and returns the appropriately shuffled vector.
2523class ShuffleVectorExpr : public Expr {
2524  SourceLocation BuiltinLoc, RParenLoc;
2525
2526  // SubExprs - the list of values passed to the __builtin_shufflevector
2527  // function. The first two are vectors, and the rest are constant
2528  // indices.  The number of values in this list is always
2529  // 2+the number of indices in the vector type.
2530  Stmt **SubExprs;
2531  unsigned NumExprs;
2532
2533public:
2534  // FIXME: Can a shufflevector be value-dependent?  Does type-dependence need
2535  // to be computed differently?
2536  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2537                    QualType Type, SourceLocation BLoc,
2538                    SourceLocation RP) :
2539    Expr(ShuffleVectorExprClass, Type, Type->isDependentType(), false),
2540    BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) {
2541
2542    SubExprs = new (C) Stmt*[nexpr];
2543    for (unsigned i = 0; i < nexpr; i++)
2544      SubExprs[i] = args[i];
2545  }
2546
2547  /// \brief Build an empty vector-shuffle expression.
2548  explicit ShuffleVectorExpr(EmptyShell Empty)
2549    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
2550
2551  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2552  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2553
2554  SourceLocation getRParenLoc() const { return RParenLoc; }
2555  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2556
2557  virtual SourceRange getSourceRange() const {
2558    return SourceRange(BuiltinLoc, RParenLoc);
2559  }
2560  static bool classof(const Stmt *T) {
2561    return T->getStmtClass() == ShuffleVectorExprClass;
2562  }
2563  static bool classof(const ShuffleVectorExpr *) { return true; }
2564
2565  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
2566  /// constant expression, the actual arguments passed in, and the function
2567  /// pointers.
2568  unsigned getNumSubExprs() const { return NumExprs; }
2569
2570  /// getExpr - Return the Expr at the specified index.
2571  Expr *getExpr(unsigned Index) {
2572    assert((Index < NumExprs) && "Arg access out of range!");
2573    return cast<Expr>(SubExprs[Index]);
2574  }
2575  const Expr *getExpr(unsigned Index) const {
2576    assert((Index < NumExprs) && "Arg access out of range!");
2577    return cast<Expr>(SubExprs[Index]);
2578  }
2579
2580  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
2581
2582  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
2583    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
2584    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
2585  }
2586
2587  // Iterators
2588  virtual child_iterator child_begin();
2589  virtual child_iterator child_end();
2590};
2591
2592/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
2593/// This AST node is similar to the conditional operator (?:) in C, with
2594/// the following exceptions:
2595/// - the test expression must be a integer constant expression.
2596/// - the expression returned acts like the chosen subexpression in every
2597///   visible way: the type is the same as that of the chosen subexpression,
2598///   and all predicates (whether it's an l-value, whether it's an integer
2599///   constant expression, etc.) return the same result as for the chosen
2600///   sub-expression.
2601class ChooseExpr : public Expr {
2602  enum { COND, LHS, RHS, END_EXPR };
2603  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2604  SourceLocation BuiltinLoc, RParenLoc;
2605public:
2606  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
2607             SourceLocation RP, bool TypeDependent, bool ValueDependent)
2608    : Expr(ChooseExprClass, t, TypeDependent, ValueDependent),
2609      BuiltinLoc(BLoc), RParenLoc(RP) {
2610      SubExprs[COND] = cond;
2611      SubExprs[LHS] = lhs;
2612      SubExprs[RHS] = rhs;
2613    }
2614
2615  /// \brief Build an empty __builtin_choose_expr.
2616  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
2617
2618  /// isConditionTrue - Return whether the condition is true (i.e. not
2619  /// equal to zero).
2620  bool isConditionTrue(ASTContext &C) const;
2621
2622  /// getChosenSubExpr - Return the subexpression chosen according to the
2623  /// condition.
2624  Expr *getChosenSubExpr(ASTContext &C) const {
2625    return isConditionTrue(C) ? getLHS() : getRHS();
2626  }
2627
2628  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2629  void setCond(Expr *E) { SubExprs[COND] = E; }
2630  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2631  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2632  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2633  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2634
2635  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2636  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2637
2638  SourceLocation getRParenLoc() const { return RParenLoc; }
2639  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2640
2641  virtual SourceRange getSourceRange() const {
2642    return SourceRange(BuiltinLoc, RParenLoc);
2643  }
2644  static bool classof(const Stmt *T) {
2645    return T->getStmtClass() == ChooseExprClass;
2646  }
2647  static bool classof(const ChooseExpr *) { return true; }
2648
2649  // Iterators
2650  virtual child_iterator child_begin();
2651  virtual child_iterator child_end();
2652};
2653
2654/// GNUNullExpr - Implements the GNU __null extension, which is a name
2655/// for a null pointer constant that has integral type (e.g., int or
2656/// long) and is the same size and alignment as a pointer. The __null
2657/// extension is typically only used by system headers, which define
2658/// NULL as __null in C++ rather than using 0 (which is an integer
2659/// that may not match the size of a pointer).
2660class GNUNullExpr : public Expr {
2661  /// TokenLoc - The location of the __null keyword.
2662  SourceLocation TokenLoc;
2663
2664public:
2665  GNUNullExpr(QualType Ty, SourceLocation Loc)
2666    : Expr(GNUNullExprClass, Ty, false, false), TokenLoc(Loc) { }
2667
2668  /// \brief Build an empty GNU __null expression.
2669  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
2670
2671  /// getTokenLocation - The location of the __null token.
2672  SourceLocation getTokenLocation() const { return TokenLoc; }
2673  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
2674
2675  virtual SourceRange getSourceRange() const {
2676    return SourceRange(TokenLoc);
2677  }
2678  static bool classof(const Stmt *T) {
2679    return T->getStmtClass() == GNUNullExprClass;
2680  }
2681  static bool classof(const GNUNullExpr *) { return true; }
2682
2683  // Iterators
2684  virtual child_iterator child_begin();
2685  virtual child_iterator child_end();
2686};
2687
2688/// VAArgExpr, used for the builtin function __builtin_va_arg.
2689class VAArgExpr : public Expr {
2690  Stmt *Val;
2691  TypeSourceInfo *TInfo;
2692  SourceLocation BuiltinLoc, RParenLoc;
2693public:
2694  VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
2695            SourceLocation RPLoc, QualType t)
2696    : Expr(VAArgExprClass, t, t->isDependentType(), false),
2697      Val(e), TInfo(TInfo),
2698      BuiltinLoc(BLoc),
2699      RParenLoc(RPLoc) { }
2700
2701  /// \brief Create an empty __builtin_va_arg expression.
2702  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
2703
2704  const Expr *getSubExpr() const { return cast<Expr>(Val); }
2705  Expr *getSubExpr() { return cast<Expr>(Val); }
2706  void setSubExpr(Expr *E) { Val = E; }
2707
2708  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
2709  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
2710
2711  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2712  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2713
2714  SourceLocation getRParenLoc() const { return RParenLoc; }
2715  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2716
2717  virtual SourceRange getSourceRange() const {
2718    return SourceRange(BuiltinLoc, RParenLoc);
2719  }
2720  static bool classof(const Stmt *T) {
2721    return T->getStmtClass() == VAArgExprClass;
2722  }
2723  static bool classof(const VAArgExpr *) { return true; }
2724
2725  // Iterators
2726  virtual child_iterator child_begin();
2727  virtual child_iterator child_end();
2728};
2729
2730/// @brief Describes an C or C++ initializer list.
2731///
2732/// InitListExpr describes an initializer list, which can be used to
2733/// initialize objects of different types, including
2734/// struct/class/union types, arrays, and vectors. For example:
2735///
2736/// @code
2737/// struct foo x = { 1, { 2, 3 } };
2738/// @endcode
2739///
2740/// Prior to semantic analysis, an initializer list will represent the
2741/// initializer list as written by the user, but will have the
2742/// placeholder type "void". This initializer list is called the
2743/// syntactic form of the initializer, and may contain C99 designated
2744/// initializers (represented as DesignatedInitExprs), initializations
2745/// of subobject members without explicit braces, and so on. Clients
2746/// interested in the original syntax of the initializer list should
2747/// use the syntactic form of the initializer list.
2748///
2749/// After semantic analysis, the initializer list will represent the
2750/// semantic form of the initializer, where the initializations of all
2751/// subobjects are made explicit with nested InitListExpr nodes and
2752/// C99 designators have been eliminated by placing the designated
2753/// initializations into the subobject they initialize. Additionally,
2754/// any "holes" in the initialization, where no initializer has been
2755/// specified for a particular subobject, will be replaced with
2756/// implicitly-generated ImplicitValueInitExpr expressions that
2757/// value-initialize the subobjects. Note, however, that the
2758/// initializer lists may still have fewer initializers than there are
2759/// elements to initialize within the object.
2760///
2761/// Given the semantic form of the initializer list, one can retrieve
2762/// the original syntactic form of that initializer list (if it
2763/// exists) using getSyntacticForm(). Since many initializer lists
2764/// have the same syntactic and semantic forms, getSyntacticForm() may
2765/// return NULL, indicating that the current initializer list also
2766/// serves as its syntactic form.
2767class InitListExpr : public Expr {
2768  // FIXME: Eliminate this vector in favor of ASTContext allocation
2769  typedef ASTVector<Stmt *> InitExprsTy;
2770  InitExprsTy InitExprs;
2771  SourceLocation LBraceLoc, RBraceLoc;
2772
2773  /// Contains the initializer list that describes the syntactic form
2774  /// written in the source code.
2775  InitListExpr *SyntacticForm;
2776
2777  /// If this initializer list initializes a union, specifies which
2778  /// field within the union will be initialized.
2779  FieldDecl *UnionFieldInit;
2780
2781  /// Whether this initializer list originally had a GNU array-range
2782  /// designator in it. This is a temporary marker used by CodeGen.
2783  bool HadArrayRangeDesignator;
2784
2785public:
2786  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
2787               Expr **initexprs, unsigned numinits,
2788               SourceLocation rbraceloc);
2789
2790  /// \brief Build an empty initializer list.
2791  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
2792    : Expr(InitListExprClass, Empty), InitExprs(C) { }
2793
2794  unsigned getNumInits() const { return InitExprs.size(); }
2795
2796  const Expr* getInit(unsigned Init) const {
2797    assert(Init < getNumInits() && "Initializer access out of range!");
2798    return cast_or_null<Expr>(InitExprs[Init]);
2799  }
2800
2801  Expr* getInit(unsigned Init) {
2802    assert(Init < getNumInits() && "Initializer access out of range!");
2803    return cast_or_null<Expr>(InitExprs[Init]);
2804  }
2805
2806  void setInit(unsigned Init, Expr *expr) {
2807    assert(Init < getNumInits() && "Initializer access out of range!");
2808    InitExprs[Init] = expr;
2809  }
2810
2811  /// \brief Reserve space for some number of initializers.
2812  void reserveInits(ASTContext &C, unsigned NumInits);
2813
2814  /// @brief Specify the number of initializers
2815  ///
2816  /// If there are more than @p NumInits initializers, the remaining
2817  /// initializers will be destroyed. If there are fewer than @p
2818  /// NumInits initializers, NULL expressions will be added for the
2819  /// unknown initializers.
2820  void resizeInits(ASTContext &Context, unsigned NumInits);
2821
2822  /// @brief Updates the initializer at index @p Init with the new
2823  /// expression @p expr, and returns the old expression at that
2824  /// location.
2825  ///
2826  /// When @p Init is out of range for this initializer list, the
2827  /// initializer list will be extended with NULL expressions to
2828  /// accomodate the new entry.
2829  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
2830
2831  /// \brief If this initializes a union, specifies which field in the
2832  /// union to initialize.
2833  ///
2834  /// Typically, this field is the first named field within the
2835  /// union. However, a designated initializer can specify the
2836  /// initialization of a different field within the union.
2837  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2838  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2839
2840  // Explicit InitListExpr's originate from source code (and have valid source
2841  // locations). Implicit InitListExpr's are created by the semantic analyzer.
2842  bool isExplicit() {
2843    return LBraceLoc.isValid() && RBraceLoc.isValid();
2844  }
2845
2846  SourceLocation getLBraceLoc() const { return LBraceLoc; }
2847  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2848  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2849  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2850
2851  /// @brief Retrieve the initializer list that describes the
2852  /// syntactic form of the initializer.
2853  ///
2854  ///
2855  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2856  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2857
2858  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2859  void sawArrayRangeDesignator(bool ARD = true) {
2860    HadArrayRangeDesignator = ARD;
2861  }
2862
2863  virtual SourceRange getSourceRange() const {
2864    return SourceRange(LBraceLoc, RBraceLoc);
2865  }
2866  static bool classof(const Stmt *T) {
2867    return T->getStmtClass() == InitListExprClass;
2868  }
2869  static bool classof(const InitListExpr *) { return true; }
2870
2871  // Iterators
2872  virtual child_iterator child_begin();
2873  virtual child_iterator child_end();
2874
2875  typedef InitExprsTy::iterator iterator;
2876  typedef InitExprsTy::const_iterator const_iterator;
2877  typedef InitExprsTy::reverse_iterator reverse_iterator;
2878  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
2879
2880  iterator begin() { return InitExprs.begin(); }
2881  const_iterator begin() const { return InitExprs.begin(); }
2882  iterator end() { return InitExprs.end(); }
2883  const_iterator end() const { return InitExprs.end(); }
2884  reverse_iterator rbegin() { return InitExprs.rbegin(); }
2885  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
2886  reverse_iterator rend() { return InitExprs.rend(); }
2887  const_reverse_iterator rend() const { return InitExprs.rend(); }
2888};
2889
2890/// @brief Represents a C99 designated initializer expression.
2891///
2892/// A designated initializer expression (C99 6.7.8) contains one or
2893/// more designators (which can be field designators, array
2894/// designators, or GNU array-range designators) followed by an
2895/// expression that initializes the field or element(s) that the
2896/// designators refer to. For example, given:
2897///
2898/// @code
2899/// struct point {
2900///   double x;
2901///   double y;
2902/// };
2903/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2904/// @endcode
2905///
2906/// The InitListExpr contains three DesignatedInitExprs, the first of
2907/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2908/// designators, one array designator for @c [2] followed by one field
2909/// designator for @c .y. The initalization expression will be 1.0.
2910class DesignatedInitExpr : public Expr {
2911public:
2912  /// \brief Forward declaration of the Designator class.
2913  class Designator;
2914
2915private:
2916  /// The location of the '=' or ':' prior to the actual initializer
2917  /// expression.
2918  SourceLocation EqualOrColonLoc;
2919
2920  /// Whether this designated initializer used the GNU deprecated
2921  /// syntax rather than the C99 '=' syntax.
2922  bool GNUSyntax : 1;
2923
2924  /// The number of designators in this initializer expression.
2925  unsigned NumDesignators : 15;
2926
2927  /// \brief The designators in this designated initialization
2928  /// expression.
2929  Designator *Designators;
2930
2931  /// The number of subexpressions of this initializer expression,
2932  /// which contains both the initializer and any additional
2933  /// expressions used by array and array-range designators.
2934  unsigned NumSubExprs : 16;
2935
2936
2937  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
2938                     const Designator *Designators,
2939                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
2940                     Expr **IndexExprs, unsigned NumIndexExprs,
2941                     Expr *Init);
2942
2943  explicit DesignatedInitExpr(unsigned NumSubExprs)
2944    : Expr(DesignatedInitExprClass, EmptyShell()),
2945      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
2946
2947public:
2948  /// A field designator, e.g., ".x".
2949  struct FieldDesignator {
2950    /// Refers to the field that is being initialized. The low bit
2951    /// of this field determines whether this is actually a pointer
2952    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
2953    /// initially constructed, a field designator will store an
2954    /// IdentifierInfo*. After semantic analysis has resolved that
2955    /// name, the field designator will instead store a FieldDecl*.
2956    uintptr_t NameOrField;
2957
2958    /// The location of the '.' in the designated initializer.
2959    unsigned DotLoc;
2960
2961    /// The location of the field name in the designated initializer.
2962    unsigned FieldLoc;
2963  };
2964
2965  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2966  struct ArrayOrRangeDesignator {
2967    /// Location of the first index expression within the designated
2968    /// initializer expression's list of subexpressions.
2969    unsigned Index;
2970    /// The location of the '[' starting the array range designator.
2971    unsigned LBracketLoc;
2972    /// The location of the ellipsis separating the start and end
2973    /// indices. Only valid for GNU array-range designators.
2974    unsigned EllipsisLoc;
2975    /// The location of the ']' terminating the array range designator.
2976    unsigned RBracketLoc;
2977  };
2978
2979  /// @brief Represents a single C99 designator.
2980  ///
2981  /// @todo This class is infuriatingly similar to clang::Designator,
2982  /// but minor differences (storing indices vs. storing pointers)
2983  /// keep us from reusing it. Try harder, later, to rectify these
2984  /// differences.
2985  class Designator {
2986    /// @brief The kind of designator this describes.
2987    enum {
2988      FieldDesignator,
2989      ArrayDesignator,
2990      ArrayRangeDesignator
2991    } Kind;
2992
2993    union {
2994      /// A field designator, e.g., ".x".
2995      struct FieldDesignator Field;
2996      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2997      struct ArrayOrRangeDesignator ArrayOrRange;
2998    };
2999    friend class DesignatedInitExpr;
3000
3001  public:
3002    Designator() {}
3003
3004    /// @brief Initializes a field designator.
3005    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3006               SourceLocation FieldLoc)
3007      : Kind(FieldDesignator) {
3008      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3009      Field.DotLoc = DotLoc.getRawEncoding();
3010      Field.FieldLoc = FieldLoc.getRawEncoding();
3011    }
3012
3013    /// @brief Initializes an array designator.
3014    Designator(unsigned Index, SourceLocation LBracketLoc,
3015               SourceLocation RBracketLoc)
3016      : Kind(ArrayDesignator) {
3017      ArrayOrRange.Index = Index;
3018      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3019      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3020      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3021    }
3022
3023    /// @brief Initializes a GNU array-range designator.
3024    Designator(unsigned Index, SourceLocation LBracketLoc,
3025               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3026      : Kind(ArrayRangeDesignator) {
3027      ArrayOrRange.Index = Index;
3028      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3029      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3030      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3031    }
3032
3033    bool isFieldDesignator() const { return Kind == FieldDesignator; }
3034    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3035    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3036
3037    IdentifierInfo * getFieldName();
3038
3039    FieldDecl *getField() {
3040      assert(Kind == FieldDesignator && "Only valid on a field designator");
3041      if (Field.NameOrField & 0x01)
3042        return 0;
3043      else
3044        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3045    }
3046
3047    void setField(FieldDecl *FD) {
3048      assert(Kind == FieldDesignator && "Only valid on a field designator");
3049      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3050    }
3051
3052    SourceLocation getDotLoc() const {
3053      assert(Kind == FieldDesignator && "Only valid on a field designator");
3054      return SourceLocation::getFromRawEncoding(Field.DotLoc);
3055    }
3056
3057    SourceLocation getFieldLoc() const {
3058      assert(Kind == FieldDesignator && "Only valid on a field designator");
3059      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3060    }
3061
3062    SourceLocation getLBracketLoc() const {
3063      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3064             "Only valid on an array or array-range designator");
3065      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3066    }
3067
3068    SourceLocation getRBracketLoc() const {
3069      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3070             "Only valid on an array or array-range designator");
3071      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3072    }
3073
3074    SourceLocation getEllipsisLoc() const {
3075      assert(Kind == ArrayRangeDesignator &&
3076             "Only valid on an array-range designator");
3077      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3078    }
3079
3080    unsigned getFirstExprIndex() const {
3081      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3082             "Only valid on an array or array-range designator");
3083      return ArrayOrRange.Index;
3084    }
3085
3086    SourceLocation getStartLocation() const {
3087      if (Kind == FieldDesignator)
3088        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3089      else
3090        return getLBracketLoc();
3091    }
3092  };
3093
3094  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3095                                    unsigned NumDesignators,
3096                                    Expr **IndexExprs, unsigned NumIndexExprs,
3097                                    SourceLocation EqualOrColonLoc,
3098                                    bool GNUSyntax, Expr *Init);
3099
3100  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3101
3102  /// @brief Returns the number of designators in this initializer.
3103  unsigned size() const { return NumDesignators; }
3104
3105  // Iterator access to the designators.
3106  typedef Designator* designators_iterator;
3107  designators_iterator designators_begin() { return Designators; }
3108  designators_iterator designators_end() {
3109    return Designators + NumDesignators;
3110  }
3111
3112  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3113
3114  void setDesignators(ASTContext &C, const Designator *Desigs,
3115                      unsigned NumDesigs);
3116
3117  Expr *getArrayIndex(const Designator& D);
3118  Expr *getArrayRangeStart(const Designator& D);
3119  Expr *getArrayRangeEnd(const Designator& D);
3120
3121  /// @brief Retrieve the location of the '=' that precedes the
3122  /// initializer value itself, if present.
3123  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3124  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3125
3126  /// @brief Determines whether this designated initializer used the
3127  /// deprecated GNU syntax for designated initializers.
3128  bool usesGNUSyntax() const { return GNUSyntax; }
3129  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3130
3131  /// @brief Retrieve the initializer value.
3132  Expr *getInit() const {
3133    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3134  }
3135
3136  void setInit(Expr *init) {
3137    *child_begin() = init;
3138  }
3139
3140  /// \brief Retrieve the total number of subexpressions in this
3141  /// designated initializer expression, including the actual
3142  /// initialized value and any expressions that occur within array
3143  /// and array-range designators.
3144  unsigned getNumSubExprs() const { return NumSubExprs; }
3145
3146  Expr *getSubExpr(unsigned Idx) {
3147    assert(Idx < NumSubExprs && "Subscript out of range");
3148    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3149    Ptr += sizeof(DesignatedInitExpr);
3150    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3151  }
3152
3153  void setSubExpr(unsigned Idx, Expr *E) {
3154    assert(Idx < NumSubExprs && "Subscript out of range");
3155    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3156    Ptr += sizeof(DesignatedInitExpr);
3157    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3158  }
3159
3160  /// \brief Replaces the designator at index @p Idx with the series
3161  /// of designators in [First, Last).
3162  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3163                        const Designator *Last);
3164
3165  virtual SourceRange getSourceRange() const;
3166
3167  static bool classof(const Stmt *T) {
3168    return T->getStmtClass() == DesignatedInitExprClass;
3169  }
3170  static bool classof(const DesignatedInitExpr *) { return true; }
3171
3172  // Iterators
3173  virtual child_iterator child_begin();
3174  virtual child_iterator child_end();
3175};
3176
3177/// \brief Represents an implicitly-generated value initialization of
3178/// an object of a given type.
3179///
3180/// Implicit value initializations occur within semantic initializer
3181/// list expressions (InitListExpr) as placeholders for subobject
3182/// initializations not explicitly specified by the user.
3183///
3184/// \see InitListExpr
3185class ImplicitValueInitExpr : public Expr {
3186public:
3187  explicit ImplicitValueInitExpr(QualType ty)
3188    : Expr(ImplicitValueInitExprClass, ty, false, false) { }
3189
3190  /// \brief Construct an empty implicit value initialization.
3191  explicit ImplicitValueInitExpr(EmptyShell Empty)
3192    : Expr(ImplicitValueInitExprClass, Empty) { }
3193
3194  static bool classof(const Stmt *T) {
3195    return T->getStmtClass() == ImplicitValueInitExprClass;
3196  }
3197  static bool classof(const ImplicitValueInitExpr *) { return true; }
3198
3199  virtual SourceRange getSourceRange() const {
3200    return SourceRange();
3201  }
3202
3203  // Iterators
3204  virtual child_iterator child_begin();
3205  virtual child_iterator child_end();
3206};
3207
3208
3209class ParenListExpr : public Expr {
3210  Stmt **Exprs;
3211  unsigned NumExprs;
3212  SourceLocation LParenLoc, RParenLoc;
3213
3214public:
3215  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3216                unsigned numexprs, SourceLocation rparenloc);
3217
3218  /// \brief Build an empty paren list.
3219  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3220
3221  unsigned getNumExprs() const { return NumExprs; }
3222
3223  const Expr* getExpr(unsigned Init) const {
3224    assert(Init < getNumExprs() && "Initializer access out of range!");
3225    return cast_or_null<Expr>(Exprs[Init]);
3226  }
3227
3228  Expr* getExpr(unsigned Init) {
3229    assert(Init < getNumExprs() && "Initializer access out of range!");
3230    return cast_or_null<Expr>(Exprs[Init]);
3231  }
3232
3233  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3234
3235  SourceLocation getLParenLoc() const { return LParenLoc; }
3236  SourceLocation getRParenLoc() const { return RParenLoc; }
3237
3238  virtual SourceRange getSourceRange() const {
3239    return SourceRange(LParenLoc, RParenLoc);
3240  }
3241  static bool classof(const Stmt *T) {
3242    return T->getStmtClass() == ParenListExprClass;
3243  }
3244  static bool classof(const ParenListExpr *) { return true; }
3245
3246  // Iterators
3247  virtual child_iterator child_begin();
3248  virtual child_iterator child_end();
3249
3250  friend class ASTStmtReader;
3251  friend class ASTStmtWriter;
3252};
3253
3254
3255//===----------------------------------------------------------------------===//
3256// Clang Extensions
3257//===----------------------------------------------------------------------===//
3258
3259
3260/// ExtVectorElementExpr - This represents access to specific elements of a
3261/// vector, and may occur on the left hand side or right hand side.  For example
3262/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3263///
3264/// Note that the base may have either vector or pointer to vector type, just
3265/// like a struct field reference.
3266///
3267class ExtVectorElementExpr : public Expr {
3268  Stmt *Base;
3269  IdentifierInfo *Accessor;
3270  SourceLocation AccessorLoc;
3271public:
3272  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
3273                       SourceLocation loc)
3274    : Expr(ExtVectorElementExprClass, ty, base->isTypeDependent(),
3275           base->isValueDependent()),
3276      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3277
3278  /// \brief Build an empty vector element expression.
3279  explicit ExtVectorElementExpr(EmptyShell Empty)
3280    : Expr(ExtVectorElementExprClass, Empty) { }
3281
3282  const Expr *getBase() const { return cast<Expr>(Base); }
3283  Expr *getBase() { return cast<Expr>(Base); }
3284  void setBase(Expr *E) { Base = E; }
3285
3286  IdentifierInfo &getAccessor() const { return *Accessor; }
3287  void setAccessor(IdentifierInfo *II) { Accessor = II; }
3288
3289  SourceLocation getAccessorLoc() const { return AccessorLoc; }
3290  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3291
3292  /// getNumElements - Get the number of components being selected.
3293  unsigned getNumElements() const;
3294
3295  /// containsDuplicateElements - Return true if any element access is
3296  /// repeated.
3297  bool containsDuplicateElements() const;
3298
3299  /// getEncodedElementAccess - Encode the elements accessed into an llvm
3300  /// aggregate Constant of ConstantInt(s).
3301  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3302
3303  virtual SourceRange getSourceRange() const {
3304    return SourceRange(getBase()->getLocStart(), AccessorLoc);
3305  }
3306
3307  /// isArrow - Return true if the base expression is a pointer to vector,
3308  /// return false if the base expression is a vector.
3309  bool isArrow() const;
3310
3311  static bool classof(const Stmt *T) {
3312    return T->getStmtClass() == ExtVectorElementExprClass;
3313  }
3314  static bool classof(const ExtVectorElementExpr *) { return true; }
3315
3316  // Iterators
3317  virtual child_iterator child_begin();
3318  virtual child_iterator child_end();
3319};
3320
3321
3322/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3323/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3324class BlockExpr : public Expr {
3325protected:
3326  BlockDecl *TheBlock;
3327  bool HasBlockDeclRefExprs;
3328public:
3329  BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
3330    : Expr(BlockExprClass, ty, ty->isDependentType(), false),
3331      TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
3332
3333  /// \brief Build an empty block expression.
3334  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3335
3336  const BlockDecl *getBlockDecl() const { return TheBlock; }
3337  BlockDecl *getBlockDecl() { return TheBlock; }
3338  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3339
3340  // Convenience functions for probing the underlying BlockDecl.
3341  SourceLocation getCaretLocation() const;
3342  const Stmt *getBody() const;
3343  Stmt *getBody();
3344
3345  virtual SourceRange getSourceRange() const {
3346    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
3347  }
3348
3349  /// getFunctionType - Return the underlying function type for this block.
3350  const FunctionType *getFunctionType() const;
3351
3352  /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
3353  /// inside of the block that reference values outside the block.
3354  bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
3355  void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
3356
3357  static bool classof(const Stmt *T) {
3358    return T->getStmtClass() == BlockExprClass;
3359  }
3360  static bool classof(const BlockExpr *) { return true; }
3361
3362  // Iterators
3363  virtual child_iterator child_begin();
3364  virtual child_iterator child_end();
3365};
3366
3367/// BlockDeclRefExpr - A reference to a declared variable, function,
3368/// enum, etc.
3369class BlockDeclRefExpr : public Expr {
3370  ValueDecl *D;
3371  SourceLocation Loc;
3372  bool IsByRef : 1;
3373  bool ConstQualAdded : 1;
3374  Stmt *CopyConstructorVal;
3375public:
3376  // FIXME: Fix type/value dependence!
3377  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
3378                   bool constAdded = false,
3379                   Stmt *copyConstructorVal = 0)
3380  : Expr(BlockDeclRefExprClass, t, (!t.isNull() && t->isDependentType()),false),
3381    D(d), Loc(l), IsByRef(ByRef),
3382    ConstQualAdded(constAdded),  CopyConstructorVal(copyConstructorVal) {}
3383
3384  // \brief Build an empty reference to a declared variable in a
3385  // block.
3386  explicit BlockDeclRefExpr(EmptyShell Empty)
3387    : Expr(BlockDeclRefExprClass, Empty) { }
3388
3389  ValueDecl *getDecl() { return D; }
3390  const ValueDecl *getDecl() const { return D; }
3391  void setDecl(ValueDecl *VD) { D = VD; }
3392
3393  SourceLocation getLocation() const { return Loc; }
3394  void setLocation(SourceLocation L) { Loc = L; }
3395
3396  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
3397
3398  bool isByRef() const { return IsByRef; }
3399  void setByRef(bool BR) { IsByRef = BR; }
3400
3401  bool isConstQualAdded() const { return ConstQualAdded; }
3402  void setConstQualAdded(bool C) { ConstQualAdded = C; }
3403
3404  const Expr *getCopyConstructorExpr() const
3405    { return cast_or_null<Expr>(CopyConstructorVal); }
3406  Expr *getCopyConstructorExpr()
3407    { return cast_or_null<Expr>(CopyConstructorVal); }
3408  void setCopyConstructorExpr(Expr *E) { CopyConstructorVal = E; }
3409
3410  static bool classof(const Stmt *T) {
3411    return T->getStmtClass() == BlockDeclRefExprClass;
3412  }
3413  static bool classof(const BlockDeclRefExpr *) { return true; }
3414
3415  // Iterators
3416  virtual child_iterator child_begin();
3417  virtual child_iterator child_end();
3418};
3419
3420}  // end namespace clang
3421
3422#endif
3423