1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Expr interface and subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_EXPR_H
15 #define LLVM_CLANG_AST_EXPR_H
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/ASTVector.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclAccessPair.h"
21 #include "clang/AST/OperationKinds.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/TypeTraits.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APSInt.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Support/Compiler.h"
37 class CXXBaseSpecifier;
38 class CXXMemberCallExpr;
39 class CXXOperatorCallExpr;
43 class MaterializeTemporaryExpr;
45 class ObjCPropertyRefExpr;
46 class OpaqueValueExpr;
51 /// \brief A simple array of base specifiers.
52 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
54 /// \brief An adjustment to be made to the temporary created when emitting a
55 /// reference binding, which accesses a particular subobject of that temporary.
56 struct SubobjectAdjustment {
58 DerivedToBaseAdjustment,
60 MemberPointerAdjustment
65 const CastExpr *BasePath;
66 const CXXRecordDecl *DerivedClass;
70 const MemberPointerType *MPT;
75 struct DTB DerivedToBase;
80 SubobjectAdjustment(const CastExpr *BasePath,
81 const CXXRecordDecl *DerivedClass)
82 : Kind(DerivedToBaseAdjustment) {
83 DerivedToBase.BasePath = BasePath;
84 DerivedToBase.DerivedClass = DerivedClass;
87 SubobjectAdjustment(FieldDecl *Field)
88 : Kind(FieldAdjustment) {
92 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
93 : Kind(MemberPointerAdjustment) {
99 /// Expr - This represents one expression. Note that Expr's are subclasses of
100 /// Stmt. This allows an expression to be transparently used any place a Stmt
103 class Expr : public Stmt {
107 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
108 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
111 ExprBits.TypeDependent = TD;
112 ExprBits.ValueDependent = VD;
113 ExprBits.InstantiationDependent = ID;
114 ExprBits.ValueKind = VK;
115 ExprBits.ObjectKind = OK;
116 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
120 /// \brief Construct an empty expression.
121 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
124 QualType getType() const { return TR; }
125 void setType(QualType t) {
126 // In C++, the type of an expression is always adjusted so that it
127 // will not have reference type an expression will never have
128 // reference type (C++ [expr]p6). Use
129 // QualType::getNonReferenceType() to retrieve the non-reference
130 // type. Additionally, inspect Expr::isLvalue to determine whether
131 // an expression that is adjusted in this manner should be
132 // considered an lvalue.
133 assert((t.isNull() || !t->isReferenceType()) &&
134 "Expressions can't have reference type");
139 /// isValueDependent - Determines whether this expression is
140 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
141 /// array bound of "Chars" in the following example is
144 /// template<int Size, char (&Chars)[Size]> struct meta_string;
146 bool isValueDependent() const { return ExprBits.ValueDependent; }
148 /// \brief Set whether this expression is value-dependent or not.
149 void setValueDependent(bool VD) {
150 ExprBits.ValueDependent = VD;
152 ExprBits.InstantiationDependent = true;
155 /// isTypeDependent - Determines whether this expression is
156 /// type-dependent (C++ [temp.dep.expr]), which means that its type
157 /// could change from one template instantiation to the next. For
158 /// example, the expressions "x" and "x + y" are type-dependent in
159 /// the following code, but "y" is not type-dependent:
161 /// template<typename T>
162 /// void add(T x, int y) {
166 bool isTypeDependent() const { return ExprBits.TypeDependent; }
168 /// \brief Set whether this expression is type-dependent or not.
169 void setTypeDependent(bool TD) {
170 ExprBits.TypeDependent = TD;
172 ExprBits.InstantiationDependent = true;
175 /// \brief Whether this expression is instantiation-dependent, meaning that
176 /// it depends in some way on a template parameter, even if neither its type
177 /// nor (constant) value can change due to the template instantiation.
179 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
180 /// instantiation-dependent (since it involves a template parameter \c T), but
181 /// is neither type- nor value-dependent, since the type of the inner
182 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
183 /// \c sizeof is known.
186 /// template<typename T>
187 /// void f(T x, T y) {
188 /// sizeof(sizeof(T() + T());
192 bool isInstantiationDependent() const {
193 return ExprBits.InstantiationDependent;
196 /// \brief Set whether this expression is instantiation-dependent or not.
197 void setInstantiationDependent(bool ID) {
198 ExprBits.InstantiationDependent = ID;
201 /// \brief Whether this expression contains an unexpanded parameter
202 /// pack (for C++11 variadic templates).
204 /// Given the following function template:
207 /// template<typename F, typename ...Types>
208 /// void forward(const F &f, Types &&...args) {
209 /// f(static_cast<Types&&>(args)...);
213 /// The expressions \c args and \c static_cast<Types&&>(args) both
214 /// contain parameter packs.
215 bool containsUnexpandedParameterPack() const {
216 return ExprBits.ContainsUnexpandedParameterPack;
219 /// \brief Set the bit that describes whether this expression
220 /// contains an unexpanded parameter pack.
221 void setContainsUnexpandedParameterPack(bool PP = true) {
222 ExprBits.ContainsUnexpandedParameterPack = PP;
225 /// getExprLoc - Return the preferred location for the arrow when diagnosing
226 /// a problem with a generic expression.
227 SourceLocation getExprLoc() const LLVM_READONLY;
229 /// isUnusedResultAWarning - Return true if this immediate expression should
230 /// be warned about if the result is unused. If so, fill in expr, location,
231 /// and ranges with expr to warn on and source locations/ranges appropriate
233 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
234 SourceRange &R1, SourceRange &R2,
235 ASTContext &Ctx) const;
237 /// isLValue - True if this expression is an "l-value" according to
238 /// the rules of the current language. C and C++ give somewhat
239 /// different rules for this concept, but in general, the result of
240 /// an l-value expression identifies a specific object whereas the
241 /// result of an r-value expression is a value detached from any
242 /// specific storage.
244 /// C++11 divides the concept of "r-value" into pure r-values
245 /// ("pr-values") and so-called expiring values ("x-values"), which
246 /// identify specific objects that can be safely cannibalized for
247 /// their resources. This is an unfortunate abuse of terminology on
248 /// the part of the C++ committee. In Clang, when we say "r-value",
249 /// we generally mean a pr-value.
250 bool isLValue() const { return getValueKind() == VK_LValue; }
251 bool isRValue() const { return getValueKind() == VK_RValue; }
252 bool isXValue() const { return getValueKind() == VK_XValue; }
253 bool isGLValue() const { return getValueKind() != VK_RValue; }
255 enum LValueClassification {
258 LV_IncompleteVoidType,
259 LV_DuplicateVectorComponents,
260 LV_InvalidExpression,
261 LV_InvalidMessageExpression,
263 LV_SubObjCPropertySetting,
267 /// Reasons why an expression might not be an l-value.
268 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
270 enum isModifiableLvalueResult {
273 MLV_IncompleteVoidType,
274 MLV_DuplicateVectorComponents,
275 MLV_InvalidExpression,
276 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
280 MLV_NoSetterProperty,
282 MLV_SubObjCPropertySetting,
283 MLV_InvalidMessageExpression,
287 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
288 /// does not have an incomplete type, does not have a const-qualified type,
289 /// and if it is a structure or union, does not have any member (including,
290 /// recursively, any member or element of all contained aggregates or unions)
291 /// with a const-qualified type.
293 /// \param Loc [in,out] - A source location which *may* be filled
294 /// in with the location of the expression making this a
295 /// non-modifiable lvalue, if specified.
296 isModifiableLvalueResult
297 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
299 /// \brief The return type of classify(). Represents the C++11 expression
301 class Classification {
303 /// \brief The various classification results. Most of these mean prvalue.
307 CL_Function, // Functions cannot be lvalues in C.
308 CL_Void, // Void cannot be an lvalue in C.
309 CL_AddressableVoid, // Void expression whose address can be taken in C.
310 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
311 CL_MemberFunction, // An expression referring to a member function
312 CL_SubObjCPropertySetting,
313 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
314 CL_ArrayTemporary, // A temporary of array type.
315 CL_ObjCMessageRValue, // ObjC message is an rvalue
316 CL_PRValue // A prvalue for any other reason, of any other type
318 /// \brief The results of modification testing.
319 enum ModifiableType {
320 CM_Untested, // testModifiable was false.
322 CM_RValue, // Not modifiable because it's an rvalue
323 CM_Function, // Not modifiable because it's a function; C++ only
324 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
325 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
335 unsigned short Modifiable;
337 explicit Classification(Kinds k, ModifiableType m)
338 : Kind(k), Modifiable(m)
344 Kinds getKind() const { return static_cast<Kinds>(Kind); }
345 ModifiableType getModifiable() const {
346 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
347 return static_cast<ModifiableType>(Modifiable);
349 bool isLValue() const { return Kind == CL_LValue; }
350 bool isXValue() const { return Kind == CL_XValue; }
351 bool isGLValue() const { return Kind <= CL_XValue; }
352 bool isPRValue() const { return Kind >= CL_Function; }
353 bool isRValue() const { return Kind >= CL_XValue; }
354 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
356 /// \brief Create a simple, modifiably lvalue
357 static Classification makeSimpleLValue() {
358 return Classification(CL_LValue, CM_Modifiable);
362 /// \brief Classify - Classify this expression according to the C++11
363 /// expression taxonomy.
365 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
366 /// old lvalue vs rvalue. This function determines the type of expression this
367 /// is. There are three expression types:
368 /// - lvalues are classical lvalues as in C++03.
369 /// - prvalues are equivalent to rvalues in C++03.
370 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
371 /// function returning an rvalue reference.
372 /// lvalues and xvalues are collectively referred to as glvalues, while
373 /// prvalues and xvalues together form rvalues.
374 Classification Classify(ASTContext &Ctx) const {
375 return ClassifyImpl(Ctx, nullptr);
378 /// \brief ClassifyModifiable - Classify this expression according to the
379 /// C++11 expression taxonomy, and see if it is valid on the left side
380 /// of an assignment.
382 /// This function extends classify in that it also tests whether the
383 /// expression is modifiable (C99 6.3.2.1p1).
384 /// \param Loc A source location that might be filled with a relevant location
385 /// if the expression is not modifiable.
386 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
387 return ClassifyImpl(Ctx, &Loc);
390 /// getValueKindForType - Given a formal return or parameter type,
391 /// give its value kind.
392 static ExprValueKind getValueKindForType(QualType T) {
393 if (const ReferenceType *RT = T->getAs<ReferenceType>())
394 return (isa<LValueReferenceType>(RT)
396 : (RT->getPointeeType()->isFunctionType()
397 ? VK_LValue : VK_XValue));
401 /// getValueKind - The value kind that this expression produces.
402 ExprValueKind getValueKind() const {
403 return static_cast<ExprValueKind>(ExprBits.ValueKind);
406 /// getObjectKind - The object kind that this expression produces.
407 /// Object kinds are meaningful only for expressions that yield an
408 /// l-value or x-value.
409 ExprObjectKind getObjectKind() const {
410 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
413 bool isOrdinaryOrBitFieldObject() const {
414 ExprObjectKind OK = getObjectKind();
415 return (OK == OK_Ordinary || OK == OK_BitField);
418 /// setValueKind - Set the value kind produced by this expression.
419 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
421 /// setObjectKind - Set the object kind produced by this expression.
422 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
425 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
429 /// \brief Returns true if this expression is a gl-value that
430 /// potentially refers to a bit-field.
432 /// In C++, whether a gl-value refers to a bitfield is essentially
433 /// an aspect of the value-kind type system.
434 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
436 /// \brief If this expression refers to a bit-field, retrieve the
437 /// declaration of that bit-field.
439 /// Note that this returns a non-null pointer in subtly different
440 /// places than refersToBitField returns true. In particular, this can
441 /// return a non-null pointer even for r-values loaded from
442 /// bit-fields, but it will return null for a conditional bit-field.
443 FieldDecl *getSourceBitField();
445 const FieldDecl *getSourceBitField() const {
446 return const_cast<Expr*>(this)->getSourceBitField();
449 /// \brief If this expression is an l-value for an Objective C
450 /// property, find the underlying property reference expression.
451 const ObjCPropertyRefExpr *getObjCProperty() const;
453 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
454 bool isObjCSelfExpr() const;
456 /// \brief Returns whether this expression refers to a vector element.
457 bool refersToVectorElement() const;
459 /// \brief Returns whether this expression has a placeholder type.
460 bool hasPlaceholderType() const {
461 return getType()->isPlaceholderType();
464 /// \brief Returns whether this expression has a specific placeholder type.
465 bool hasPlaceholderType(BuiltinType::Kind K) const {
466 assert(BuiltinType::isPlaceholderTypeKind(K));
467 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
468 return BT->getKind() == K;
472 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
473 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
474 /// but also int expressions which are produced by things like comparisons in
476 bool isKnownToHaveBooleanValue() const;
478 /// isIntegerConstantExpr - Return true if this expression is a valid integer
479 /// constant expression, and, if so, return its value in Result. If not a
480 /// valid i-c-e, return false and fill in Loc (if specified) with the location
481 /// of the invalid expression.
483 /// Note: This does not perform the implicit conversions required by C++11
485 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
486 SourceLocation *Loc = nullptr,
487 bool isEvaluated = true) const;
488 bool isIntegerConstantExpr(const ASTContext &Ctx,
489 SourceLocation *Loc = nullptr) const;
491 /// isCXX98IntegralConstantExpr - Return true if this expression is an
492 /// integral constant expression in C++98. Can only be used in C++.
493 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
495 /// isCXX11ConstantExpr - Return true if this expression is a constant
496 /// expression in C++11. Can only be used in C++.
498 /// Note: This does not perform the implicit conversions required by C++11
500 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
501 SourceLocation *Loc = nullptr) const;
503 /// isPotentialConstantExpr - Return true if this function's definition
504 /// might be usable in a constant expression in C++11, if it were marked
505 /// constexpr. Return false if the function can never produce a constant
506 /// expression, along with diagnostics describing why not.
507 static bool isPotentialConstantExpr(const FunctionDecl *FD,
509 PartialDiagnosticAt> &Diags);
511 /// isPotentialConstantExprUnevaluted - Return true if this expression might
512 /// be usable in a constant expression in C++11 in an unevaluated context, if
513 /// it were in function FD marked constexpr. Return false if the function can
514 /// never produce a constant expression, along with diagnostics describing
516 static bool isPotentialConstantExprUnevaluated(Expr *E,
517 const FunctionDecl *FD,
519 PartialDiagnosticAt> &Diags);
521 /// isConstantInitializer - Returns true if this expression can be emitted to
522 /// IR as a constant, and thus can be used as a constant initializer in C.
523 /// If this expression is not constant and Culprit is non-null,
524 /// it is used to store the address of first non constant expr.
525 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
526 const Expr **Culprit = nullptr) const;
528 /// EvalStatus is a struct with detailed info about an evaluation in progress.
530 /// HasSideEffects - Whether the evaluated expression has side effects.
531 /// For example, (f() && 0) can be folded, but it still has side effects.
534 /// Diag - If this is non-null, it will be filled in with a stack of notes
535 /// indicating why evaluation failed (or why it failed to produce a constant
537 /// If the expression is unfoldable, the notes will indicate why it's not
538 /// foldable. If the expression is foldable, but not a constant expression,
539 /// the notes will describes why it isn't a constant expression. If the
540 /// expression *is* a constant expression, no notes will be produced.
541 SmallVectorImpl<PartialDiagnosticAt> *Diag;
543 EvalStatus() : HasSideEffects(false), Diag(nullptr) {}
545 // hasSideEffects - Return true if the evaluated expression has
547 bool hasSideEffects() const {
548 return HasSideEffects;
552 /// EvalResult is a struct with detailed info about an evaluated expression.
553 struct EvalResult : EvalStatus {
554 /// Val - This is the value the expression can be folded to.
557 // isGlobalLValue - Return true if the evaluated lvalue expression
559 bool isGlobalLValue() const;
562 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
563 /// an rvalue using any crazy technique (that has nothing to do with language
564 /// standards) that we want to, even if the expression has side-effects. If
565 /// this function returns true, it returns the folded constant in Result. If
566 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
568 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
570 /// EvaluateAsBooleanCondition - Return true if this is a constant
571 /// which we we can fold and convert to a boolean condition using
572 /// any crazy technique that we want to, even if the expression has
574 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
576 enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects };
578 /// EvaluateAsInt - Return true if this is a constant which we can fold and
579 /// convert to an integer, using any crazy technique that we want to.
580 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
581 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
583 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
584 /// constant folded without side-effects, but discard the result.
585 bool isEvaluatable(const ASTContext &Ctx) const;
587 /// HasSideEffects - This routine returns true for all those expressions
588 /// which have any effect other than producing a value. Example is a function
589 /// call, volatile variable read, or throwing an exception.
590 bool HasSideEffects(const ASTContext &Ctx) const;
592 /// \brief Determine whether this expression involves a call to any function
593 /// that is not trivial.
594 bool hasNonTrivialCall(ASTContext &Ctx);
596 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
597 /// integer. This must be called on an expression that constant folds to an
599 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
600 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
602 void EvaluateForOverflow(const ASTContext &Ctx) const;
604 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
605 /// lvalue with link time known address, with no side-effects.
606 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
608 /// EvaluateAsInitializer - Evaluate an expression as if it were the
609 /// initializer of the given declaration. Returns true if the initializer
610 /// can be folded to a constant, and produces any relevant notes. In C++11,
611 /// notes will be produced if the expression is not a constant expression.
612 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
614 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
616 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
617 /// of a call to the given function with the given arguments, inside an
618 /// unevaluated context. Returns true if the expression could be folded to a
620 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
621 const FunctionDecl *Callee,
622 ArrayRef<const Expr*> Args) const;
624 /// \brief Enumeration used to describe the kind of Null pointer constant
625 /// returned from \c isNullPointerConstant().
626 enum NullPointerConstantKind {
627 /// \brief Expression is not a Null pointer constant.
630 /// \brief Expression is a Null pointer constant built from a zero integer
631 /// expression that is not a simple, possibly parenthesized, zero literal.
632 /// C++ Core Issue 903 will classify these expressions as "not pointers"
633 /// once it is adopted.
634 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
637 /// \brief Expression is a Null pointer constant built from a literal zero.
640 /// \brief Expression is a C++11 nullptr.
643 /// \brief Expression is a GNU-style __null constant.
647 /// \brief Enumeration used to describe how \c isNullPointerConstant()
648 /// should cope with value-dependent expressions.
649 enum NullPointerConstantValueDependence {
650 /// \brief Specifies that the expression should never be value-dependent.
651 NPC_NeverValueDependent = 0,
653 /// \brief Specifies that a value-dependent expression of integral or
654 /// dependent type should be considered a null pointer constant.
655 NPC_ValueDependentIsNull,
657 /// \brief Specifies that a value-dependent expression should be considered
658 /// to never be a null pointer constant.
659 NPC_ValueDependentIsNotNull
662 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
663 /// a Null pointer constant. The return value can further distinguish the
664 /// kind of NULL pointer constant that was detected.
665 NullPointerConstantKind isNullPointerConstant(
667 NullPointerConstantValueDependence NPC) const;
669 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
671 bool isOBJCGCCandidate(ASTContext &Ctx) const;
673 /// \brief Returns true if this expression is a bound member function.
674 bool isBoundMemberFunction(ASTContext &Ctx) const;
676 /// \brief Given an expression of bound-member type, find the type
677 /// of the member. Returns null if this is an *overloaded* bound
678 /// member expression.
679 static QualType findBoundMemberType(const Expr *expr);
681 /// IgnoreImpCasts - Skip past any implicit casts which might
682 /// surround this expression. Only skips ImplicitCastExprs.
683 Expr *IgnoreImpCasts() LLVM_READONLY;
685 /// IgnoreImplicit - Skip past any implicit AST nodes which might
686 /// surround this expression.
687 Expr *IgnoreImplicit() LLVM_READONLY {
688 return cast<Expr>(Stmt::IgnoreImplicit());
691 const Expr *IgnoreImplicit() const LLVM_READONLY {
692 return const_cast<Expr*>(this)->IgnoreImplicit();
695 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
696 /// its subexpression. If that subexpression is also a ParenExpr,
697 /// then this method recursively returns its subexpression, and so forth.
698 /// Otherwise, the method returns the current Expr.
699 Expr *IgnoreParens() LLVM_READONLY;
701 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
702 /// or CastExprs, returning their operand.
703 Expr *IgnoreParenCasts() LLVM_READONLY;
705 /// Ignore casts. Strip off any CastExprs, returning their operand.
706 Expr *IgnoreCasts() LLVM_READONLY;
708 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
709 /// any ParenExpr or ImplicitCastExprs, returning their operand.
710 Expr *IgnoreParenImpCasts() LLVM_READONLY;
712 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
713 /// call to a conversion operator, return the argument.
714 Expr *IgnoreConversionOperator() LLVM_READONLY;
716 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
717 return const_cast<Expr*>(this)->IgnoreConversionOperator();
720 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
721 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
724 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
725 /// CastExprs that represent lvalue casts, returning their operand.
726 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
728 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
729 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
732 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
733 /// value (including ptr->int casts of the same size). Strip off any
734 /// ParenExpr or CastExprs, returning their operand.
735 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
737 /// Ignore parentheses and derived-to-base casts.
738 Expr *ignoreParenBaseCasts() LLVM_READONLY;
740 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
741 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
744 /// \brief Determine whether this expression is a default function argument.
746 /// Default arguments are implicitly generated in the abstract syntax tree
747 /// by semantic analysis for function calls, object constructions, etc. in
748 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
749 /// this routine also looks through any implicit casts to determine whether
750 /// the expression is a default argument.
751 bool isDefaultArgument() const;
753 /// \brief Determine whether the result of this expression is a
754 /// temporary object of the given class type.
755 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
757 /// \brief Whether this expression is an implicit reference to 'this' in C++.
758 bool isImplicitCXXThis() const;
760 const Expr *IgnoreImpCasts() const LLVM_READONLY {
761 return const_cast<Expr*>(this)->IgnoreImpCasts();
763 const Expr *IgnoreParens() const LLVM_READONLY {
764 return const_cast<Expr*>(this)->IgnoreParens();
766 const Expr *IgnoreParenCasts() const LLVM_READONLY {
767 return const_cast<Expr*>(this)->IgnoreParenCasts();
769 /// Strip off casts, but keep parentheses.
770 const Expr *IgnoreCasts() const LLVM_READONLY {
771 return const_cast<Expr*>(this)->IgnoreCasts();
774 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
775 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
778 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
780 /// \brief For an expression of class type or pointer to class type,
781 /// return the most derived class decl the expression is known to refer to.
783 /// If this expression is a cast, this method looks through it to find the
784 /// most derived decl that can be inferred from the expression.
785 /// This is valid because derived-to-base conversions have undefined
786 /// behavior if the object isn't dynamically of the derived type.
787 const CXXRecordDecl *getBestDynamicClassType() const;
789 /// Walk outwards from an expression we want to bind a reference to and
790 /// find the expression whose lifetime needs to be extended. Record
791 /// the LHSs of comma expressions and adjustments needed along the path.
792 const Expr *skipRValueSubobjectAdjustments(
793 SmallVectorImpl<const Expr *> &CommaLHS,
794 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
796 static bool classof(const Stmt *T) {
797 return T->getStmtClass() >= firstExprConstant &&
798 T->getStmtClass() <= lastExprConstant;
803 //===----------------------------------------------------------------------===//
804 // Primary Expressions.
805 //===----------------------------------------------------------------------===//
807 /// OpaqueValueExpr - An expression referring to an opaque object of a
808 /// fixed type and value class. These don't correspond to concrete
809 /// syntax; instead they're used to express operations (usually copy
810 /// operations) on values whose source is generally obvious from
812 class OpaqueValueExpr : public Expr {
813 friend class ASTStmtReader;
818 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
819 ExprObjectKind OK = OK_Ordinary,
820 Expr *SourceExpr = nullptr)
821 : Expr(OpaqueValueExprClass, T, VK, OK,
822 T->isDependentType(),
823 T->isDependentType() ||
824 (SourceExpr && SourceExpr->isValueDependent()),
825 T->isInstantiationDependentType(),
827 SourceExpr(SourceExpr), Loc(Loc) {
830 /// Given an expression which invokes a copy constructor --- i.e. a
831 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
832 /// find the OpaqueValueExpr that's the source of the construction.
833 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
835 explicit OpaqueValueExpr(EmptyShell Empty)
836 : Expr(OpaqueValueExprClass, Empty) { }
838 /// \brief Retrieve the location of this expression.
839 SourceLocation getLocation() const { return Loc; }
841 SourceLocation getLocStart() const LLVM_READONLY {
842 return SourceExpr ? SourceExpr->getLocStart() : Loc;
844 SourceLocation getLocEnd() const LLVM_READONLY {
845 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
847 SourceLocation getExprLoc() const LLVM_READONLY {
848 if (SourceExpr) return SourceExpr->getExprLoc();
852 child_range children() { return child_range(); }
854 /// The source expression of an opaque value expression is the
855 /// expression which originally generated the value. This is
856 /// provided as a convenience for analyses that don't wish to
857 /// precisely model the execution behavior of the program.
859 /// The source expression is typically set when building the
860 /// expression which binds the opaque value expression in the first
862 Expr *getSourceExpr() const { return SourceExpr; }
864 static bool classof(const Stmt *T) {
865 return T->getStmtClass() == OpaqueValueExprClass;
869 /// \brief A reference to a declared variable, function, enum, etc.
872 /// This encodes all the information about how a declaration is referenced
873 /// within an expression.
875 /// There are several optional constructs attached to DeclRefExprs only when
876 /// they apply in order to conserve memory. These are laid out past the end of
877 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
879 /// DeclRefExprBits.HasQualifier:
880 /// Specifies when this declaration reference expression has a C++
881 /// nested-name-specifier.
882 /// DeclRefExprBits.HasFoundDecl:
883 /// Specifies when this declaration reference expression has a record of
884 /// a NamedDecl (different from the referenced ValueDecl) which was found
885 /// during name lookup and/or overload resolution.
886 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
887 /// Specifies when this declaration reference expression has an explicit
888 /// C++ template keyword and/or template argument list.
889 /// DeclRefExprBits.RefersToEnclosingLocal
890 /// Specifies when this declaration reference expression (validly)
891 /// refers to a local variable from a different function.
892 class DeclRefExpr : public Expr {
893 /// \brief The declaration that we are referencing.
896 /// \brief The location of the declaration name itself.
899 /// \brief Provides source/type location info for the declaration name
901 DeclarationNameLoc DNLoc;
903 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
904 NestedNameSpecifierLoc &getInternalQualifierLoc() {
905 assert(hasQualifier());
906 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
909 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
910 const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
911 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
914 /// \brief Test whether there is a distinct FoundDecl attached to the end of
916 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
918 /// \brief Helper to retrieve the optional NamedDecl through which this
919 /// reference occurred.
920 NamedDecl *&getInternalFoundDecl() {
921 assert(hasFoundDecl());
923 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
924 return *reinterpret_cast<NamedDecl **>(this + 1);
927 /// \brief Helper to retrieve the optional NamedDecl through which this
928 /// reference occurred.
929 NamedDecl *getInternalFoundDecl() const {
930 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
933 DeclRefExpr(const ASTContext &Ctx,
934 NestedNameSpecifierLoc QualifierLoc,
935 SourceLocation TemplateKWLoc,
936 ValueDecl *D, bool refersToEnclosingLocal,
937 const DeclarationNameInfo &NameInfo,
939 const TemplateArgumentListInfo *TemplateArgs,
940 QualType T, ExprValueKind VK);
942 /// \brief Construct an empty declaration reference expression.
943 explicit DeclRefExpr(EmptyShell Empty)
944 : Expr(DeclRefExprClass, Empty) { }
946 /// \brief Computes the type- and value-dependence flags for this
947 /// declaration reference expression.
948 void computeDependence(const ASTContext &C);
951 DeclRefExpr(ValueDecl *D, bool refersToEnclosingLocal, QualType T,
952 ExprValueKind VK, SourceLocation L,
953 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
954 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
955 D(D), Loc(L), DNLoc(LocInfo) {
956 DeclRefExprBits.HasQualifier = 0;
957 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
958 DeclRefExprBits.HasFoundDecl = 0;
959 DeclRefExprBits.HadMultipleCandidates = 0;
960 DeclRefExprBits.RefersToEnclosingLocal = refersToEnclosingLocal;
961 computeDependence(D->getASTContext());
965 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
966 SourceLocation TemplateKWLoc, ValueDecl *D, bool isEnclosingLocal,
967 SourceLocation NameLoc, QualType T, ExprValueKind VK,
968 NamedDecl *FoundD = nullptr,
969 const TemplateArgumentListInfo *TemplateArgs = nullptr);
972 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
973 SourceLocation TemplateKWLoc, ValueDecl *D, bool isEnclosingLocal,
974 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
975 NamedDecl *FoundD = nullptr,
976 const TemplateArgumentListInfo *TemplateArgs = nullptr);
978 /// \brief Construct an empty declaration reference expression.
979 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
982 bool HasTemplateKWAndArgsInfo,
983 unsigned NumTemplateArgs);
985 ValueDecl *getDecl() { return D; }
986 const ValueDecl *getDecl() const { return D; }
987 void setDecl(ValueDecl *NewD) { D = NewD; }
989 DeclarationNameInfo getNameInfo() const {
990 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
993 SourceLocation getLocation() const { return Loc; }
994 void setLocation(SourceLocation L) { Loc = L; }
995 SourceLocation getLocStart() const LLVM_READONLY;
996 SourceLocation getLocEnd() const LLVM_READONLY;
998 /// \brief Determine whether this declaration reference was preceded by a
999 /// C++ nested-name-specifier, e.g., \c N::foo.
1000 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1002 /// \brief If the name was qualified, retrieves the nested-name-specifier
1003 /// that precedes the name. Otherwise, returns NULL.
1004 NestedNameSpecifier *getQualifier() const {
1005 if (!hasQualifier())
1008 return getInternalQualifierLoc().getNestedNameSpecifier();
1011 /// \brief If the name was qualified, retrieves the nested-name-specifier
1012 /// that precedes the name, with source-location information.
1013 NestedNameSpecifierLoc getQualifierLoc() const {
1014 if (!hasQualifier())
1015 return NestedNameSpecifierLoc();
1017 return getInternalQualifierLoc();
1020 /// \brief Get the NamedDecl through which this reference occurred.
1022 /// This Decl may be different from the ValueDecl actually referred to in the
1023 /// presence of using declarations, etc. It always returns non-NULL, and may
1024 /// simple return the ValueDecl when appropriate.
1025 NamedDecl *getFoundDecl() {
1026 return hasFoundDecl() ? getInternalFoundDecl() : D;
1029 /// \brief Get the NamedDecl through which this reference occurred.
1030 /// See non-const variant.
1031 const NamedDecl *getFoundDecl() const {
1032 return hasFoundDecl() ? getInternalFoundDecl() : D;
1035 bool hasTemplateKWAndArgsInfo() const {
1036 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1039 /// \brief Return the optional template keyword and arguments info.
1040 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
1041 if (!hasTemplateKWAndArgsInfo())
1045 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1046 &getInternalFoundDecl() + 1);
1049 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1050 &getInternalQualifierLoc() + 1);
1052 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
1055 /// \brief Return the optional template keyword and arguments info.
1056 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
1057 return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo();
1060 /// \brief Retrieve the location of the template keyword preceding
1061 /// this name, if any.
1062 SourceLocation getTemplateKeywordLoc() const {
1063 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1064 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
1067 /// \brief Retrieve the location of the left angle bracket starting the
1068 /// explicit template argument list following the name, if any.
1069 SourceLocation getLAngleLoc() const {
1070 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1071 return getTemplateKWAndArgsInfo()->LAngleLoc;
1074 /// \brief Retrieve the location of the right angle bracket ending the
1075 /// explicit template argument list following the name, if any.
1076 SourceLocation getRAngleLoc() const {
1077 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1078 return getTemplateKWAndArgsInfo()->RAngleLoc;
1081 /// \brief Determines whether the name in this declaration reference
1082 /// was preceded by the template keyword.
1083 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1085 /// \brief Determines whether this declaration reference was followed by an
1086 /// explicit template argument list.
1087 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1089 /// \brief Retrieve the explicit template argument list that followed the
1090 /// member template name.
1091 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
1092 assert(hasExplicitTemplateArgs());
1093 return *getTemplateKWAndArgsInfo();
1096 /// \brief Retrieve the explicit template argument list that followed the
1097 /// member template name.
1098 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
1099 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
1102 /// \brief Retrieves the optional explicit template arguments.
1103 /// This points to the same data as getExplicitTemplateArgs(), but
1104 /// returns null if there are no explicit template arguments.
1105 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
1106 if (!hasExplicitTemplateArgs()) return nullptr;
1107 return &getExplicitTemplateArgs();
1110 /// \brief Copies the template arguments (if present) into the given
1112 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1113 if (hasExplicitTemplateArgs())
1114 getExplicitTemplateArgs().copyInto(List);
1117 /// \brief Retrieve the template arguments provided as part of this
1119 const TemplateArgumentLoc *getTemplateArgs() const {
1120 if (!hasExplicitTemplateArgs())
1123 return getExplicitTemplateArgs().getTemplateArgs();
1126 /// \brief Retrieve the number of template arguments provided as part of this
1128 unsigned getNumTemplateArgs() const {
1129 if (!hasExplicitTemplateArgs())
1132 return getExplicitTemplateArgs().NumTemplateArgs;
1135 /// \brief Returns true if this expression refers to a function that
1136 /// was resolved from an overloaded set having size greater than 1.
1137 bool hadMultipleCandidates() const {
1138 return DeclRefExprBits.HadMultipleCandidates;
1140 /// \brief Sets the flag telling whether this expression refers to
1141 /// a function that was resolved from an overloaded set having size
1143 void setHadMultipleCandidates(bool V = true) {
1144 DeclRefExprBits.HadMultipleCandidates = V;
1147 /// Does this DeclRefExpr refer to a local declaration from an
1148 /// enclosing function scope?
1149 bool refersToEnclosingLocal() const {
1150 return DeclRefExprBits.RefersToEnclosingLocal;
1153 static bool classof(const Stmt *T) {
1154 return T->getStmtClass() == DeclRefExprClass;
1158 child_range children() { return child_range(); }
1160 friend class ASTStmtReader;
1161 friend class ASTStmtWriter;
1164 /// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
1165 class PredefinedExpr : public Expr {
1170 LFunction, // Same as Function, but as wide string.
1174 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
1175 /// 'virtual' keyword is omitted for virtual member functions.
1176 PrettyFunctionNoVirtual
1183 PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
1184 : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
1185 type->isDependentType(), type->isDependentType(),
1186 type->isInstantiationDependentType(),
1187 /*ContainsUnexpandedParameterPack=*/false),
1190 /// \brief Construct an empty predefined expression.
1191 explicit PredefinedExpr(EmptyShell Empty)
1192 : Expr(PredefinedExprClass, Empty) { }
1194 IdentType getIdentType() const { return Type; }
1195 void setIdentType(IdentType IT) { Type = IT; }
1197 SourceLocation getLocation() const { return Loc; }
1198 void setLocation(SourceLocation L) { Loc = L; }
1200 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1202 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1203 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1205 static bool classof(const Stmt *T) {
1206 return T->getStmtClass() == PredefinedExprClass;
1210 child_range children() { return child_range(); }
1213 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1216 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1217 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1218 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1219 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1220 /// ASTContext's allocator for memory allocation.
1221 class APNumericStorage {
1223 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1224 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1228 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1230 APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1231 void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1234 APNumericStorage() : VAL(0), BitWidth(0) { }
1236 llvm::APInt getIntValue() const {
1237 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1239 return llvm::APInt(BitWidth, NumWords, pVal);
1241 return llvm::APInt(BitWidth, VAL);
1243 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1246 class APIntStorage : private APNumericStorage {
1248 llvm::APInt getValue() const { return getIntValue(); }
1249 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1250 setIntValue(C, Val);
1254 class APFloatStorage : private APNumericStorage {
1256 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1257 return llvm::APFloat(Semantics, getIntValue());
1259 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1260 setIntValue(C, Val.bitcastToAPInt());
1264 class IntegerLiteral : public Expr, public APIntStorage {
1267 /// \brief Construct an empty integer literal.
1268 explicit IntegerLiteral(EmptyShell Empty)
1269 : Expr(IntegerLiteralClass, Empty) { }
1272 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1273 // or UnsignedLongLongTy
1274 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1277 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1278 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1279 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1280 /// \param V - the value that the returned integer literal contains.
1281 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1282 QualType type, SourceLocation l);
1283 /// \brief Returns a new empty integer literal.
1284 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1286 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1287 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1289 /// \brief Retrieve the location of the literal.
1290 SourceLocation getLocation() const { return Loc; }
1292 void setLocation(SourceLocation Location) { Loc = Location; }
1294 static bool classof(const Stmt *T) {
1295 return T->getStmtClass() == IntegerLiteralClass;
1299 child_range children() { return child_range(); }
1302 class CharacterLiteral : public Expr {
1304 enum CharacterKind {
1315 // type should be IntTy
1316 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1318 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1320 Value(value), Loc(l) {
1321 CharacterLiteralBits.Kind = kind;
1324 /// \brief Construct an empty character literal.
1325 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1327 SourceLocation getLocation() const { return Loc; }
1328 CharacterKind getKind() const {
1329 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1332 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1333 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1335 unsigned getValue() const { return Value; }
1337 void setLocation(SourceLocation Location) { Loc = Location; }
1338 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1339 void setValue(unsigned Val) { Value = Val; }
1341 static bool classof(const Stmt *T) {
1342 return T->getStmtClass() == CharacterLiteralClass;
1346 child_range children() { return child_range(); }
1349 class FloatingLiteral : public Expr, private APFloatStorage {
1352 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1353 QualType Type, SourceLocation L);
1355 /// \brief Construct an empty floating-point literal.
1356 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1359 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1360 bool isexact, QualType Type, SourceLocation L);
1361 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1363 llvm::APFloat getValue() const {
1364 return APFloatStorage::getValue(getSemantics());
1366 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1367 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1368 APFloatStorage::setValue(C, Val);
1371 /// Get a raw enumeration value representing the floating-point semantics of
1372 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1373 APFloatSemantics getRawSemantics() const {
1374 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1377 /// Set the raw enumeration value representing the floating-point semantics of
1378 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1379 void setRawSemantics(APFloatSemantics Sem) {
1380 FloatingLiteralBits.Semantics = Sem;
1383 /// Return the APFloat semantics this literal uses.
1384 const llvm::fltSemantics &getSemantics() const;
1386 /// Set the APFloat semantics this literal uses.
1387 void setSemantics(const llvm::fltSemantics &Sem);
1389 bool isExact() const { return FloatingLiteralBits.IsExact; }
1390 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1392 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1393 /// double. Note that this may cause loss of precision, but is useful for
1394 /// debugging dumps, etc.
1395 double getValueAsApproximateDouble() const;
1397 SourceLocation getLocation() const { return Loc; }
1398 void setLocation(SourceLocation L) { Loc = L; }
1400 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1401 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1403 static bool classof(const Stmt *T) {
1404 return T->getStmtClass() == FloatingLiteralClass;
1408 child_range children() { return child_range(); }
1411 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1412 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1413 /// IntegerLiteral classes. Instances of this class always have a Complex type
1414 /// whose element type matches the subexpression.
1416 class ImaginaryLiteral : public Expr {
1419 ImaginaryLiteral(Expr *val, QualType Ty)
1420 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1424 /// \brief Build an empty imaginary literal.
1425 explicit ImaginaryLiteral(EmptyShell Empty)
1426 : Expr(ImaginaryLiteralClass, Empty) { }
1428 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1429 Expr *getSubExpr() { return cast<Expr>(Val); }
1430 void setSubExpr(Expr *E) { Val = E; }
1432 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1433 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1435 static bool classof(const Stmt *T) {
1436 return T->getStmtClass() == ImaginaryLiteralClass;
1440 child_range children() { return child_range(&Val, &Val+1); }
1443 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1444 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1445 /// is NOT null-terminated, and the length of the string is determined by
1446 /// calling getByteLength(). The C type for a string is always a
1447 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1450 /// Note that strings in C can be formed by concatenation of multiple string
1451 /// literal pptokens in translation phase #6. This keeps track of the locations
1452 /// of each of these pieces.
1454 /// Strings in C can also be truncated and extended by assigning into arrays,
1455 /// e.g. with constructs like:
1456 /// char X[2] = "foobar";
1457 /// In this case, getByteLength() will return 6, but the string literal will
1458 /// have type "char[2]".
1459 class StringLiteral : public Expr {
1470 friend class ASTStmtReader;
1474 const uint16_t *asUInt16;
1475 const uint32_t *asUInt32;
1478 unsigned CharByteWidth : 4;
1480 unsigned IsPascal : 1;
1481 unsigned NumConcatenated;
1482 SourceLocation TokLocs[1];
1484 StringLiteral(QualType Ty) :
1485 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1488 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1491 /// This is the "fully general" constructor that allows representation of
1492 /// strings formed from multiple concatenated tokens.
1493 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1494 StringKind Kind, bool Pascal, QualType Ty,
1495 const SourceLocation *Loc, unsigned NumStrs);
1497 /// Simple constructor for string literals made from one token.
1498 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1499 StringKind Kind, bool Pascal, QualType Ty,
1500 SourceLocation Loc) {
1501 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1504 /// \brief Construct an empty string literal.
1505 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1507 StringRef getString() const {
1508 assert(CharByteWidth==1
1509 && "This function is used in places that assume strings use char");
1510 return StringRef(StrData.asChar, getByteLength());
1513 /// Allow access to clients that need the byte representation, such as
1514 /// ASTWriterStmt::VisitStringLiteral().
1515 StringRef getBytes() const {
1516 // FIXME: StringRef may not be the right type to use as a result for this.
1517 if (CharByteWidth == 1)
1518 return StringRef(StrData.asChar, getByteLength());
1519 if (CharByteWidth == 4)
1520 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1522 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1523 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1527 void outputString(raw_ostream &OS) const;
1529 uint32_t getCodeUnit(size_t i) const {
1530 assert(i < Length && "out of bounds access");
1531 if (CharByteWidth == 1)
1532 return static_cast<unsigned char>(StrData.asChar[i]);
1533 if (CharByteWidth == 4)
1534 return StrData.asUInt32[i];
1535 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1536 return StrData.asUInt16[i];
1539 unsigned getByteLength() const { return CharByteWidth*Length; }
1540 unsigned getLength() const { return Length; }
1541 unsigned getCharByteWidth() const { return CharByteWidth; }
1543 /// \brief Sets the string data to the given string data.
1544 void setString(const ASTContext &C, StringRef Str,
1545 StringKind Kind, bool IsPascal);
1547 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1550 bool isAscii() const { return Kind == Ascii; }
1551 bool isWide() const { return Kind == Wide; }
1552 bool isUTF8() const { return Kind == UTF8; }
1553 bool isUTF16() const { return Kind == UTF16; }
1554 bool isUTF32() const { return Kind == UTF32; }
1555 bool isPascal() const { return IsPascal; }
1557 bool containsNonAsciiOrNull() const {
1558 StringRef Str = getString();
1559 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1560 if (!isASCII(Str[i]) || !Str[i])
1565 /// getNumConcatenated - Get the number of string literal tokens that were
1566 /// concatenated in translation phase #6 to form this string literal.
1567 unsigned getNumConcatenated() const { return NumConcatenated; }
1569 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1570 assert(TokNum < NumConcatenated && "Invalid tok number");
1571 return TokLocs[TokNum];
1573 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1574 assert(TokNum < NumConcatenated && "Invalid tok number");
1575 TokLocs[TokNum] = L;
1578 /// getLocationOfByte - Return a source location that points to the specified
1579 /// byte of this string literal.
1581 /// Strings are amazingly complex. They can be formed from multiple tokens
1582 /// and can have escape sequences in them in addition to the usual trigraph
1583 /// and escaped newline business. This routine handles this complexity.
1585 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1586 const LangOptions &Features,
1587 const TargetInfo &Target) const;
1589 typedef const SourceLocation *tokloc_iterator;
1590 tokloc_iterator tokloc_begin() const { return TokLocs; }
1591 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1593 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1594 SourceLocation getLocEnd() const LLVM_READONLY {
1595 return TokLocs[NumConcatenated - 1];
1598 static bool classof(const Stmt *T) {
1599 return T->getStmtClass() == StringLiteralClass;
1603 child_range children() { return child_range(); }
1606 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1607 /// AST node is only formed if full location information is requested.
1608 class ParenExpr : public Expr {
1609 SourceLocation L, R;
1612 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1613 : Expr(ParenExprClass, val->getType(),
1614 val->getValueKind(), val->getObjectKind(),
1615 val->isTypeDependent(), val->isValueDependent(),
1616 val->isInstantiationDependent(),
1617 val->containsUnexpandedParameterPack()),
1618 L(l), R(r), Val(val) {}
1620 /// \brief Construct an empty parenthesized expression.
1621 explicit ParenExpr(EmptyShell Empty)
1622 : Expr(ParenExprClass, Empty) { }
1624 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1625 Expr *getSubExpr() { return cast<Expr>(Val); }
1626 void setSubExpr(Expr *E) { Val = E; }
1628 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1629 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1631 /// \brief Get the location of the left parentheses '('.
1632 SourceLocation getLParen() const { return L; }
1633 void setLParen(SourceLocation Loc) { L = Loc; }
1635 /// \brief Get the location of the right parentheses ')'.
1636 SourceLocation getRParen() const { return R; }
1637 void setRParen(SourceLocation Loc) { R = Loc; }
1639 static bool classof(const Stmt *T) {
1640 return T->getStmtClass() == ParenExprClass;
1644 child_range children() { return child_range(&Val, &Val+1); }
1648 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1649 /// alignof), the postinc/postdec operators from postfix-expression, and various
1652 /// Notes on various nodes:
1654 /// Real/Imag - These return the real/imag part of a complex operand. If
1655 /// applied to a non-complex value, the former returns its operand and the
1656 /// later returns zero in the type of the operand.
1658 class UnaryOperator : public Expr {
1660 typedef UnaryOperatorKind Opcode;
1668 UnaryOperator(Expr *input, Opcode opc, QualType type,
1669 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1670 : Expr(UnaryOperatorClass, type, VK, OK,
1671 input->isTypeDependent() || type->isDependentType(),
1672 input->isValueDependent(),
1673 (input->isInstantiationDependent() ||
1674 type->isInstantiationDependentType()),
1675 input->containsUnexpandedParameterPack()),
1676 Opc(opc), Loc(l), Val(input) {}
1678 /// \brief Build an empty unary operator.
1679 explicit UnaryOperator(EmptyShell Empty)
1680 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1682 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1683 void setOpcode(Opcode O) { Opc = O; }
1685 Expr *getSubExpr() const { return cast<Expr>(Val); }
1686 void setSubExpr(Expr *E) { Val = E; }
1688 /// getOperatorLoc - Return the location of the operator.
1689 SourceLocation getOperatorLoc() const { return Loc; }
1690 void setOperatorLoc(SourceLocation L) { Loc = L; }
1692 /// isPostfix - Return true if this is a postfix operation, like x++.
1693 static bool isPostfix(Opcode Op) {
1694 return Op == UO_PostInc || Op == UO_PostDec;
1697 /// isPrefix - Return true if this is a prefix operation, like --x.
1698 static bool isPrefix(Opcode Op) {
1699 return Op == UO_PreInc || Op == UO_PreDec;
1702 bool isPrefix() const { return isPrefix(getOpcode()); }
1703 bool isPostfix() const { return isPostfix(getOpcode()); }
1705 static bool isIncrementOp(Opcode Op) {
1706 return Op == UO_PreInc || Op == UO_PostInc;
1708 bool isIncrementOp() const {
1709 return isIncrementOp(getOpcode());
1712 static bool isDecrementOp(Opcode Op) {
1713 return Op == UO_PreDec || Op == UO_PostDec;
1715 bool isDecrementOp() const {
1716 return isDecrementOp(getOpcode());
1719 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1720 bool isIncrementDecrementOp() const {
1721 return isIncrementDecrementOp(getOpcode());
1724 static bool isArithmeticOp(Opcode Op) {
1725 return Op >= UO_Plus && Op <= UO_LNot;
1727 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1729 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1730 /// corresponds to, e.g. "sizeof" or "[pre]++"
1731 static StringRef getOpcodeStr(Opcode Op);
1733 /// \brief Retrieve the unary opcode that corresponds to the given
1734 /// overloaded operator.
1735 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1737 /// \brief Retrieve the overloaded operator kind that corresponds to
1738 /// the given unary opcode.
1739 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1741 SourceLocation getLocStart() const LLVM_READONLY {
1742 return isPostfix() ? Val->getLocStart() : Loc;
1744 SourceLocation getLocEnd() const LLVM_READONLY {
1745 return isPostfix() ? Loc : Val->getLocEnd();
1747 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1749 static bool classof(const Stmt *T) {
1750 return T->getStmtClass() == UnaryOperatorClass;
1754 child_range children() { return child_range(&Val, &Val+1); }
1757 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1758 /// offsetof(record-type, member-designator). For example, given:
1769 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1771 class OffsetOfExpr : public Expr {
1773 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1774 class OffsetOfNode {
1776 /// \brief The kind of offsetof node we have.
1778 /// \brief An index into an array.
1782 /// \brief A field in a dependent type, known only by its name.
1784 /// \brief An implicit indirection through a C++ base class, when the
1785 /// field found is in a base class.
1790 enum { MaskBits = 2, Mask = 0x03 };
1792 /// \brief The source range that covers this part of the designator.
1795 /// \brief The data describing the designator, which comes in three
1796 /// different forms, depending on the lower two bits.
1797 /// - An unsigned index into the array of Expr*'s stored after this node
1798 /// in memory, for [constant-expression] designators.
1799 /// - A FieldDecl*, for references to a known field.
1800 /// - An IdentifierInfo*, for references to a field with a given name
1801 /// when the class type is dependent.
1802 /// - A CXXBaseSpecifier*, for references that look at a field in a
1807 /// \brief Create an offsetof node that refers to an array element.
1808 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1809 SourceLocation RBracketLoc)
1810 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1812 /// \brief Create an offsetof node that refers to a field.
1813 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1814 SourceLocation NameLoc)
1815 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1816 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1818 /// \brief Create an offsetof node that refers to an identifier.
1819 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1820 SourceLocation NameLoc)
1821 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1822 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1824 /// \brief Create an offsetof node that refers into a C++ base class.
1825 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1826 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1828 /// \brief Determine what kind of offsetof node this is.
1829 Kind getKind() const {
1830 return static_cast<Kind>(Data & Mask);
1833 /// \brief For an array element node, returns the index into the array
1835 unsigned getArrayExprIndex() const {
1836 assert(getKind() == Array);
1840 /// \brief For a field offsetof node, returns the field.
1841 FieldDecl *getField() const {
1842 assert(getKind() == Field);
1843 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1846 /// \brief For a field or identifier offsetof node, returns the name of
1848 IdentifierInfo *getFieldName() const;
1850 /// \brief For a base class node, returns the base specifier.
1851 CXXBaseSpecifier *getBase() const {
1852 assert(getKind() == Base);
1853 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1856 /// \brief Retrieve the source range that covers this offsetof node.
1858 /// For an array element node, the source range contains the locations of
1859 /// the square brackets. For a field or identifier node, the source range
1860 /// contains the location of the period (if there is one) and the
1862 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1863 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1864 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1869 SourceLocation OperatorLoc, RParenLoc;
1871 TypeSourceInfo *TSInfo;
1872 // Number of sub-components (i.e. instances of OffsetOfNode).
1874 // Number of sub-expressions (i.e. array subscript expressions).
1877 OffsetOfExpr(const ASTContext &C, QualType type,
1878 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1879 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1880 SourceLocation RParenLoc);
1882 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1883 : Expr(OffsetOfExprClass, EmptyShell()),
1884 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1888 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1889 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1890 ArrayRef<OffsetOfNode> comps,
1891 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1893 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1894 unsigned NumComps, unsigned NumExprs);
1896 /// getOperatorLoc - Return the location of the operator.
1897 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1898 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1900 /// \brief Return the location of the right parentheses.
1901 SourceLocation getRParenLoc() const { return RParenLoc; }
1902 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1904 TypeSourceInfo *getTypeSourceInfo() const {
1907 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1911 const OffsetOfNode &getComponent(unsigned Idx) const {
1912 assert(Idx < NumComps && "Subscript out of range");
1913 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1916 void setComponent(unsigned Idx, OffsetOfNode ON) {
1917 assert(Idx < NumComps && "Subscript out of range");
1918 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1921 unsigned getNumComponents() const {
1925 Expr* getIndexExpr(unsigned Idx) {
1926 assert(Idx < NumExprs && "Subscript out of range");
1927 return reinterpret_cast<Expr **>(
1928 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1930 const Expr *getIndexExpr(unsigned Idx) const {
1931 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1934 void setIndexExpr(unsigned Idx, Expr* E) {
1935 assert(Idx < NumComps && "Subscript out of range");
1936 reinterpret_cast<Expr **>(
1937 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1940 unsigned getNumExpressions() const {
1944 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1945 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1947 static bool classof(const Stmt *T) {
1948 return T->getStmtClass() == OffsetOfExprClass;
1952 child_range children() {
1954 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1956 return child_range(begin, begin + NumExprs);
1960 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1961 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1962 /// vec_step (OpenCL 1.1 6.11.12).
1963 class UnaryExprOrTypeTraitExpr : public Expr {
1968 SourceLocation OpLoc, RParenLoc;
1971 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1972 QualType resultType, SourceLocation op,
1973 SourceLocation rp) :
1974 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1975 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1976 // Value-dependent if the argument is type-dependent.
1977 TInfo->getType()->isDependentType(),
1978 TInfo->getType()->isInstantiationDependentType(),
1979 TInfo->getType()->containsUnexpandedParameterPack()),
1980 OpLoc(op), RParenLoc(rp) {
1981 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1982 UnaryExprOrTypeTraitExprBits.IsType = true;
1983 Argument.Ty = TInfo;
1986 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1987 QualType resultType, SourceLocation op,
1988 SourceLocation rp) :
1989 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1990 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1991 // Value-dependent if the argument is type-dependent.
1992 E->isTypeDependent(),
1993 E->isInstantiationDependent(),
1994 E->containsUnexpandedParameterPack()),
1995 OpLoc(op), RParenLoc(rp) {
1996 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1997 UnaryExprOrTypeTraitExprBits.IsType = false;
2001 /// \brief Construct an empty sizeof/alignof expression.
2002 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2003 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2005 UnaryExprOrTypeTrait getKind() const {
2006 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2008 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2010 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2011 QualType getArgumentType() const {
2012 return getArgumentTypeInfo()->getType();
2014 TypeSourceInfo *getArgumentTypeInfo() const {
2015 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2018 Expr *getArgumentExpr() {
2019 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2020 return static_cast<Expr*>(Argument.Ex);
2022 const Expr *getArgumentExpr() const {
2023 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2026 void setArgument(Expr *E) {
2028 UnaryExprOrTypeTraitExprBits.IsType = false;
2030 void setArgument(TypeSourceInfo *TInfo) {
2031 Argument.Ty = TInfo;
2032 UnaryExprOrTypeTraitExprBits.IsType = true;
2035 /// Gets the argument type, or the type of the argument expression, whichever
2037 QualType getTypeOfArgument() const {
2038 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2041 SourceLocation getOperatorLoc() const { return OpLoc; }
2042 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2044 SourceLocation getRParenLoc() const { return RParenLoc; }
2045 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2047 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2048 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2050 static bool classof(const Stmt *T) {
2051 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2055 child_range children();
2058 //===----------------------------------------------------------------------===//
2059 // Postfix Operators.
2060 //===----------------------------------------------------------------------===//
2062 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2063 class ArraySubscriptExpr : public Expr {
2064 enum { LHS, RHS, END_EXPR=2 };
2065 Stmt* SubExprs[END_EXPR];
2066 SourceLocation RBracketLoc;
2068 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2069 ExprValueKind VK, ExprObjectKind OK,
2070 SourceLocation rbracketloc)
2071 : Expr(ArraySubscriptExprClass, t, VK, OK,
2072 lhs->isTypeDependent() || rhs->isTypeDependent(),
2073 lhs->isValueDependent() || rhs->isValueDependent(),
2074 (lhs->isInstantiationDependent() ||
2075 rhs->isInstantiationDependent()),
2076 (lhs->containsUnexpandedParameterPack() ||
2077 rhs->containsUnexpandedParameterPack())),
2078 RBracketLoc(rbracketloc) {
2079 SubExprs[LHS] = lhs;
2080 SubExprs[RHS] = rhs;
2083 /// \brief Create an empty array subscript expression.
2084 explicit ArraySubscriptExpr(EmptyShell Shell)
2085 : Expr(ArraySubscriptExprClass, Shell) { }
2087 /// An array access can be written A[4] or 4[A] (both are equivalent).
2088 /// - getBase() and getIdx() always present the normalized view: A[4].
2089 /// In this case getBase() returns "A" and getIdx() returns "4".
2090 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2091 /// 4[A] getLHS() returns "4".
2092 /// Note: Because vector element access is also written A[4] we must
2093 /// predicate the format conversion in getBase and getIdx only on the
2094 /// the type of the RHS, as it is possible for the LHS to be a vector of
2096 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2097 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2098 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2100 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2101 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2102 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2105 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2108 const Expr *getBase() const {
2109 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2113 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2116 const Expr *getIdx() const {
2117 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2120 SourceLocation getLocStart() const LLVM_READONLY {
2121 return getLHS()->getLocStart();
2123 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2125 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2126 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2128 SourceLocation getExprLoc() const LLVM_READONLY {
2129 return getBase()->getExprLoc();
2132 static bool classof(const Stmt *T) {
2133 return T->getStmtClass() == ArraySubscriptExprClass;
2137 child_range children() {
2138 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2143 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2144 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2145 /// while its subclasses may represent alternative syntax that (semantically)
2146 /// results in a function call. For example, CXXOperatorCallExpr is
2147 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2148 /// "str1 + str2" to resolve to a function call.
2149 class CallExpr : public Expr {
2150 enum { FN=0, PREARGS_START=1 };
2153 SourceLocation RParenLoc;
2156 // These versions of the constructor are for derived classes.
2157 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2158 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2159 SourceLocation rparenloc);
2160 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2163 Stmt *getPreArg(unsigned i) {
2164 assert(i < getNumPreArgs() && "Prearg access out of range!");
2165 return SubExprs[PREARGS_START+i];
2167 const Stmt *getPreArg(unsigned i) const {
2168 assert(i < getNumPreArgs() && "Prearg access out of range!");
2169 return SubExprs[PREARGS_START+i];
2171 void setPreArg(unsigned i, Stmt *PreArg) {
2172 assert(i < getNumPreArgs() && "Prearg access out of range!");
2173 SubExprs[PREARGS_START+i] = PreArg;
2176 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2179 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2180 ExprValueKind VK, SourceLocation rparenloc);
2182 /// \brief Build an empty call expression.
2183 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2185 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2186 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2187 void setCallee(Expr *F) { SubExprs[FN] = F; }
2189 Decl *getCalleeDecl();
2190 const Decl *getCalleeDecl() const {
2191 return const_cast<CallExpr*>(this)->getCalleeDecl();
2194 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2195 FunctionDecl *getDirectCallee();
2196 const FunctionDecl *getDirectCallee() const {
2197 return const_cast<CallExpr*>(this)->getDirectCallee();
2200 /// getNumArgs - Return the number of actual arguments to this call.
2202 unsigned getNumArgs() const { return NumArgs; }
2204 /// \brief Retrieve the call arguments.
2206 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2208 const Expr *const *getArgs() const {
2209 return const_cast<CallExpr*>(this)->getArgs();
2212 /// getArg - Return the specified argument.
2213 Expr *getArg(unsigned Arg) {
2214 assert(Arg < NumArgs && "Arg access out of range!");
2215 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2217 const Expr *getArg(unsigned Arg) const {
2218 assert(Arg < NumArgs && "Arg access out of range!");
2219 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2222 /// setArg - Set the specified argument.
2223 void setArg(unsigned Arg, Expr *ArgExpr) {
2224 assert(Arg < NumArgs && "Arg access out of range!");
2225 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2228 /// setNumArgs - This changes the number of arguments present in this call.
2229 /// Any orphaned expressions are deleted by this, and any new operands are set
2231 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2233 typedef ExprIterator arg_iterator;
2234 typedef ConstExprIterator const_arg_iterator;
2235 typedef llvm::iterator_range<arg_iterator> arg_range;
2236 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2238 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2239 arg_const_range arguments() const {
2240 return arg_const_range(arg_begin(), arg_end());
2243 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2244 arg_iterator arg_end() {
2245 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2247 const_arg_iterator arg_begin() const {
2248 return SubExprs+PREARGS_START+getNumPreArgs();
2250 const_arg_iterator arg_end() const {
2251 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2254 /// This method provides fast access to all the subexpressions of
2255 /// a CallExpr without going through the slower virtual child_iterator
2256 /// interface. This provides efficient reverse iteration of the
2257 /// subexpressions. This is currently used for CFG construction.
2258 ArrayRef<Stmt*> getRawSubExprs() {
2259 return ArrayRef<Stmt*>(SubExprs,
2260 getNumPreArgs() + PREARGS_START + getNumArgs());
2263 /// getNumCommas - Return the number of commas that must have been present in
2264 /// this function call.
2265 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2267 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2268 /// of the callee. If not, return 0.
2269 unsigned getBuiltinCallee() const;
2271 /// \brief Returns \c true if this is a call to a builtin which does not
2272 /// evaluate side-effects within its arguments.
2273 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
2275 /// getCallReturnType - Get the return type of the call expr. This is not
2276 /// always the type of the expr itself, if the return type is a reference
2278 QualType getCallReturnType() const;
2280 SourceLocation getRParenLoc() const { return RParenLoc; }
2281 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2283 SourceLocation getLocStart() const LLVM_READONLY;
2284 SourceLocation getLocEnd() const LLVM_READONLY;
2286 static bool classof(const Stmt *T) {
2287 return T->getStmtClass() >= firstCallExprConstant &&
2288 T->getStmtClass() <= lastCallExprConstant;
2292 child_range children() {
2293 return child_range(&SubExprs[0],
2294 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2298 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2300 class MemberExpr : public Expr {
2301 /// Extra data stored in some member expressions.
2302 struct MemberNameQualifier {
2303 /// \brief The nested-name-specifier that qualifies the name, including
2304 /// source-location information.
2305 NestedNameSpecifierLoc QualifierLoc;
2307 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2308 /// name qualifiers.
2309 DeclAccessPair FoundDecl;
2312 /// Base - the expression for the base pointer or structure references. In
2313 /// X.F, this is "X".
2316 /// MemberDecl - This is the decl being referenced by the field/member name.
2317 /// In X.F, this is the decl referenced by F.
2318 ValueDecl *MemberDecl;
2320 /// MemberDNLoc - Provides source/type location info for the
2321 /// declaration name embedded in MemberDecl.
2322 DeclarationNameLoc MemberDNLoc;
2324 /// MemberLoc - This is the location of the member name.
2325 SourceLocation MemberLoc;
2327 /// IsArrow - True if this is "X->F", false if this is "X.F".
2330 /// \brief True if this member expression used a nested-name-specifier to
2331 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2332 /// declaration. When true, a MemberNameQualifier
2333 /// structure is allocated immediately after the MemberExpr.
2334 bool HasQualifierOrFoundDecl : 1;
2336 /// \brief True if this member expression specified a template keyword
2337 /// and/or a template argument list explicitly, e.g., x->f<int>,
2338 /// x->template f, x->template f<int>.
2339 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2340 /// TemplateArguments (if any) are allocated immediately after
2341 /// the MemberExpr or, if the member expression also has a qualifier,
2342 /// after the MemberNameQualifier structure.
2343 bool HasTemplateKWAndArgsInfo : 1;
2345 /// \brief True if this member expression refers to a method that
2346 /// was resolved from an overloaded set having size greater than 1.
2347 bool HadMultipleCandidates : 1;
2349 /// \brief Retrieve the qualifier that preceded the member name, if any.
2350 MemberNameQualifier *getMemberQualifier() {
2351 assert(HasQualifierOrFoundDecl);
2352 return reinterpret_cast<MemberNameQualifier *> (this + 1);
2355 /// \brief Retrieve the qualifier that preceded the member name, if any.
2356 const MemberNameQualifier *getMemberQualifier() const {
2357 return const_cast<MemberExpr *>(this)->getMemberQualifier();
2361 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2362 const DeclarationNameInfo &NameInfo, QualType ty,
2363 ExprValueKind VK, ExprObjectKind OK)
2364 : Expr(MemberExprClass, ty, VK, OK,
2365 base->isTypeDependent(),
2366 base->isValueDependent(),
2367 base->isInstantiationDependent(),
2368 base->containsUnexpandedParameterPack()),
2369 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2370 MemberLoc(NameInfo.getLoc()), IsArrow(isarrow),
2371 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2372 HadMultipleCandidates(false) {
2373 assert(memberdecl->getDeclName() == NameInfo.getName());
2376 // NOTE: this constructor should be used only when it is known that
2377 // the member name can not provide additional syntactic info
2378 // (i.e., source locations for C++ operator names or type source info
2379 // for constructors, destructors and conversion operators).
2380 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2381 SourceLocation l, QualType ty,
2382 ExprValueKind VK, ExprObjectKind OK)
2383 : Expr(MemberExprClass, ty, VK, OK,
2384 base->isTypeDependent(), base->isValueDependent(),
2385 base->isInstantiationDependent(),
2386 base->containsUnexpandedParameterPack()),
2387 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2389 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2390 HadMultipleCandidates(false) {}
2392 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2393 NestedNameSpecifierLoc QualifierLoc,
2394 SourceLocation TemplateKWLoc,
2395 ValueDecl *memberdecl, DeclAccessPair founddecl,
2396 DeclarationNameInfo MemberNameInfo,
2397 const TemplateArgumentListInfo *targs,
2398 QualType ty, ExprValueKind VK, ExprObjectKind OK);
2400 void setBase(Expr *E) { Base = E; }
2401 Expr *getBase() const { return cast<Expr>(Base); }
2403 /// \brief Retrieve the member declaration to which this expression refers.
2405 /// The returned declaration will either be a FieldDecl or (in C++)
2406 /// a CXXMethodDecl.
2407 ValueDecl *getMemberDecl() const { return MemberDecl; }
2408 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2410 /// \brief Retrieves the declaration found by lookup.
2411 DeclAccessPair getFoundDecl() const {
2412 if (!HasQualifierOrFoundDecl)
2413 return DeclAccessPair::make(getMemberDecl(),
2414 getMemberDecl()->getAccess());
2415 return getMemberQualifier()->FoundDecl;
2418 /// \brief Determines whether this member expression actually had
2419 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2421 bool hasQualifier() const { return getQualifier() != nullptr; }
2423 /// \brief If the member name was qualified, retrieves the
2424 /// nested-name-specifier that precedes the member name. Otherwise, returns
2426 NestedNameSpecifier *getQualifier() const {
2427 if (!HasQualifierOrFoundDecl)
2430 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2433 /// \brief If the member name was qualified, retrieves the
2434 /// nested-name-specifier that precedes the member name, with source-location
2436 NestedNameSpecifierLoc getQualifierLoc() const {
2437 if (!hasQualifier())
2438 return NestedNameSpecifierLoc();
2440 return getMemberQualifier()->QualifierLoc;
2443 /// \brief Return the optional template keyword and arguments info.
2444 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2445 if (!HasTemplateKWAndArgsInfo)
2448 if (!HasQualifierOrFoundDecl)
2449 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
2451 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
2452 getMemberQualifier() + 1);
2455 /// \brief Return the optional template keyword and arguments info.
2456 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2457 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
2460 /// \brief Retrieve the location of the template keyword preceding
2461 /// the member name, if any.
2462 SourceLocation getTemplateKeywordLoc() const {
2463 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2464 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2467 /// \brief Retrieve the location of the left angle bracket starting the
2468 /// explicit template argument list following the member name, if any.
2469 SourceLocation getLAngleLoc() const {
2470 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2471 return getTemplateKWAndArgsInfo()->LAngleLoc;
2474 /// \brief Retrieve the location of the right angle bracket ending the
2475 /// explicit template argument list following the member name, if any.
2476 SourceLocation getRAngleLoc() const {
2477 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2478 return getTemplateKWAndArgsInfo()->RAngleLoc;
2481 /// Determines whether the member name was preceded by the template keyword.
2482 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2484 /// \brief Determines whether the member name was followed by an
2485 /// explicit template argument list.
2486 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2488 /// \brief Copies the template arguments (if present) into the given
2490 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2491 if (hasExplicitTemplateArgs())
2492 getExplicitTemplateArgs().copyInto(List);
2495 /// \brief Retrieve the explicit template argument list that
2496 /// follow the member template name. This must only be called on an
2497 /// expression with explicit template arguments.
2498 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2499 assert(hasExplicitTemplateArgs());
2500 return *getTemplateKWAndArgsInfo();
2503 /// \brief Retrieve the explicit template argument list that
2504 /// followed the member template name. This must only be called on
2505 /// an expression with explicit template arguments.
2506 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2507 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2510 /// \brief Retrieves the optional explicit template arguments.
2511 /// This points to the same data as getExplicitTemplateArgs(), but
2512 /// returns null if there are no explicit template arguments.
2513 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2514 if (!hasExplicitTemplateArgs()) return nullptr;
2515 return &getExplicitTemplateArgs();
2518 /// \brief Retrieve the template arguments provided as part of this
2520 const TemplateArgumentLoc *getTemplateArgs() const {
2521 if (!hasExplicitTemplateArgs())
2524 return getExplicitTemplateArgs().getTemplateArgs();
2527 /// \brief Retrieve the number of template arguments provided as part of this
2529 unsigned getNumTemplateArgs() const {
2530 if (!hasExplicitTemplateArgs())
2533 return getExplicitTemplateArgs().NumTemplateArgs;
2536 /// \brief Retrieve the member declaration name info.
2537 DeclarationNameInfo getMemberNameInfo() const {
2538 return DeclarationNameInfo(MemberDecl->getDeclName(),
2539 MemberLoc, MemberDNLoc);
2542 bool isArrow() const { return IsArrow; }
2543 void setArrow(bool A) { IsArrow = A; }
2545 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2546 /// location of 'F'.
2547 SourceLocation getMemberLoc() const { return MemberLoc; }
2548 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2550 SourceLocation getLocStart() const LLVM_READONLY;
2551 SourceLocation getLocEnd() const LLVM_READONLY;
2553 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2555 /// \brief Determine whether the base of this explicit is implicit.
2556 bool isImplicitAccess() const {
2557 return getBase() && getBase()->isImplicitCXXThis();
2560 /// \brief Returns true if this member expression refers to a method that
2561 /// was resolved from an overloaded set having size greater than 1.
2562 bool hadMultipleCandidates() const {
2563 return HadMultipleCandidates;
2565 /// \brief Sets the flag telling whether this expression refers to
2566 /// a method that was resolved from an overloaded set having size
2568 void setHadMultipleCandidates(bool V = true) {
2569 HadMultipleCandidates = V;
2572 static bool classof(const Stmt *T) {
2573 return T->getStmtClass() == MemberExprClass;
2577 child_range children() { return child_range(&Base, &Base+1); }
2579 friend class ASTReader;
2580 friend class ASTStmtWriter;
2583 /// CompoundLiteralExpr - [C99 6.5.2.5]
2585 class CompoundLiteralExpr : public Expr {
2586 /// LParenLoc - If non-null, this is the location of the left paren in a
2587 /// compound literal like "(int){4}". This can be null if this is a
2588 /// synthesized compound expression.
2589 SourceLocation LParenLoc;
2591 /// The type as written. This can be an incomplete array type, in
2592 /// which case the actual expression type will be different.
2593 /// The int part of the pair stores whether this expr is file scope.
2594 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2597 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2598 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2599 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2600 tinfo->getType()->isDependentType(),
2601 init->isValueDependent(),
2602 (init->isInstantiationDependent() ||
2603 tinfo->getType()->isInstantiationDependentType()),
2604 init->containsUnexpandedParameterPack()),
2605 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2607 /// \brief Construct an empty compound literal.
2608 explicit CompoundLiteralExpr(EmptyShell Empty)
2609 : Expr(CompoundLiteralExprClass, Empty) { }
2611 const Expr *getInitializer() const { return cast<Expr>(Init); }
2612 Expr *getInitializer() { return cast<Expr>(Init); }
2613 void setInitializer(Expr *E) { Init = E; }
2615 bool isFileScope() const { return TInfoAndScope.getInt(); }
2616 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2618 SourceLocation getLParenLoc() const { return LParenLoc; }
2619 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2621 TypeSourceInfo *getTypeSourceInfo() const {
2622 return TInfoAndScope.getPointer();
2624 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2625 TInfoAndScope.setPointer(tinfo);
2628 SourceLocation getLocStart() const LLVM_READONLY {
2629 // FIXME: Init should never be null.
2631 return SourceLocation();
2632 if (LParenLoc.isInvalid())
2633 return Init->getLocStart();
2636 SourceLocation getLocEnd() const LLVM_READONLY {
2637 // FIXME: Init should never be null.
2639 return SourceLocation();
2640 return Init->getLocEnd();
2643 static bool classof(const Stmt *T) {
2644 return T->getStmtClass() == CompoundLiteralExprClass;
2648 child_range children() { return child_range(&Init, &Init+1); }
2651 /// CastExpr - Base class for type casts, including both implicit
2652 /// casts (ImplicitCastExpr) and explicit casts that have some
2653 /// representation in the source code (ExplicitCastExpr's derived
2655 class CastExpr : public Expr {
2657 typedef clang::CastKind CastKind;
2662 bool CastConsistency() const;
2664 const CXXBaseSpecifier * const *path_buffer() const {
2665 return const_cast<CastExpr*>(this)->path_buffer();
2667 CXXBaseSpecifier **path_buffer();
2669 void setBasePathSize(unsigned basePathSize) {
2670 CastExprBits.BasePathSize = basePathSize;
2671 assert(CastExprBits.BasePathSize == basePathSize &&
2672 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2676 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2677 const CastKind kind, Expr *op, unsigned BasePathSize) :
2678 Expr(SC, ty, VK, OK_Ordinary,
2679 // Cast expressions are type-dependent if the type is
2680 // dependent (C++ [temp.dep.expr]p3).
2681 ty->isDependentType(),
2682 // Cast expressions are value-dependent if the type is
2683 // dependent or if the subexpression is value-dependent.
2684 ty->isDependentType() || (op && op->isValueDependent()),
2685 (ty->isInstantiationDependentType() ||
2686 (op && op->isInstantiationDependent())),
2687 (ty->containsUnexpandedParameterPack() ||
2688 (op && op->containsUnexpandedParameterPack()))),
2690 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2691 CastExprBits.Kind = kind;
2692 setBasePathSize(BasePathSize);
2693 assert(CastConsistency());
2696 /// \brief Construct an empty cast.
2697 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2699 setBasePathSize(BasePathSize);
2703 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2704 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2705 const char *getCastKindName() const;
2707 Expr *getSubExpr() { return cast<Expr>(Op); }
2708 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2709 void setSubExpr(Expr *E) { Op = E; }
2711 /// \brief Retrieve the cast subexpression as it was written in the source
2712 /// code, looking through any implicit casts or other intermediate nodes
2713 /// introduced by semantic analysis.
2714 Expr *getSubExprAsWritten();
2715 const Expr *getSubExprAsWritten() const {
2716 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2719 typedef CXXBaseSpecifier **path_iterator;
2720 typedef const CXXBaseSpecifier * const *path_const_iterator;
2721 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2722 unsigned path_size() const { return CastExprBits.BasePathSize; }
2723 path_iterator path_begin() { return path_buffer(); }
2724 path_iterator path_end() { return path_buffer() + path_size(); }
2725 path_const_iterator path_begin() const { return path_buffer(); }
2726 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2728 void setCastPath(const CXXCastPath &Path);
2730 static bool classof(const Stmt *T) {
2731 return T->getStmtClass() >= firstCastExprConstant &&
2732 T->getStmtClass() <= lastCastExprConstant;
2736 child_range children() { return child_range(&Op, &Op+1); }
2739 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2740 /// conversions, which have no direct representation in the original
2741 /// source code. For example: converting T[]->T*, void f()->void
2742 /// (*f)(), float->double, short->int, etc.
2744 /// In C, implicit casts always produce rvalues. However, in C++, an
2745 /// implicit cast whose result is being bound to a reference will be
2746 /// an lvalue or xvalue. For example:
2750 /// class Derived : public Base { };
2751 /// Derived &&ref();
2752 /// void f(Derived d) {
2753 /// Base& b = d; // initializer is an ImplicitCastExpr
2754 /// // to an lvalue of type Base
2755 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2756 /// // to an xvalue of type Base
2759 class ImplicitCastExpr : public CastExpr {
2761 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2762 unsigned BasePathLength, ExprValueKind VK)
2763 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2766 /// \brief Construct an empty implicit cast.
2767 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2768 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2771 enum OnStack_t { OnStack };
2772 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2774 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2777 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2778 CastKind Kind, Expr *Operand,
2779 const CXXCastPath *BasePath,
2782 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2785 SourceLocation getLocStart() const LLVM_READONLY {
2786 return getSubExpr()->getLocStart();
2788 SourceLocation getLocEnd() const LLVM_READONLY {
2789 return getSubExpr()->getLocEnd();
2792 static bool classof(const Stmt *T) {
2793 return T->getStmtClass() == ImplicitCastExprClass;
2797 inline Expr *Expr::IgnoreImpCasts() {
2799 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2800 e = ice->getSubExpr();
2804 /// ExplicitCastExpr - An explicit cast written in the source
2807 /// This class is effectively an abstract class, because it provides
2808 /// the basic representation of an explicitly-written cast without
2809 /// specifying which kind of cast (C cast, functional cast, static
2810 /// cast, etc.) was written; specific derived classes represent the
2811 /// particular style of cast and its location information.
2813 /// Unlike implicit casts, explicit cast nodes have two different
2814 /// types: the type that was written into the source code, and the
2815 /// actual type of the expression as determined by semantic
2816 /// analysis. These types may differ slightly. For example, in C++ one
2817 /// can cast to a reference type, which indicates that the resulting
2818 /// expression will be an lvalue or xvalue. The reference type, however,
2819 /// will not be used as the type of the expression.
2820 class ExplicitCastExpr : public CastExpr {
2821 /// TInfo - Source type info for the (written) type
2822 /// this expression is casting to.
2823 TypeSourceInfo *TInfo;
2826 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2827 CastKind kind, Expr *op, unsigned PathSize,
2828 TypeSourceInfo *writtenTy)
2829 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2831 /// \brief Construct an empty explicit cast.
2832 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2833 : CastExpr(SC, Shell, PathSize) { }
2836 /// getTypeInfoAsWritten - Returns the type source info for the type
2837 /// that this expression is casting to.
2838 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2839 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2841 /// getTypeAsWritten - Returns the type that this expression is
2842 /// casting to, as written in the source code.
2843 QualType getTypeAsWritten() const { return TInfo->getType(); }
2845 static bool classof(const Stmt *T) {
2846 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2847 T->getStmtClass() <= lastExplicitCastExprConstant;
2851 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2852 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2853 /// (Type)expr. For example: @c (int)f.
2854 class CStyleCastExpr : public ExplicitCastExpr {
2855 SourceLocation LPLoc; // the location of the left paren
2856 SourceLocation RPLoc; // the location of the right paren
2858 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2859 unsigned PathSize, TypeSourceInfo *writtenTy,
2860 SourceLocation l, SourceLocation r)
2861 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2862 writtenTy), LPLoc(l), RPLoc(r) {}
2864 /// \brief Construct an empty C-style explicit cast.
2865 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2866 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2869 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2870 ExprValueKind VK, CastKind K,
2871 Expr *Op, const CXXCastPath *BasePath,
2872 TypeSourceInfo *WrittenTy, SourceLocation L,
2875 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2878 SourceLocation getLParenLoc() const { return LPLoc; }
2879 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2881 SourceLocation getRParenLoc() const { return RPLoc; }
2882 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2884 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2885 SourceLocation getLocEnd() const LLVM_READONLY {
2886 return getSubExpr()->getLocEnd();
2889 static bool classof(const Stmt *T) {
2890 return T->getStmtClass() == CStyleCastExprClass;
2894 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2896 /// This expression node kind describes a builtin binary operation,
2897 /// such as "x + y" for integer values "x" and "y". The operands will
2898 /// already have been converted to appropriate types (e.g., by
2899 /// performing promotions or conversions).
2901 /// In C++, where operators may be overloaded, a different kind of
2902 /// expression node (CXXOperatorCallExpr) is used to express the
2903 /// invocation of an overloaded operator with operator syntax. Within
2904 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2905 /// used to store an expression "x + y" depends on the subexpressions
2906 /// for x and y. If neither x or y is type-dependent, and the "+"
2907 /// operator resolves to a built-in operation, BinaryOperator will be
2908 /// used to express the computation (x and y may still be
2909 /// value-dependent). If either x or y is type-dependent, or if the
2910 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2911 /// be used to express the computation.
2912 class BinaryOperator : public Expr {
2914 typedef BinaryOperatorKind Opcode;
2919 // Records the FP_CONTRACT pragma status at the point that this binary
2920 // operator was parsed. This bit is only meaningful for operations on
2921 // floating point types. For all other types it should default to
2923 unsigned FPContractable : 1;
2924 SourceLocation OpLoc;
2926 enum { LHS, RHS, END_EXPR };
2927 Stmt* SubExprs[END_EXPR];
2930 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2931 ExprValueKind VK, ExprObjectKind OK,
2932 SourceLocation opLoc, bool fpContractable)
2933 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2934 lhs->isTypeDependent() || rhs->isTypeDependent(),
2935 lhs->isValueDependent() || rhs->isValueDependent(),
2936 (lhs->isInstantiationDependent() ||
2937 rhs->isInstantiationDependent()),
2938 (lhs->containsUnexpandedParameterPack() ||
2939 rhs->containsUnexpandedParameterPack())),
2940 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2941 SubExprs[LHS] = lhs;
2942 SubExprs[RHS] = rhs;
2943 assert(!isCompoundAssignmentOp() &&
2944 "Use CompoundAssignOperator for compound assignments");
2947 /// \brief Construct an empty binary operator.
2948 explicit BinaryOperator(EmptyShell Empty)
2949 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2951 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2952 SourceLocation getOperatorLoc() const { return OpLoc; }
2953 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2955 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2956 void setOpcode(Opcode O) { Opc = O; }
2958 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2959 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2960 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2961 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2963 SourceLocation getLocStart() const LLVM_READONLY {
2964 return getLHS()->getLocStart();
2966 SourceLocation getLocEnd() const LLVM_READONLY {
2967 return getRHS()->getLocEnd();
2970 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2971 /// corresponds to, e.g. "<<=".
2972 static StringRef getOpcodeStr(Opcode Op);
2974 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2976 /// \brief Retrieve the binary opcode that corresponds to the given
2977 /// overloaded operator.
2978 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2980 /// \brief Retrieve the overloaded operator kind that corresponds to
2981 /// the given binary opcode.
2982 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2984 /// predicates to categorize the respective opcodes.
2985 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2986 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2987 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2988 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2989 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2990 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2992 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2993 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2995 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2996 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2998 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2999 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3001 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
3002 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3004 static Opcode negateComparisonOp(Opcode Opc) {
3007 llvm_unreachable("Not a comparsion operator.");
3008 case BO_LT: return BO_GE;
3009 case BO_GT: return BO_LE;
3010 case BO_LE: return BO_GT;
3011 case BO_GE: return BO_LT;
3012 case BO_EQ: return BO_NE;
3013 case BO_NE: return BO_EQ;
3017 static Opcode reverseComparisonOp(Opcode Opc) {
3020 llvm_unreachable("Not a comparsion operator.");
3021 case BO_LT: return BO_GT;
3022 case BO_GT: return BO_LT;
3023 case BO_LE: return BO_GE;
3024 case BO_GE: return BO_LE;
3031 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3032 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3034 static bool isAssignmentOp(Opcode Opc) {
3035 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3037 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3039 static bool isCompoundAssignmentOp(Opcode Opc) {
3040 return Opc > BO_Assign && Opc <= BO_OrAssign;
3042 bool isCompoundAssignmentOp() const {
3043 return isCompoundAssignmentOp(getOpcode());
3045 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3046 assert(isCompoundAssignmentOp(Opc));
3047 if (Opc >= BO_AndAssign)
3048 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3050 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3053 static bool isShiftAssignOp(Opcode Opc) {
3054 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3056 bool isShiftAssignOp() const {
3057 return isShiftAssignOp(getOpcode());
3060 static bool classof(const Stmt *S) {
3061 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3062 S->getStmtClass() <= lastBinaryOperatorConstant;
3066 child_range children() {
3067 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3070 // Set the FP contractability status of this operator. Only meaningful for
3071 // operations on floating point types.
3072 void setFPContractable(bool FPC) { FPContractable = FPC; }
3074 // Get the FP contractability status of this operator. Only meaningful for
3075 // operations on floating point types.
3076 bool isFPContractable() const { return FPContractable; }
3079 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3080 ExprValueKind VK, ExprObjectKind OK,
3081 SourceLocation opLoc, bool fpContractable, bool dead2)
3082 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3083 lhs->isTypeDependent() || rhs->isTypeDependent(),
3084 lhs->isValueDependent() || rhs->isValueDependent(),
3085 (lhs->isInstantiationDependent() ||
3086 rhs->isInstantiationDependent()),
3087 (lhs->containsUnexpandedParameterPack() ||
3088 rhs->containsUnexpandedParameterPack())),
3089 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3090 SubExprs[LHS] = lhs;
3091 SubExprs[RHS] = rhs;
3094 BinaryOperator(StmtClass SC, EmptyShell Empty)
3095 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3098 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3099 /// track of the type the operation is performed in. Due to the semantics of
3100 /// these operators, the operands are promoted, the arithmetic performed, an
3101 /// implicit conversion back to the result type done, then the assignment takes
3102 /// place. This captures the intermediate type which the computation is done
3104 class CompoundAssignOperator : public BinaryOperator {
3105 QualType ComputationLHSType;
3106 QualType ComputationResultType;
3108 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3109 ExprValueKind VK, ExprObjectKind OK,
3110 QualType CompLHSType, QualType CompResultType,
3111 SourceLocation OpLoc, bool fpContractable)
3112 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3114 ComputationLHSType(CompLHSType),
3115 ComputationResultType(CompResultType) {
3116 assert(isCompoundAssignmentOp() &&
3117 "Only should be used for compound assignments");
3120 /// \brief Build an empty compound assignment operator expression.
3121 explicit CompoundAssignOperator(EmptyShell Empty)
3122 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3124 // The two computation types are the type the LHS is converted
3125 // to for the computation and the type of the result; the two are
3126 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3127 QualType getComputationLHSType() const { return ComputationLHSType; }
3128 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3130 QualType getComputationResultType() const { return ComputationResultType; }
3131 void setComputationResultType(QualType T) { ComputationResultType = T; }
3133 static bool classof(const Stmt *S) {
3134 return S->getStmtClass() == CompoundAssignOperatorClass;
3138 /// AbstractConditionalOperator - An abstract base class for
3139 /// ConditionalOperator and BinaryConditionalOperator.
3140 class AbstractConditionalOperator : public Expr {
3141 SourceLocation QuestionLoc, ColonLoc;
3142 friend class ASTStmtReader;
3145 AbstractConditionalOperator(StmtClass SC, QualType T,
3146 ExprValueKind VK, ExprObjectKind OK,
3147 bool TD, bool VD, bool ID,
3148 bool ContainsUnexpandedParameterPack,
3149 SourceLocation qloc,
3150 SourceLocation cloc)
3151 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3152 QuestionLoc(qloc), ColonLoc(cloc) {}
3154 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3155 : Expr(SC, Empty) { }
3158 // getCond - Return the expression representing the condition for
3160 Expr *getCond() const;
3162 // getTrueExpr - Return the subexpression representing the value of
3163 // the expression if the condition evaluates to true.
3164 Expr *getTrueExpr() const;
3166 // getFalseExpr - Return the subexpression representing the value of
3167 // the expression if the condition evaluates to false. This is
3168 // the same as getRHS.
3169 Expr *getFalseExpr() const;
3171 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3172 SourceLocation getColonLoc() const { return ColonLoc; }
3174 static bool classof(const Stmt *T) {
3175 return T->getStmtClass() == ConditionalOperatorClass ||
3176 T->getStmtClass() == BinaryConditionalOperatorClass;
3180 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3181 /// middle" extension is a BinaryConditionalOperator.
3182 class ConditionalOperator : public AbstractConditionalOperator {
3183 enum { COND, LHS, RHS, END_EXPR };
3184 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3186 friend class ASTStmtReader;
3188 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3189 SourceLocation CLoc, Expr *rhs,
3190 QualType t, ExprValueKind VK, ExprObjectKind OK)
3191 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3192 // FIXME: the type of the conditional operator doesn't
3193 // depend on the type of the conditional, but the standard
3194 // seems to imply that it could. File a bug!
3195 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3196 (cond->isValueDependent() || lhs->isValueDependent() ||
3197 rhs->isValueDependent()),
3198 (cond->isInstantiationDependent() ||
3199 lhs->isInstantiationDependent() ||
3200 rhs->isInstantiationDependent()),
3201 (cond->containsUnexpandedParameterPack() ||
3202 lhs->containsUnexpandedParameterPack() ||
3203 rhs->containsUnexpandedParameterPack()),
3205 SubExprs[COND] = cond;
3206 SubExprs[LHS] = lhs;
3207 SubExprs[RHS] = rhs;
3210 /// \brief Build an empty conditional operator.
3211 explicit ConditionalOperator(EmptyShell Empty)
3212 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3214 // getCond - Return the expression representing the condition for
3216 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3218 // getTrueExpr - Return the subexpression representing the value of
3219 // the expression if the condition evaluates to true.
3220 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3222 // getFalseExpr - Return the subexpression representing the value of
3223 // the expression if the condition evaluates to false. This is
3224 // the same as getRHS.
3225 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3227 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3228 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3230 SourceLocation getLocStart() const LLVM_READONLY {
3231 return getCond()->getLocStart();
3233 SourceLocation getLocEnd() const LLVM_READONLY {
3234 return getRHS()->getLocEnd();
3237 static bool classof(const Stmt *T) {
3238 return T->getStmtClass() == ConditionalOperatorClass;
3242 child_range children() {
3243 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3247 /// BinaryConditionalOperator - The GNU extension to the conditional
3248 /// operator which allows the middle operand to be omitted.
3250 /// This is a different expression kind on the assumption that almost
3251 /// every client ends up needing to know that these are different.
3252 class BinaryConditionalOperator : public AbstractConditionalOperator {
3253 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3255 /// - the common condition/left-hand-side expression, which will be
3256 /// evaluated as the opaque value
3257 /// - the condition, expressed in terms of the opaque value
3258 /// - the left-hand-side, expressed in terms of the opaque value
3259 /// - the right-hand-side
3260 Stmt *SubExprs[NUM_SUBEXPRS];
3261 OpaqueValueExpr *OpaqueValue;
3263 friend class ASTStmtReader;
3265 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3266 Expr *cond, Expr *lhs, Expr *rhs,
3267 SourceLocation qloc, SourceLocation cloc,
3268 QualType t, ExprValueKind VK, ExprObjectKind OK)
3269 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3270 (common->isTypeDependent() || rhs->isTypeDependent()),
3271 (common->isValueDependent() || rhs->isValueDependent()),
3272 (common->isInstantiationDependent() ||
3273 rhs->isInstantiationDependent()),
3274 (common->containsUnexpandedParameterPack() ||
3275 rhs->containsUnexpandedParameterPack()),
3277 OpaqueValue(opaqueValue) {
3278 SubExprs[COMMON] = common;
3279 SubExprs[COND] = cond;
3280 SubExprs[LHS] = lhs;
3281 SubExprs[RHS] = rhs;
3282 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3285 /// \brief Build an empty conditional operator.
3286 explicit BinaryConditionalOperator(EmptyShell Empty)
3287 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3289 /// \brief getCommon - Return the common expression, written to the
3290 /// left of the condition. The opaque value will be bound to the
3291 /// result of this expression.
3292 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3294 /// \brief getOpaqueValue - Return the opaque value placeholder.
3295 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3297 /// \brief getCond - Return the condition expression; this is defined
3298 /// in terms of the opaque value.
3299 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3301 /// \brief getTrueExpr - Return the subexpression which will be
3302 /// evaluated if the condition evaluates to true; this is defined
3303 /// in terms of the opaque value.
3304 Expr *getTrueExpr() const {
3305 return cast<Expr>(SubExprs[LHS]);
3308 /// \brief getFalseExpr - Return the subexpression which will be
3309 /// evaluated if the condnition evaluates to false; this is
3310 /// defined in terms of the opaque value.
3311 Expr *getFalseExpr() const {
3312 return cast<Expr>(SubExprs[RHS]);
3315 SourceLocation getLocStart() const LLVM_READONLY {
3316 return getCommon()->getLocStart();
3318 SourceLocation getLocEnd() const LLVM_READONLY {
3319 return getFalseExpr()->getLocEnd();
3322 static bool classof(const Stmt *T) {
3323 return T->getStmtClass() == BinaryConditionalOperatorClass;
3327 child_range children() {
3328 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3332 inline Expr *AbstractConditionalOperator::getCond() const {
3333 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3334 return co->getCond();
3335 return cast<BinaryConditionalOperator>(this)->getCond();
3338 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3339 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3340 return co->getTrueExpr();
3341 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3344 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3345 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3346 return co->getFalseExpr();
3347 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3350 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3351 class AddrLabelExpr : public Expr {
3352 SourceLocation AmpAmpLoc, LabelLoc;
3355 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3357 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3359 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3361 /// \brief Build an empty address of a label expression.
3362 explicit AddrLabelExpr(EmptyShell Empty)
3363 : Expr(AddrLabelExprClass, Empty) { }
3365 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3366 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3367 SourceLocation getLabelLoc() const { return LabelLoc; }
3368 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3370 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3371 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3373 LabelDecl *getLabel() const { return Label; }
3374 void setLabel(LabelDecl *L) { Label = L; }
3376 static bool classof(const Stmt *T) {
3377 return T->getStmtClass() == AddrLabelExprClass;
3381 child_range children() { return child_range(); }
3384 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3385 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3386 /// takes the value of the last subexpression.
3388 /// A StmtExpr is always an r-value; values "returned" out of a
3389 /// StmtExpr will be copied.
3390 class StmtExpr : public Expr {
3392 SourceLocation LParenLoc, RParenLoc;
3394 // FIXME: Does type-dependence need to be computed differently?
3395 // FIXME: Do we need to compute instantiation instantiation-dependence for
3396 // statements? (ugh!)
3397 StmtExpr(CompoundStmt *substmt, QualType T,
3398 SourceLocation lp, SourceLocation rp) :
3399 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3400 T->isDependentType(), false, false, false),
3401 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3403 /// \brief Build an empty statement expression.
3404 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3406 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3407 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3408 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3410 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3411 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3413 SourceLocation getLParenLoc() const { return LParenLoc; }
3414 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3415 SourceLocation getRParenLoc() const { return RParenLoc; }
3416 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3418 static bool classof(const Stmt *T) {
3419 return T->getStmtClass() == StmtExprClass;
3423 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3427 /// ShuffleVectorExpr - clang-specific builtin-in function
3428 /// __builtin_shufflevector.
3429 /// This AST node represents a operator that does a constant
3430 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3431 /// two vectors and a variable number of constant indices,
3432 /// and returns the appropriately shuffled vector.
3433 class ShuffleVectorExpr : public Expr {
3434 SourceLocation BuiltinLoc, RParenLoc;
3436 // SubExprs - the list of values passed to the __builtin_shufflevector
3437 // function. The first two are vectors, and the rest are constant
3438 // indices. The number of values in this list is always
3439 // 2+the number of indices in the vector type.
3444 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3445 SourceLocation BLoc, SourceLocation RP);
3447 /// \brief Build an empty vector-shuffle expression.
3448 explicit ShuffleVectorExpr(EmptyShell Empty)
3449 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3451 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3452 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3454 SourceLocation getRParenLoc() const { return RParenLoc; }
3455 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3457 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3458 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3460 static bool classof(const Stmt *T) {
3461 return T->getStmtClass() == ShuffleVectorExprClass;
3464 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3465 /// constant expression, the actual arguments passed in, and the function
3467 unsigned getNumSubExprs() const { return NumExprs; }
3469 /// \brief Retrieve the array of expressions.
3470 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3472 /// getExpr - Return the Expr at the specified index.
3473 Expr *getExpr(unsigned Index) {
3474 assert((Index < NumExprs) && "Arg access out of range!");
3475 return cast<Expr>(SubExprs[Index]);
3477 const Expr *getExpr(unsigned Index) const {
3478 assert((Index < NumExprs) && "Arg access out of range!");
3479 return cast<Expr>(SubExprs[Index]);
3482 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3484 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3485 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3486 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3490 child_range children() {
3491 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3495 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3496 /// This AST node provides support for converting a vector type to another
3497 /// vector type of the same arity.
3498 class ConvertVectorExpr : public Expr {
3501 TypeSourceInfo *TInfo;
3502 SourceLocation BuiltinLoc, RParenLoc;
3504 friend class ASTReader;
3505 friend class ASTStmtReader;
3506 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3509 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3510 ExprValueKind VK, ExprObjectKind OK,
3511 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3512 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3513 DstType->isDependentType(),
3514 DstType->isDependentType() || SrcExpr->isValueDependent(),
3515 (DstType->isInstantiationDependentType() ||
3516 SrcExpr->isInstantiationDependent()),
3517 (DstType->containsUnexpandedParameterPack() ||
3518 SrcExpr->containsUnexpandedParameterPack())),
3519 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3521 /// getSrcExpr - Return the Expr to be converted.
3522 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3524 /// getTypeSourceInfo - Return the destination type.
3525 TypeSourceInfo *getTypeSourceInfo() const {
3528 void setTypeSourceInfo(TypeSourceInfo *ti) {
3532 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3533 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3535 /// getRParenLoc - Return the location of final right parenthesis.
3536 SourceLocation getRParenLoc() const { return RParenLoc; }
3538 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3539 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3541 static bool classof(const Stmt *T) {
3542 return T->getStmtClass() == ConvertVectorExprClass;
3546 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3549 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3550 /// This AST node is similar to the conditional operator (?:) in C, with
3551 /// the following exceptions:
3552 /// - the test expression must be a integer constant expression.
3553 /// - the expression returned acts like the chosen subexpression in every
3554 /// visible way: the type is the same as that of the chosen subexpression,
3555 /// and all predicates (whether it's an l-value, whether it's an integer
3556 /// constant expression, etc.) return the same result as for the chosen
3558 class ChooseExpr : public Expr {
3559 enum { COND, LHS, RHS, END_EXPR };
3560 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3561 SourceLocation BuiltinLoc, RParenLoc;
3564 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3565 QualType t, ExprValueKind VK, ExprObjectKind OK,
3566 SourceLocation RP, bool condIsTrue,
3567 bool TypeDependent, bool ValueDependent)
3568 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3569 (cond->isInstantiationDependent() ||
3570 lhs->isInstantiationDependent() ||
3571 rhs->isInstantiationDependent()),
3572 (cond->containsUnexpandedParameterPack() ||
3573 lhs->containsUnexpandedParameterPack() ||
3574 rhs->containsUnexpandedParameterPack())),
3575 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3576 SubExprs[COND] = cond;
3577 SubExprs[LHS] = lhs;
3578 SubExprs[RHS] = rhs;
3581 /// \brief Build an empty __builtin_choose_expr.
3582 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3584 /// isConditionTrue - Return whether the condition is true (i.e. not
3586 bool isConditionTrue() const {
3587 assert(!isConditionDependent() &&
3588 "Dependent condition isn't true or false");
3591 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3593 bool isConditionDependent() const {
3594 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3597 /// getChosenSubExpr - Return the subexpression chosen according to the
3599 Expr *getChosenSubExpr() const {
3600 return isConditionTrue() ? getLHS() : getRHS();
3603 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3604 void setCond(Expr *E) { SubExprs[COND] = E; }
3605 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3606 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3607 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3608 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3610 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3611 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3613 SourceLocation getRParenLoc() const { return RParenLoc; }
3614 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3616 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3617 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3619 static bool classof(const Stmt *T) {
3620 return T->getStmtClass() == ChooseExprClass;
3624 child_range children() {
3625 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3629 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3630 /// for a null pointer constant that has integral type (e.g., int or
3631 /// long) and is the same size and alignment as a pointer. The __null
3632 /// extension is typically only used by system headers, which define
3633 /// NULL as __null in C++ rather than using 0 (which is an integer
3634 /// that may not match the size of a pointer).
3635 class GNUNullExpr : public Expr {
3636 /// TokenLoc - The location of the __null keyword.
3637 SourceLocation TokenLoc;
3640 GNUNullExpr(QualType Ty, SourceLocation Loc)
3641 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3645 /// \brief Build an empty GNU __null expression.
3646 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3648 /// getTokenLocation - The location of the __null token.
3649 SourceLocation getTokenLocation() const { return TokenLoc; }
3650 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3652 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3653 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3655 static bool classof(const Stmt *T) {
3656 return T->getStmtClass() == GNUNullExprClass;
3660 child_range children() { return child_range(); }
3663 /// VAArgExpr, used for the builtin function __builtin_va_arg.
3664 class VAArgExpr : public Expr {
3666 TypeSourceInfo *TInfo;
3667 SourceLocation BuiltinLoc, RParenLoc;
3669 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3670 SourceLocation RPLoc, QualType t)
3671 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3672 t->isDependentType(), false,
3673 (TInfo->getType()->isInstantiationDependentType() ||
3674 e->isInstantiationDependent()),
3675 (TInfo->getType()->containsUnexpandedParameterPack() ||
3676 e->containsUnexpandedParameterPack())),
3677 Val(e), TInfo(TInfo),
3679 RParenLoc(RPLoc) { }
3681 /// \brief Create an empty __builtin_va_arg expression.
3682 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3684 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3685 Expr *getSubExpr() { return cast<Expr>(Val); }
3686 void setSubExpr(Expr *E) { Val = E; }
3688 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3689 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3691 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3692 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3694 SourceLocation getRParenLoc() const { return RParenLoc; }
3695 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3697 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3698 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3700 static bool classof(const Stmt *T) {
3701 return T->getStmtClass() == VAArgExprClass;
3705 child_range children() { return child_range(&Val, &Val+1); }
3708 /// @brief Describes an C or C++ initializer list.
3710 /// InitListExpr describes an initializer list, which can be used to
3711 /// initialize objects of different types, including
3712 /// struct/class/union types, arrays, and vectors. For example:
3715 /// struct foo x = { 1, { 2, 3 } };
3718 /// Prior to semantic analysis, an initializer list will represent the
3719 /// initializer list as written by the user, but will have the
3720 /// placeholder type "void". This initializer list is called the
3721 /// syntactic form of the initializer, and may contain C99 designated
3722 /// initializers (represented as DesignatedInitExprs), initializations
3723 /// of subobject members without explicit braces, and so on. Clients
3724 /// interested in the original syntax of the initializer list should
3725 /// use the syntactic form of the initializer list.
3727 /// After semantic analysis, the initializer list will represent the
3728 /// semantic form of the initializer, where the initializations of all
3729 /// subobjects are made explicit with nested InitListExpr nodes and
3730 /// C99 designators have been eliminated by placing the designated
3731 /// initializations into the subobject they initialize. Additionally,
3732 /// any "holes" in the initialization, where no initializer has been
3733 /// specified for a particular subobject, will be replaced with
3734 /// implicitly-generated ImplicitValueInitExpr expressions that
3735 /// value-initialize the subobjects. Note, however, that the
3736 /// initializer lists may still have fewer initializers than there are
3737 /// elements to initialize within the object.
3739 /// After semantic analysis has completed, given an initializer list,
3740 /// method isSemanticForm() returns true if and only if this is the
3741 /// semantic form of the initializer list (note: the same AST node
3742 /// may at the same time be the syntactic form).
3743 /// Given the semantic form of the initializer list, one can retrieve
3744 /// the syntactic form of that initializer list (when different)
3745 /// using method getSyntacticForm(); the method returns null if applied
3746 /// to a initializer list which is already in syntactic form.
3747 /// Similarly, given the syntactic form (i.e., an initializer list such
3748 /// that isSemanticForm() returns false), one can retrieve the semantic
3749 /// form using method getSemanticForm().
3750 /// Since many initializer lists have the same syntactic and semantic forms,
3751 /// getSyntacticForm() may return NULL, indicating that the current
3752 /// semantic initializer list also serves as its syntactic form.
3753 class InitListExpr : public Expr {
3754 // FIXME: Eliminate this vector in favor of ASTContext allocation
3755 typedef ASTVector<Stmt *> InitExprsTy;
3756 InitExprsTy InitExprs;
3757 SourceLocation LBraceLoc, RBraceLoc;
3759 /// The alternative form of the initializer list (if it exists).
3760 /// The int part of the pair stores whether this initializer list is
3761 /// in semantic form. If not null, the pointer points to:
3762 /// - the syntactic form, if this is in semantic form;
3763 /// - the semantic form, if this is in syntactic form.
3764 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3767 /// If this initializer list initializes an array with more elements than
3768 /// there are initializers in the list, specifies an expression to be used
3769 /// for value initialization of the rest of the elements.
3771 /// If this initializer list initializes a union, specifies which
3772 /// field within the union will be initialized.
3773 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3776 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3777 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3779 /// \brief Build an empty initializer list.
3780 explicit InitListExpr(EmptyShell Empty)
3781 : Expr(InitListExprClass, Empty) { }
3783 unsigned getNumInits() const { return InitExprs.size(); }
3785 /// \brief Retrieve the set of initializers.
3786 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3788 const Expr *getInit(unsigned Init) const {
3789 assert(Init < getNumInits() && "Initializer access out of range!");
3790 return cast_or_null<Expr>(InitExprs[Init]);
3793 Expr *getInit(unsigned Init) {
3794 assert(Init < getNumInits() && "Initializer access out of range!");
3795 return cast_or_null<Expr>(InitExprs[Init]);
3798 void setInit(unsigned Init, Expr *expr) {
3799 assert(Init < getNumInits() && "Initializer access out of range!");
3800 InitExprs[Init] = expr;
3803 ExprBits.TypeDependent |= expr->isTypeDependent();
3804 ExprBits.ValueDependent |= expr->isValueDependent();
3805 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3806 ExprBits.ContainsUnexpandedParameterPack |=
3807 expr->containsUnexpandedParameterPack();
3811 /// \brief Reserve space for some number of initializers.
3812 void reserveInits(const ASTContext &C, unsigned NumInits);
3814 /// @brief Specify the number of initializers
3816 /// If there are more than @p NumInits initializers, the remaining
3817 /// initializers will be destroyed. If there are fewer than @p
3818 /// NumInits initializers, NULL expressions will be added for the
3819 /// unknown initializers.
3820 void resizeInits(const ASTContext &Context, unsigned NumInits);
3822 /// @brief Updates the initializer at index @p Init with the new
3823 /// expression @p expr, and returns the old expression at that
3826 /// When @p Init is out of range for this initializer list, the
3827 /// initializer list will be extended with NULL expressions to
3828 /// accommodate the new entry.
3829 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3831 /// \brief If this initializer list initializes an array with more elements
3832 /// than there are initializers in the list, specifies an expression to be
3833 /// used for value initialization of the rest of the elements.
3834 Expr *getArrayFiller() {
3835 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3837 const Expr *getArrayFiller() const {
3838 return const_cast<InitListExpr *>(this)->getArrayFiller();
3840 void setArrayFiller(Expr *filler);
3842 /// \brief Return true if this is an array initializer and its array "filler"
3844 bool hasArrayFiller() const { return getArrayFiller(); }
3846 /// \brief If this initializes a union, specifies which field in the
3847 /// union to initialize.
3849 /// Typically, this field is the first named field within the
3850 /// union. However, a designated initializer can specify the
3851 /// initialization of a different field within the union.
3852 FieldDecl *getInitializedFieldInUnion() {
3853 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3855 const FieldDecl *getInitializedFieldInUnion() const {
3856 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3858 void setInitializedFieldInUnion(FieldDecl *FD) {
3859 assert((FD == nullptr
3860 || getInitializedFieldInUnion() == nullptr
3861 || getInitializedFieldInUnion() == FD)
3862 && "Only one field of a union may be initialized at a time!");
3863 ArrayFillerOrUnionFieldInit = FD;
3866 // Explicit InitListExpr's originate from source code (and have valid source
3867 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3869 return LBraceLoc.isValid() && RBraceLoc.isValid();
3872 // Is this an initializer for an array of characters, initialized by a string
3873 // literal or an @encode?
3874 bool isStringLiteralInit() const;
3876 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3877 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3878 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3879 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3881 bool isSemanticForm() const { return AltForm.getInt(); }
3882 InitListExpr *getSemanticForm() const {
3883 return isSemanticForm() ? nullptr : AltForm.getPointer();
3885 InitListExpr *getSyntacticForm() const {
3886 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3889 void setSyntacticForm(InitListExpr *Init) {
3890 AltForm.setPointer(Init);
3891 AltForm.setInt(true);
3892 Init->AltForm.setPointer(this);
3893 Init->AltForm.setInt(false);
3896 bool hadArrayRangeDesignator() const {
3897 return InitListExprBits.HadArrayRangeDesignator != 0;
3899 void sawArrayRangeDesignator(bool ARD = true) {
3900 InitListExprBits.HadArrayRangeDesignator = ARD;
3903 SourceLocation getLocStart() const LLVM_READONLY;
3904 SourceLocation getLocEnd() const LLVM_READONLY;
3906 static bool classof(const Stmt *T) {
3907 return T->getStmtClass() == InitListExprClass;
3911 child_range children() {
3912 // FIXME: This does not include the array filler expression.
3913 if (InitExprs.empty()) return child_range();
3914 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3917 typedef InitExprsTy::iterator iterator;
3918 typedef InitExprsTy::const_iterator const_iterator;
3919 typedef InitExprsTy::reverse_iterator reverse_iterator;
3920 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3922 iterator begin() { return InitExprs.begin(); }
3923 const_iterator begin() const { return InitExprs.begin(); }
3924 iterator end() { return InitExprs.end(); }
3925 const_iterator end() const { return InitExprs.end(); }
3926 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3927 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3928 reverse_iterator rend() { return InitExprs.rend(); }
3929 const_reverse_iterator rend() const { return InitExprs.rend(); }
3931 friend class ASTStmtReader;
3932 friend class ASTStmtWriter;
3935 /// @brief Represents a C99 designated initializer expression.
3937 /// A designated initializer expression (C99 6.7.8) contains one or
3938 /// more designators (which can be field designators, array
3939 /// designators, or GNU array-range designators) followed by an
3940 /// expression that initializes the field or element(s) that the
3941 /// designators refer to. For example, given:
3948 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3951 /// The InitListExpr contains three DesignatedInitExprs, the first of
3952 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3953 /// designators, one array designator for @c [2] followed by one field
3954 /// designator for @c .y. The initialization expression will be 1.0.
3955 class DesignatedInitExpr : public Expr {
3957 /// \brief Forward declaration of the Designator class.
3961 /// The location of the '=' or ':' prior to the actual initializer
3963 SourceLocation EqualOrColonLoc;
3965 /// Whether this designated initializer used the GNU deprecated
3966 /// syntax rather than the C99 '=' syntax.
3969 /// The number of designators in this initializer expression.
3970 unsigned NumDesignators : 15;
3972 /// The number of subexpressions of this initializer expression,
3973 /// which contains both the initializer and any additional
3974 /// expressions used by array and array-range designators.
3975 unsigned NumSubExprs : 16;
3977 /// \brief The designators in this designated initialization
3979 Designator *Designators;
3982 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3983 const Designator *Designators,
3984 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3985 ArrayRef<Expr*> IndexExprs, Expr *Init);
3987 explicit DesignatedInitExpr(unsigned NumSubExprs)
3988 : Expr(DesignatedInitExprClass, EmptyShell()),
3989 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
3992 /// A field designator, e.g., ".x".
3993 struct FieldDesignator {
3994 /// Refers to the field that is being initialized. The low bit
3995 /// of this field determines whether this is actually a pointer
3996 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3997 /// initially constructed, a field designator will store an
3998 /// IdentifierInfo*. After semantic analysis has resolved that
3999 /// name, the field designator will instead store a FieldDecl*.
4000 uintptr_t NameOrField;
4002 /// The location of the '.' in the designated initializer.
4005 /// The location of the field name in the designated initializer.
4009 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4010 struct ArrayOrRangeDesignator {
4011 /// Location of the first index expression within the designated
4012 /// initializer expression's list of subexpressions.
4014 /// The location of the '[' starting the array range designator.
4015 unsigned LBracketLoc;
4016 /// The location of the ellipsis separating the start and end
4017 /// indices. Only valid for GNU array-range designators.
4018 unsigned EllipsisLoc;
4019 /// The location of the ']' terminating the array range designator.
4020 unsigned RBracketLoc;
4023 /// @brief Represents a single C99 designator.
4025 /// @todo This class is infuriatingly similar to clang::Designator,
4026 /// but minor differences (storing indices vs. storing pointers)
4027 /// keep us from reusing it. Try harder, later, to rectify these
4030 /// @brief The kind of designator this describes.
4034 ArrayRangeDesignator
4038 /// A field designator, e.g., ".x".
4039 struct FieldDesignator Field;
4040 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4041 struct ArrayOrRangeDesignator ArrayOrRange;
4043 friend class DesignatedInitExpr;
4048 /// @brief Initializes a field designator.
4049 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4050 SourceLocation FieldLoc)
4051 : Kind(FieldDesignator) {
4052 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4053 Field.DotLoc = DotLoc.getRawEncoding();
4054 Field.FieldLoc = FieldLoc.getRawEncoding();
4057 /// @brief Initializes an array designator.
4058 Designator(unsigned Index, SourceLocation LBracketLoc,
4059 SourceLocation RBracketLoc)
4060 : Kind(ArrayDesignator) {
4061 ArrayOrRange.Index = Index;
4062 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4063 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4064 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4067 /// @brief Initializes a GNU array-range designator.
4068 Designator(unsigned Index, SourceLocation LBracketLoc,
4069 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4070 : Kind(ArrayRangeDesignator) {
4071 ArrayOrRange.Index = Index;
4072 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4073 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4074 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4077 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4078 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4079 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4081 IdentifierInfo *getFieldName() const;
4083 FieldDecl *getField() const {
4084 assert(Kind == FieldDesignator && "Only valid on a field designator");
4085 if (Field.NameOrField & 0x01)
4088 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4091 void setField(FieldDecl *FD) {
4092 assert(Kind == FieldDesignator && "Only valid on a field designator");
4093 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4096 SourceLocation getDotLoc() const {
4097 assert(Kind == FieldDesignator && "Only valid on a field designator");
4098 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4101 SourceLocation getFieldLoc() const {
4102 assert(Kind == FieldDesignator && "Only valid on a field designator");
4103 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4106 SourceLocation getLBracketLoc() const {
4107 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4108 "Only valid on an array or array-range designator");
4109 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4112 SourceLocation getRBracketLoc() const {
4113 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4114 "Only valid on an array or array-range designator");
4115 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4118 SourceLocation getEllipsisLoc() const {
4119 assert(Kind == ArrayRangeDesignator &&
4120 "Only valid on an array-range designator");
4121 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4124 unsigned getFirstExprIndex() const {
4125 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4126 "Only valid on an array or array-range designator");
4127 return ArrayOrRange.Index;
4130 SourceLocation getLocStart() const LLVM_READONLY {
4131 if (Kind == FieldDesignator)
4132 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4134 return getLBracketLoc();
4136 SourceLocation getLocEnd() const LLVM_READONLY {
4137 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4139 SourceRange getSourceRange() const LLVM_READONLY {
4140 return SourceRange(getLocStart(), getLocEnd());
4144 static DesignatedInitExpr *Create(const ASTContext &C,
4145 Designator *Designators,
4146 unsigned NumDesignators,
4147 ArrayRef<Expr*> IndexExprs,
4148 SourceLocation EqualOrColonLoc,
4149 bool GNUSyntax, Expr *Init);
4151 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4152 unsigned NumIndexExprs);
4154 /// @brief Returns the number of designators in this initializer.
4155 unsigned size() const { return NumDesignators; }
4157 // Iterator access to the designators.
4158 typedef Designator *designators_iterator;
4159 designators_iterator designators_begin() { return Designators; }
4160 designators_iterator designators_end() {
4161 return Designators + NumDesignators;
4164 typedef const Designator *const_designators_iterator;
4165 const_designators_iterator designators_begin() const { return Designators; }
4166 const_designators_iterator designators_end() const {
4167 return Designators + NumDesignators;
4170 typedef llvm::iterator_range<designators_iterator> designators_range;
4171 designators_range designators() {
4172 return designators_range(designators_begin(), designators_end());
4175 typedef llvm::iterator_range<const_designators_iterator>
4176 designators_const_range;
4177 designators_const_range designators() const {
4178 return designators_const_range(designators_begin(), designators_end());
4181 typedef std::reverse_iterator<designators_iterator>
4182 reverse_designators_iterator;
4183 reverse_designators_iterator designators_rbegin() {
4184 return reverse_designators_iterator(designators_end());
4186 reverse_designators_iterator designators_rend() {
4187 return reverse_designators_iterator(designators_begin());
4190 typedef std::reverse_iterator<const_designators_iterator>
4191 const_reverse_designators_iterator;
4192 const_reverse_designators_iterator designators_rbegin() const {
4193 return const_reverse_designators_iterator(designators_end());
4195 const_reverse_designators_iterator designators_rend() const {
4196 return const_reverse_designators_iterator(designators_begin());
4199 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4201 void setDesignators(const ASTContext &C, const Designator *Desigs,
4202 unsigned NumDesigs);
4204 Expr *getArrayIndex(const Designator &D) const;
4205 Expr *getArrayRangeStart(const Designator &D) const;
4206 Expr *getArrayRangeEnd(const Designator &D) const;
4208 /// @brief Retrieve the location of the '=' that precedes the
4209 /// initializer value itself, if present.
4210 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4211 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4213 /// @brief Determines whether this designated initializer used the
4214 /// deprecated GNU syntax for designated initializers.
4215 bool usesGNUSyntax() const { return GNUSyntax; }
4216 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4218 /// @brief Retrieve the initializer value.
4219 Expr *getInit() const {
4220 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4223 void setInit(Expr *init) {
4224 *child_begin() = init;
4227 /// \brief Retrieve the total number of subexpressions in this
4228 /// designated initializer expression, including the actual
4229 /// initialized value and any expressions that occur within array
4230 /// and array-range designators.
4231 unsigned getNumSubExprs() const { return NumSubExprs; }
4233 Expr *getSubExpr(unsigned Idx) const {
4234 assert(Idx < NumSubExprs && "Subscript out of range");
4235 return cast<Expr>(reinterpret_cast<Stmt *const *>(this + 1)[Idx]);
4238 void setSubExpr(unsigned Idx, Expr *E) {
4239 assert(Idx < NumSubExprs && "Subscript out of range");
4240 reinterpret_cast<Stmt **>(this + 1)[Idx] = E;
4243 /// \brief Replaces the designator at index @p Idx with the series
4244 /// of designators in [First, Last).
4245 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4246 const Designator *First, const Designator *Last);
4248 SourceRange getDesignatorsSourceRange() const;
4250 SourceLocation getLocStart() const LLVM_READONLY;
4251 SourceLocation getLocEnd() const LLVM_READONLY;
4253 static bool classof(const Stmt *T) {
4254 return T->getStmtClass() == DesignatedInitExprClass;
4258 child_range children() {
4259 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4260 return child_range(begin, begin + NumSubExprs);
4264 /// \brief Represents an implicitly-generated value initialization of
4265 /// an object of a given type.
4267 /// Implicit value initializations occur within semantic initializer
4268 /// list expressions (InitListExpr) as placeholders for subobject
4269 /// initializations not explicitly specified by the user.
4271 /// \see InitListExpr
4272 class ImplicitValueInitExpr : public Expr {
4274 explicit ImplicitValueInitExpr(QualType ty)
4275 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4276 false, false, ty->isInstantiationDependentType(), false) { }
4278 /// \brief Construct an empty implicit value initialization.
4279 explicit ImplicitValueInitExpr(EmptyShell Empty)
4280 : Expr(ImplicitValueInitExprClass, Empty) { }
4282 static bool classof(const Stmt *T) {
4283 return T->getStmtClass() == ImplicitValueInitExprClass;
4286 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4287 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4290 child_range children() { return child_range(); }
4294 class ParenListExpr : public Expr {
4297 SourceLocation LParenLoc, RParenLoc;
4300 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4301 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4303 /// \brief Build an empty paren list.
4304 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4306 unsigned getNumExprs() const { return NumExprs; }
4308 const Expr* getExpr(unsigned Init) const {
4309 assert(Init < getNumExprs() && "Initializer access out of range!");
4310 return cast_or_null<Expr>(Exprs[Init]);
4313 Expr* getExpr(unsigned Init) {
4314 assert(Init < getNumExprs() && "Initializer access out of range!");
4315 return cast_or_null<Expr>(Exprs[Init]);
4318 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4320 SourceLocation getLParenLoc() const { return LParenLoc; }
4321 SourceLocation getRParenLoc() const { return RParenLoc; }
4323 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4324 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4326 static bool classof(const Stmt *T) {
4327 return T->getStmtClass() == ParenListExprClass;
4331 child_range children() {
4332 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4335 friend class ASTStmtReader;
4336 friend class ASTStmtWriter;
4340 /// \brief Represents a C11 generic selection.
4342 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4343 /// expression, followed by one or more generic associations. Each generic
4344 /// association specifies a type name and an expression, or "default" and an
4345 /// expression (in which case it is known as a default generic association).
4346 /// The type and value of the generic selection are identical to those of its
4347 /// result expression, which is defined as the expression in the generic
4348 /// association with a type name that is compatible with the type of the
4349 /// controlling expression, or the expression in the default generic association
4350 /// if no types are compatible. For example:
4353 /// _Generic(X, double: 1, float: 2, default: 3)
4356 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4357 /// or 3 if "hello".
4359 /// As an extension, generic selections are allowed in C++, where the following
4360 /// additional semantics apply:
4362 /// Any generic selection whose controlling expression is type-dependent or
4363 /// which names a dependent type in its association list is result-dependent,
4364 /// which means that the choice of result expression is dependent.
4365 /// Result-dependent generic associations are both type- and value-dependent.
4366 class GenericSelectionExpr : public Expr {
4367 enum { CONTROLLING, END_EXPR };
4368 TypeSourceInfo **AssocTypes;
4370 unsigned NumAssocs, ResultIndex;
4371 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4374 GenericSelectionExpr(const ASTContext &Context,
4375 SourceLocation GenericLoc, Expr *ControllingExpr,
4376 ArrayRef<TypeSourceInfo*> AssocTypes,
4377 ArrayRef<Expr*> AssocExprs,
4378 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4379 bool ContainsUnexpandedParameterPack,
4380 unsigned ResultIndex);
4382 /// This constructor is used in the result-dependent case.
4383 GenericSelectionExpr(const ASTContext &Context,
4384 SourceLocation GenericLoc, Expr *ControllingExpr,
4385 ArrayRef<TypeSourceInfo*> AssocTypes,
4386 ArrayRef<Expr*> AssocExprs,
4387 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4388 bool ContainsUnexpandedParameterPack);
4390 explicit GenericSelectionExpr(EmptyShell Empty)
4391 : Expr(GenericSelectionExprClass, Empty) { }
4393 unsigned getNumAssocs() const { return NumAssocs; }
4395 SourceLocation getGenericLoc() const { return GenericLoc; }
4396 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4397 SourceLocation getRParenLoc() const { return RParenLoc; }
4399 const Expr *getAssocExpr(unsigned i) const {
4400 return cast<Expr>(SubExprs[END_EXPR+i]);
4402 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4404 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4405 return AssocTypes[i];
4407 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4409 QualType getAssocType(unsigned i) const {
4410 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4411 return TS->getType();
4416 const Expr *getControllingExpr() const {
4417 return cast<Expr>(SubExprs[CONTROLLING]);
4419 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4421 /// Whether this generic selection is result-dependent.
4422 bool isResultDependent() const { return ResultIndex == -1U; }
4424 /// The zero-based index of the result expression's generic association in
4425 /// the generic selection's association list. Defined only if the
4426 /// generic selection is not result-dependent.
4427 unsigned getResultIndex() const {
4428 assert(!isResultDependent() && "Generic selection is result-dependent");
4432 /// The generic selection's result expression. Defined only if the
4433 /// generic selection is not result-dependent.
4434 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4435 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4437 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4438 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4440 static bool classof(const Stmt *T) {
4441 return T->getStmtClass() == GenericSelectionExprClass;
4444 child_range children() {
4445 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4448 friend class ASTStmtReader;
4451 //===----------------------------------------------------------------------===//
4453 //===----------------------------------------------------------------------===//
4456 /// ExtVectorElementExpr - This represents access to specific elements of a
4457 /// vector, and may occur on the left hand side or right hand side. For example
4458 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4460 /// Note that the base may have either vector or pointer to vector type, just
4461 /// like a struct field reference.
4463 class ExtVectorElementExpr : public Expr {
4465 IdentifierInfo *Accessor;
4466 SourceLocation AccessorLoc;
4468 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4469 IdentifierInfo &accessor, SourceLocation loc)
4470 : Expr(ExtVectorElementExprClass, ty, VK,
4471 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4472 base->isTypeDependent(), base->isValueDependent(),
4473 base->isInstantiationDependent(),
4474 base->containsUnexpandedParameterPack()),
4475 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4477 /// \brief Build an empty vector element expression.
4478 explicit ExtVectorElementExpr(EmptyShell Empty)
4479 : Expr(ExtVectorElementExprClass, Empty) { }
4481 const Expr *getBase() const { return cast<Expr>(Base); }
4482 Expr *getBase() { return cast<Expr>(Base); }
4483 void setBase(Expr *E) { Base = E; }
4485 IdentifierInfo &getAccessor() const { return *Accessor; }
4486 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4488 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4489 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4491 /// getNumElements - Get the number of components being selected.
4492 unsigned getNumElements() const;
4494 /// containsDuplicateElements - Return true if any element access is
4496 bool containsDuplicateElements() const;
4498 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4499 /// aggregate Constant of ConstantInt(s).
4500 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4502 SourceLocation getLocStart() const LLVM_READONLY {
4503 return getBase()->getLocStart();
4505 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4507 /// isArrow - Return true if the base expression is a pointer to vector,
4508 /// return false if the base expression is a vector.
4509 bool isArrow() const;
4511 static bool classof(const Stmt *T) {
4512 return T->getStmtClass() == ExtVectorElementExprClass;
4516 child_range children() { return child_range(&Base, &Base+1); }
4520 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4521 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4522 class BlockExpr : public Expr {
4524 BlockDecl *TheBlock;
4526 BlockExpr(BlockDecl *BD, QualType ty)
4527 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4528 ty->isDependentType(), ty->isDependentType(),
4529 ty->isInstantiationDependentType() || BD->isDependentContext(),
4533 /// \brief Build an empty block expression.
4534 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4536 const BlockDecl *getBlockDecl() const { return TheBlock; }
4537 BlockDecl *getBlockDecl() { return TheBlock; }
4538 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4540 // Convenience functions for probing the underlying BlockDecl.
4541 SourceLocation getCaretLocation() const;
4542 const Stmt *getBody() const;
4545 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4546 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4548 /// getFunctionType - Return the underlying function type for this block.
4549 const FunctionProtoType *getFunctionType() const;
4551 static bool classof(const Stmt *T) {
4552 return T->getStmtClass() == BlockExprClass;
4556 child_range children() { return child_range(); }
4559 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4560 /// This AST node provides support for reinterpreting a type to another
4561 /// type of the same size.
4562 class AsTypeExpr : public Expr {
4565 SourceLocation BuiltinLoc, RParenLoc;
4567 friend class ASTReader;
4568 friend class ASTStmtReader;
4569 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4572 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4573 ExprValueKind VK, ExprObjectKind OK,
4574 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4575 : Expr(AsTypeExprClass, DstType, VK, OK,
4576 DstType->isDependentType(),
4577 DstType->isDependentType() || SrcExpr->isValueDependent(),
4578 (DstType->isInstantiationDependentType() ||
4579 SrcExpr->isInstantiationDependent()),
4580 (DstType->containsUnexpandedParameterPack() ||
4581 SrcExpr->containsUnexpandedParameterPack())),
4582 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4584 /// getSrcExpr - Return the Expr to be converted.
4585 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4587 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4588 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4590 /// getRParenLoc - Return the location of final right parenthesis.
4591 SourceLocation getRParenLoc() const { return RParenLoc; }
4593 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4594 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4596 static bool classof(const Stmt *T) {
4597 return T->getStmtClass() == AsTypeExprClass;
4601 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4604 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4605 /// l-value. A pseudo-object is an abstract object, accesses to which
4606 /// are translated to calls. The pseudo-object expression has a
4607 /// syntactic form, which shows how the expression was actually
4608 /// written in the source code, and a semantic form, which is a series
4609 /// of expressions to be executed in order which detail how the
4610 /// operation is actually evaluated. Optionally, one of the semantic
4611 /// forms may also provide a result value for the expression.
4613 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4614 /// that OVE is required to have a source expression, and it is bound
4615 /// to the result of that source expression. Such OVEs may appear
4616 /// only in subsequent semantic-form expressions and as
4617 /// sub-expressions of the syntactic form.
4619 /// PseudoObjectExpr should be used only when an operation can be
4620 /// usefully described in terms of fairly simple rewrite rules on
4621 /// objects and functions that are meant to be used by end-developers.
4622 /// For example, under the Itanium ABI, dynamic casts are implemented
4623 /// as a call to a runtime function called __dynamic_cast; using this
4624 /// class to describe that would be inappropriate because that call is
4625 /// not really part of the user-visible semantics, and instead the
4626 /// cast is properly reflected in the AST and IR-generation has been
4627 /// taught to generate the call as necessary. In contrast, an
4628 /// Objective-C property access is semantically defined to be
4629 /// equivalent to a particular message send, and this is very much
4630 /// part of the user model. The name of this class encourages this
4631 /// modelling design.
4632 class PseudoObjectExpr : public Expr {
4633 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4634 // Always at least two, because the first sub-expression is the
4637 // PseudoObjectExprBits.ResultIndex - The index of the
4638 // sub-expression holding the result. 0 means the result is void,
4639 // which is unambiguous because it's the index of the syntactic
4640 // form. Note that this is therefore 1 higher than the value passed
4641 // in to Create, which is an index within the semantic forms.
4642 // Note also that ASTStmtWriter assumes this encoding.
4644 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
4645 const Expr * const *getSubExprsBuffer() const {
4646 return reinterpret_cast<const Expr * const *>(this + 1);
4649 friend class ASTStmtReader;
4651 PseudoObjectExpr(QualType type, ExprValueKind VK,
4652 Expr *syntactic, ArrayRef<Expr*> semantic,
4653 unsigned resultIndex);
4655 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4657 unsigned getNumSubExprs() const {
4658 return PseudoObjectExprBits.NumSubExprs;
4662 /// NoResult - A value for the result index indicating that there is
4663 /// no semantic result.
4664 enum : unsigned { NoResult = ~0U };
4666 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4667 ArrayRef<Expr*> semantic,
4668 unsigned resultIndex);
4670 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4671 unsigned numSemanticExprs);
4673 /// Return the syntactic form of this expression, i.e. the
4674 /// expression it actually looks like. Likely to be expressed in
4675 /// terms of OpaqueValueExprs bound in the semantic form.
4676 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4677 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4679 /// Return the index of the result-bearing expression into the semantics
4680 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4681 unsigned getResultExprIndex() const {
4682 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4683 return PseudoObjectExprBits.ResultIndex - 1;
4686 /// Return the result-bearing expression, or null if there is none.
4687 Expr *getResultExpr() {
4688 if (PseudoObjectExprBits.ResultIndex == 0)
4690 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4692 const Expr *getResultExpr() const {
4693 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4696 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4698 typedef Expr * const *semantics_iterator;
4699 typedef const Expr * const *const_semantics_iterator;
4700 semantics_iterator semantics_begin() {
4701 return getSubExprsBuffer() + 1;
4703 const_semantics_iterator semantics_begin() const {
4704 return getSubExprsBuffer() + 1;
4706 semantics_iterator semantics_end() {
4707 return getSubExprsBuffer() + getNumSubExprs();
4709 const_semantics_iterator semantics_end() const {
4710 return getSubExprsBuffer() + getNumSubExprs();
4712 Expr *getSemanticExpr(unsigned index) {
4713 assert(index + 1 < getNumSubExprs());
4714 return getSubExprsBuffer()[index + 1];
4716 const Expr *getSemanticExpr(unsigned index) const {
4717 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4720 SourceLocation getExprLoc() const LLVM_READONLY {
4721 return getSyntacticForm()->getExprLoc();
4724 SourceLocation getLocStart() const LLVM_READONLY {
4725 return getSyntacticForm()->getLocStart();
4727 SourceLocation getLocEnd() const LLVM_READONLY {
4728 return getSyntacticForm()->getLocEnd();
4731 child_range children() {
4732 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4733 return child_range(cs, cs + getNumSubExprs());
4736 static bool classof(const Stmt *T) {
4737 return T->getStmtClass() == PseudoObjectExprClass;
4741 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4742 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4743 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4744 /// All of these instructions take one primary pointer and at least one memory
4746 class AtomicExpr : public Expr {
4749 #define BUILTIN(ID, TYPE, ATTRS)
4750 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4751 #include "clang/Basic/Builtins.def"
4752 // Avoid trailing comma
4756 // The ABI values for various atomic memory orderings.
4757 enum AtomicOrderingKind {
4758 AO_ABI_memory_order_relaxed = 0,
4759 AO_ABI_memory_order_consume = 1,
4760 AO_ABI_memory_order_acquire = 2,
4761 AO_ABI_memory_order_release = 3,
4762 AO_ABI_memory_order_acq_rel = 4,
4763 AO_ABI_memory_order_seq_cst = 5
4767 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4768 Stmt* SubExprs[END_EXPR];
4769 unsigned NumSubExprs;
4770 SourceLocation BuiltinLoc, RParenLoc;
4773 friend class ASTStmtReader;
4776 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4777 AtomicOp op, SourceLocation RP);
4779 /// \brief Determine the number of arguments the specified atomic builtin
4781 static unsigned getNumSubExprs(AtomicOp Op);
4783 /// \brief Build an empty AtomicExpr.
4784 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4786 Expr *getPtr() const {
4787 return cast<Expr>(SubExprs[PTR]);
4789 Expr *getOrder() const {
4790 return cast<Expr>(SubExprs[ORDER]);
4792 Expr *getVal1() const {
4793 if (Op == AO__c11_atomic_init)
4794 return cast<Expr>(SubExprs[ORDER]);
4795 assert(NumSubExprs > VAL1);
4796 return cast<Expr>(SubExprs[VAL1]);
4798 Expr *getOrderFail() const {
4799 assert(NumSubExprs > ORDER_FAIL);
4800 return cast<Expr>(SubExprs[ORDER_FAIL]);
4802 Expr *getVal2() const {
4803 if (Op == AO__atomic_exchange)
4804 return cast<Expr>(SubExprs[ORDER_FAIL]);
4805 assert(NumSubExprs > VAL2);
4806 return cast<Expr>(SubExprs[VAL2]);
4808 Expr *getWeak() const {
4809 assert(NumSubExprs > WEAK);
4810 return cast<Expr>(SubExprs[WEAK]);
4813 AtomicOp getOp() const { return Op; }
4814 unsigned getNumSubExprs() { return NumSubExprs; }
4816 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4818 bool isVolatile() const {
4819 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4822 bool isCmpXChg() const {
4823 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4824 getOp() == AO__c11_atomic_compare_exchange_weak ||
4825 getOp() == AO__atomic_compare_exchange ||
4826 getOp() == AO__atomic_compare_exchange_n;
4829 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4830 SourceLocation getRParenLoc() const { return RParenLoc; }
4832 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4833 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4835 static bool classof(const Stmt *T) {
4836 return T->getStmtClass() == AtomicExprClass;
4840 child_range children() {
4841 return child_range(SubExprs, SubExprs+NumSubExprs);
4844 } // end namespace clang