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